Skip to content

Instantly share code, notes, and snippets.

@magik6k
Created November 15, 2022 22:11
Show Gist options
  • Save magik6k/ada79bebc4f5ccf3078d72f6513a49e2 to your computer and use it in GitHub Desktop.
Save magik6k/ada79bebc4f5ccf3078d72f6513a49e2 to your computer and use it in GitHub Desktop.
This file has been truncated, but you can view the full file.
diff -Naur --color b/vendor/github.com/armon/go-metrics/const_unix.go a/vendor/github.com/armon/go-metrics/const_unix.go
--- b/vendor/github.com/armon/go-metrics/const_unix.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/armon/go-metrics/const_unix.go 2022-11-15 23:06:29.382015706 +0100
@@ -0,0 +1,12 @@
+// +build !windows
+
+package metrics
+
+import (
+ "syscall"
+)
+
+const (
+ // DefaultSignal is used with DefaultInmemSignal
+ DefaultSignal = syscall.SIGUSR1
+)
diff -Naur --color b/vendor/github.com/armon/go-metrics/const_windows.go a/vendor/github.com/armon/go-metrics/const_windows.go
--- b/vendor/github.com/armon/go-metrics/const_windows.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/armon/go-metrics/const_windows.go 2022-11-15 23:06:29.382015706 +0100
@@ -0,0 +1,13 @@
+// +build windows
+
+package metrics
+
+import (
+ "syscall"
+)
+
+const (
+ // DefaultSignal is used with DefaultInmemSignal
+ // Windows has no SIGUSR1, use SIGBREAK
+ DefaultSignal = syscall.Signal(21)
+)
diff -Naur --color b/vendor/github.com/armon/go-metrics/.gitignore a/vendor/github.com/armon/go-metrics/.gitignore
--- b/vendor/github.com/armon/go-metrics/.gitignore 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/armon/go-metrics/.gitignore 2022-11-15 23:06:29.378682308 +0100
@@ -0,0 +1,26 @@
+# Compiled Object files, Static and Dynamic libs (Shared Objects)
+*.o
+*.a
+*.so
+
+# Folders
+_obj
+_test
+
+# Architecture specific extensions/prefixes
+*.[568vq]
+[568vq].out
+
+*.cgo1.go
+*.cgo2.c
+_cgo_defun.c
+_cgo_gotypes.go
+_cgo_export.*
+
+_testmain.go
+
+*.exe
+
+/metrics.out
+
+.idea
diff -Naur --color b/vendor/github.com/armon/go-metrics/inmem_endpoint.go a/vendor/github.com/armon/go-metrics/inmem_endpoint.go
--- b/vendor/github.com/armon/go-metrics/inmem_endpoint.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/armon/go-metrics/inmem_endpoint.go 2022-11-15 23:06:29.382015706 +0100
@@ -0,0 +1,162 @@
+package metrics
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "sort"
+ "time"
+)
+
+// MetricsSummary holds a roll-up of metrics info for a given interval
+type MetricsSummary struct {
+ Timestamp string
+ Gauges []GaugeValue
+ Points []PointValue
+ Counters []SampledValue
+ Samples []SampledValue
+}
+
+type GaugeValue struct {
+ Name string
+ Hash string `json:"-"`
+ Value float32
+
+ Labels []Label `json:"-"`
+ DisplayLabels map[string]string `json:"Labels"`
+}
+
+type PointValue struct {
+ Name string
+ Points []float32
+}
+
+type SampledValue struct {
+ Name string
+ Hash string `json:"-"`
+ *AggregateSample
+ Mean float64
+ Stddev float64
+
+ Labels []Label `json:"-"`
+ DisplayLabels map[string]string `json:"Labels"`
+}
+
+// deepCopy allocates a new instance of AggregateSample
+func (source *SampledValue) deepCopy() SampledValue {
+ dest := *source
+ if source.AggregateSample != nil {
+ dest.AggregateSample = &AggregateSample{}
+ *dest.AggregateSample = *source.AggregateSample
+ }
+ return dest
+}
+
+// DisplayMetrics returns a summary of the metrics from the most recent finished interval.
+func (i *InmemSink) DisplayMetrics(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
+ data := i.Data()
+
+ var interval *IntervalMetrics
+ n := len(data)
+ switch {
+ case n == 0:
+ return nil, fmt.Errorf("no metric intervals have been initialized yet")
+ case n == 1:
+ // Show the current interval if it's all we have
+ interval = data[0]
+ default:
+ // Show the most recent finished interval if we have one
+ interval = data[n-2]
+ }
+
+ return newMetricSummaryFromInterval(interval), nil
+}
+
+func newMetricSummaryFromInterval(interval *IntervalMetrics) MetricsSummary {
+ interval.RLock()
+ defer interval.RUnlock()
+
+ summary := MetricsSummary{
+ Timestamp: interval.Interval.Round(time.Second).UTC().String(),
+ Gauges: make([]GaugeValue, 0, len(interval.Gauges)),
+ Points: make([]PointValue, 0, len(interval.Points)),
+ }
+
+ // Format and sort the output of each metric type, so it gets displayed in a
+ // deterministic order.
+ for name, points := range interval.Points {
+ summary.Points = append(summary.Points, PointValue{name, points})
+ }
+ sort.Slice(summary.Points, func(i, j int) bool {
+ return summary.Points[i].Name < summary.Points[j].Name
+ })
+
+ for hash, value := range interval.Gauges {
+ value.Hash = hash
+ value.DisplayLabels = make(map[string]string)
+ for _, label := range value.Labels {
+ value.DisplayLabels[label.Name] = label.Value
+ }
+ value.Labels = nil
+
+ summary.Gauges = append(summary.Gauges, value)
+ }
+ sort.Slice(summary.Gauges, func(i, j int) bool {
+ return summary.Gauges[i].Hash < summary.Gauges[j].Hash
+ })
+
+ summary.Counters = formatSamples(interval.Counters)
+ summary.Samples = formatSamples(interval.Samples)
+
+ return summary
+}
+
+func formatSamples(source map[string]SampledValue) []SampledValue {
+ output := make([]SampledValue, 0, len(source))
+ for hash, sample := range source {
+ displayLabels := make(map[string]string)
+ for _, label := range sample.Labels {
+ displayLabels[label.Name] = label.Value
+ }
+
+ output = append(output, SampledValue{
+ Name: sample.Name,
+ Hash: hash,
+ AggregateSample: sample.AggregateSample,
+ Mean: sample.AggregateSample.Mean(),
+ Stddev: sample.AggregateSample.Stddev(),
+ DisplayLabels: displayLabels,
+ })
+ }
+ sort.Slice(output, func(i, j int) bool {
+ return output[i].Hash < output[j].Hash
+ })
+
+ return output
+}
+
+type Encoder interface {
+ Encode(interface{}) error
+}
+
+// Stream writes metrics using encoder.Encode each time an interval ends. Runs
+// until the request context is cancelled, or the encoder returns an error.
+// The caller is responsible for logging any errors from encoder.
+func (i *InmemSink) Stream(ctx context.Context, encoder Encoder) {
+ interval := i.getInterval()
+
+ for {
+ select {
+ case <-interval.done:
+ summary := newMetricSummaryFromInterval(interval)
+ if err := encoder.Encode(summary); err != nil {
+ return
+ }
+
+ // update interval to the next one
+ interval = i.getInterval()
+ case <-ctx.Done():
+ return
+ }
+ }
+}
diff -Naur --color b/vendor/github.com/armon/go-metrics/inmem.go a/vendor/github.com/armon/go-metrics/inmem.go
--- b/vendor/github.com/armon/go-metrics/inmem.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/armon/go-metrics/inmem.go 2022-11-15 23:06:29.382015706 +0100
@@ -0,0 +1,339 @@
+package metrics
+
+import (
+ "bytes"
+ "fmt"
+ "math"
+ "net/url"
+ "strings"
+ "sync"
+ "time"
+)
+
+var spaceReplacer = strings.NewReplacer(" ", "_")
+
+// InmemSink provides a MetricSink that does in-memory aggregation
+// without sending metrics over a network. It can be embedded within
+// an application to provide profiling information.
+type InmemSink struct {
+ // How long is each aggregation interval
+ interval time.Duration
+
+ // Retain controls how many metrics interval we keep
+ retain time.Duration
+
+ // maxIntervals is the maximum length of intervals.
+ // It is retain / interval.
+ maxIntervals int
+
+ // intervals is a slice of the retained intervals
+ intervals []*IntervalMetrics
+ intervalLock sync.RWMutex
+
+ rateDenom float64
+}
+
+// IntervalMetrics stores the aggregated metrics
+// for a specific interval
+type IntervalMetrics struct {
+ sync.RWMutex
+
+ // The start time of the interval
+ Interval time.Time
+
+ // Gauges maps the key to the last set value
+ Gauges map[string]GaugeValue
+
+ // Points maps the string to the list of emitted values
+ // from EmitKey
+ Points map[string][]float32
+
+ // Counters maps the string key to a sum of the counter
+ // values
+ Counters map[string]SampledValue
+
+ // Samples maps the key to an AggregateSample,
+ // which has the rolled up view of a sample
+ Samples map[string]SampledValue
+
+ // done is closed when this interval has ended, and a new IntervalMetrics
+ // has been created to receive any future metrics.
+ done chan struct{}
+}
+
+// NewIntervalMetrics creates a new IntervalMetrics for a given interval
+func NewIntervalMetrics(intv time.Time) *IntervalMetrics {
+ return &IntervalMetrics{
+ Interval: intv,
+ Gauges: make(map[string]GaugeValue),
+ Points: make(map[string][]float32),
+ Counters: make(map[string]SampledValue),
+ Samples: make(map[string]SampledValue),
+ done: make(chan struct{}),
+ }
+}
+
+// AggregateSample is used to hold aggregate metrics
+// about a sample
+type AggregateSample struct {
+ Count int // The count of emitted pairs
+ Rate float64 // The values rate per time unit (usually 1 second)
+ Sum float64 // The sum of values
+ SumSq float64 `json:"-"` // The sum of squared values
+ Min float64 // Minimum value
+ Max float64 // Maximum value
+ LastUpdated time.Time `json:"-"` // When value was last updated
+}
+
+// Computes a Stddev of the values
+func (a *AggregateSample) Stddev() float64 {
+ num := (float64(a.Count) * a.SumSq) - math.Pow(a.Sum, 2)
+ div := float64(a.Count * (a.Count - 1))
+ if div == 0 {
+ return 0
+ }
+ return math.Sqrt(num / div)
+}
+
+// Computes a mean of the values
+func (a *AggregateSample) Mean() float64 {
+ if a.Count == 0 {
+ return 0
+ }
+ return a.Sum / float64(a.Count)
+}
+
+// Ingest is used to update a sample
+func (a *AggregateSample) Ingest(v float64, rateDenom float64) {
+ a.Count++
+ a.Sum += v
+ a.SumSq += (v * v)
+ if v < a.Min || a.Count == 1 {
+ a.Min = v
+ }
+ if v > a.Max || a.Count == 1 {
+ a.Max = v
+ }
+ a.Rate = float64(a.Sum) / rateDenom
+ a.LastUpdated = time.Now()
+}
+
+func (a *AggregateSample) String() string {
+ if a.Count == 0 {
+ return "Count: 0"
+ } else if a.Stddev() == 0 {
+ return fmt.Sprintf("Count: %d Sum: %0.3f LastUpdated: %s", a.Count, a.Sum, a.LastUpdated)
+ } else {
+ return fmt.Sprintf("Count: %d Min: %0.3f Mean: %0.3f Max: %0.3f Stddev: %0.3f Sum: %0.3f LastUpdated: %s",
+ a.Count, a.Min, a.Mean(), a.Max, a.Stddev(), a.Sum, a.LastUpdated)
+ }
+}
+
+// NewInmemSinkFromURL creates an InmemSink from a URL. It is used
+// (and tested) from NewMetricSinkFromURL.
+func NewInmemSinkFromURL(u *url.URL) (MetricSink, error) {
+ params := u.Query()
+
+ interval, err := time.ParseDuration(params.Get("interval"))
+ if err != nil {
+ return nil, fmt.Errorf("Bad 'interval' param: %s", err)
+ }
+
+ retain, err := time.ParseDuration(params.Get("retain"))
+ if err != nil {
+ return nil, fmt.Errorf("Bad 'retain' param: %s", err)
+ }
+
+ return NewInmemSink(interval, retain), nil
+}
+
+// NewInmemSink is used to construct a new in-memory sink.
+// Uses an aggregation interval and maximum retention period.
+func NewInmemSink(interval, retain time.Duration) *InmemSink {
+ rateTimeUnit := time.Second
+ i := &InmemSink{
+ interval: interval,
+ retain: retain,
+ maxIntervals: int(retain / interval),
+ rateDenom: float64(interval.Nanoseconds()) / float64(rateTimeUnit.Nanoseconds()),
+ }
+ i.intervals = make([]*IntervalMetrics, 0, i.maxIntervals)
+ return i
+}
+
+func (i *InmemSink) SetGauge(key []string, val float32) {
+ i.SetGaugeWithLabels(key, val, nil)
+}
+
+func (i *InmemSink) SetGaugeWithLabels(key []string, val float32, labels []Label) {
+ k, name := i.flattenKeyLabels(key, labels)
+ intv := i.getInterval()
+
+ intv.Lock()
+ defer intv.Unlock()
+ intv.Gauges[k] = GaugeValue{Name: name, Value: val, Labels: labels}
+}
+
+func (i *InmemSink) EmitKey(key []string, val float32) {
+ k := i.flattenKey(key)
+ intv := i.getInterval()
+
+ intv.Lock()
+ defer intv.Unlock()
+ vals := intv.Points[k]
+ intv.Points[k] = append(vals, val)
+}
+
+func (i *InmemSink) IncrCounter(key []string, val float32) {
+ i.IncrCounterWithLabels(key, val, nil)
+}
+
+func (i *InmemSink) IncrCounterWithLabels(key []string, val float32, labels []Label) {
+ k, name := i.flattenKeyLabels(key, labels)
+ intv := i.getInterval()
+
+ intv.Lock()
+ defer intv.Unlock()
+
+ agg, ok := intv.Counters[k]
+ if !ok {
+ agg = SampledValue{
+ Name: name,
+ AggregateSample: &AggregateSample{},
+ Labels: labels,
+ }
+ intv.Counters[k] = agg
+ }
+ agg.Ingest(float64(val), i.rateDenom)
+}
+
+func (i *InmemSink) AddSample(key []string, val float32) {
+ i.AddSampleWithLabels(key, val, nil)
+}
+
+func (i *InmemSink) AddSampleWithLabels(key []string, val float32, labels []Label) {
+ k, name := i.flattenKeyLabels(key, labels)
+ intv := i.getInterval()
+
+ intv.Lock()
+ defer intv.Unlock()
+
+ agg, ok := intv.Samples[k]
+ if !ok {
+ agg = SampledValue{
+ Name: name,
+ AggregateSample: &AggregateSample{},
+ Labels: labels,
+ }
+ intv.Samples[k] = agg
+ }
+ agg.Ingest(float64(val), i.rateDenom)
+}
+
+// Data is used to retrieve all the aggregated metrics
+// Intervals may be in use, and a read lock should be acquired
+func (i *InmemSink) Data() []*IntervalMetrics {
+ // Get the current interval, forces creation
+ i.getInterval()
+
+ i.intervalLock.RLock()
+ defer i.intervalLock.RUnlock()
+
+ n := len(i.intervals)
+ intervals := make([]*IntervalMetrics, n)
+
+ copy(intervals[:n-1], i.intervals[:n-1])
+ current := i.intervals[n-1]
+
+ // make its own copy for current interval
+ intervals[n-1] = &IntervalMetrics{}
+ copyCurrent := intervals[n-1]
+ current.RLock()
+ *copyCurrent = *current
+ // RWMutex is not safe to copy, so create a new instance on the copy
+ copyCurrent.RWMutex = sync.RWMutex{}
+
+ copyCurrent.Gauges = make(map[string]GaugeValue, len(current.Gauges))
+ for k, v := range current.Gauges {
+ copyCurrent.Gauges[k] = v
+ }
+ // saved values will be not change, just copy its link
+ copyCurrent.Points = make(map[string][]float32, len(current.Points))
+ for k, v := range current.Points {
+ copyCurrent.Points[k] = v
+ }
+ copyCurrent.Counters = make(map[string]SampledValue, len(current.Counters))
+ for k, v := range current.Counters {
+ copyCurrent.Counters[k] = v.deepCopy()
+ }
+ copyCurrent.Samples = make(map[string]SampledValue, len(current.Samples))
+ for k, v := range current.Samples {
+ copyCurrent.Samples[k] = v.deepCopy()
+ }
+ current.RUnlock()
+
+ return intervals
+}
+
+// getInterval returns the current interval. A new interval is created if no
+// previous interval exists, or if the current time is beyond the window for the
+// current interval.
+func (i *InmemSink) getInterval() *IntervalMetrics {
+ intv := time.Now().Truncate(i.interval)
+
+ // Attempt to return the existing interval first, because it only requires
+ // a read lock.
+ i.intervalLock.RLock()
+ n := len(i.intervals)
+ if n > 0 && i.intervals[n-1].Interval == intv {
+ defer i.intervalLock.RUnlock()
+ return i.intervals[n-1]
+ }
+ i.intervalLock.RUnlock()
+
+ i.intervalLock.Lock()
+ defer i.intervalLock.Unlock()
+
+ // Re-check for an existing interval now that the lock is re-acquired.
+ n = len(i.intervals)
+ if n > 0 && i.intervals[n-1].Interval == intv {
+ return i.intervals[n-1]
+ }
+
+ current := NewIntervalMetrics(intv)
+ i.intervals = append(i.intervals, current)
+ if n > 0 {
+ close(i.intervals[n-1].done)
+ }
+
+ n++
+ // Prune old intervals if the count exceeds the max.
+ if n >= i.maxIntervals {
+ copy(i.intervals[0:], i.intervals[n-i.maxIntervals:])
+ i.intervals = i.intervals[:i.maxIntervals]
+ }
+ return current
+}
+
+// Flattens the key for formatting, removes spaces
+func (i *InmemSink) flattenKey(parts []string) string {
+ buf := &bytes.Buffer{}
+
+ joined := strings.Join(parts, ".")
+
+ spaceReplacer.WriteString(buf, joined)
+
+ return buf.String()
+}
+
+// Flattens the key for formatting along with its labels, removes spaces
+func (i *InmemSink) flattenKeyLabels(parts []string, labels []Label) (string, string) {
+ key := i.flattenKey(parts)
+ buf := bytes.NewBufferString(key)
+
+ for _, label := range labels {
+ spaceReplacer.WriteString(buf, fmt.Sprintf(";%s=%s", label.Name, label.Value))
+ }
+
+ return buf.String(), key
+}
diff -Naur --color b/vendor/github.com/armon/go-metrics/inmem_signal.go a/vendor/github.com/armon/go-metrics/inmem_signal.go
--- b/vendor/github.com/armon/go-metrics/inmem_signal.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/armon/go-metrics/inmem_signal.go 2022-11-15 23:06:29.382015706 +0100
@@ -0,0 +1,117 @@
+package metrics
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "os"
+ "os/signal"
+ "strings"
+ "sync"
+ "syscall"
+)
+
+// InmemSignal is used to listen for a given signal, and when received,
+// to dump the current metrics from the InmemSink to an io.Writer
+type InmemSignal struct {
+ signal syscall.Signal
+ inm *InmemSink
+ w io.Writer
+ sigCh chan os.Signal
+
+ stop bool
+ stopCh chan struct{}
+ stopLock sync.Mutex
+}
+
+// NewInmemSignal creates a new InmemSignal which listens for a given signal,
+// and dumps the current metrics out to a writer
+func NewInmemSignal(inmem *InmemSink, sig syscall.Signal, w io.Writer) *InmemSignal {
+ i := &InmemSignal{
+ signal: sig,
+ inm: inmem,
+ w: w,
+ sigCh: make(chan os.Signal, 1),
+ stopCh: make(chan struct{}),
+ }
+ signal.Notify(i.sigCh, sig)
+ go i.run()
+ return i
+}
+
+// DefaultInmemSignal returns a new InmemSignal that responds to SIGUSR1
+// and writes output to stderr. Windows uses SIGBREAK
+func DefaultInmemSignal(inmem *InmemSink) *InmemSignal {
+ return NewInmemSignal(inmem, DefaultSignal, os.Stderr)
+}
+
+// Stop is used to stop the InmemSignal from listening
+func (i *InmemSignal) Stop() {
+ i.stopLock.Lock()
+ defer i.stopLock.Unlock()
+
+ if i.stop {
+ return
+ }
+ i.stop = true
+ close(i.stopCh)
+ signal.Stop(i.sigCh)
+}
+
+// run is a long running routine that handles signals
+func (i *InmemSignal) run() {
+ for {
+ select {
+ case <-i.sigCh:
+ i.dumpStats()
+ case <-i.stopCh:
+ return
+ }
+ }
+}
+
+// dumpStats is used to dump the data to output writer
+func (i *InmemSignal) dumpStats() {
+ buf := bytes.NewBuffer(nil)
+
+ data := i.inm.Data()
+ // Skip the last period which is still being aggregated
+ for j := 0; j < len(data)-1; j++ {
+ intv := data[j]
+ intv.RLock()
+ for _, val := range intv.Gauges {
+ name := i.flattenLabels(val.Name, val.Labels)
+ fmt.Fprintf(buf, "[%v][G] '%s': %0.3f\n", intv.Interval, name, val.Value)
+ }
+ for name, vals := range intv.Points {
+ for _, val := range vals {
+ fmt.Fprintf(buf, "[%v][P] '%s': %0.3f\n", intv.Interval, name, val)
+ }
+ }
+ for _, agg := range intv.Counters {
+ name := i.flattenLabels(agg.Name, agg.Labels)
+ fmt.Fprintf(buf, "[%v][C] '%s': %s\n", intv.Interval, name, agg.AggregateSample)
+ }
+ for _, agg := range intv.Samples {
+ name := i.flattenLabels(agg.Name, agg.Labels)
+ fmt.Fprintf(buf, "[%v][S] '%s': %s\n", intv.Interval, name, agg.AggregateSample)
+ }
+ intv.RUnlock()
+ }
+
+ // Write out the bytes
+ i.w.Write(buf.Bytes())
+}
+
+// Flattens the key for formatting along with its labels, removes spaces
+func (i *InmemSignal) flattenLabels(name string, labels []Label) string {
+ buf := bytes.NewBufferString(name)
+ replacer := strings.NewReplacer(" ", "_", ":", "_")
+
+ for _, label := range labels {
+ replacer.WriteString(buf, ".")
+ replacer.WriteString(buf, label.Value)
+ }
+
+ return buf.String()
+}
diff -Naur --color b/vendor/github.com/armon/go-metrics/LICENSE a/vendor/github.com/armon/go-metrics/LICENSE
--- b/vendor/github.com/armon/go-metrics/LICENSE 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/armon/go-metrics/LICENSE 2022-11-15 23:06:29.382015706 +0100
@@ -0,0 +1,20 @@
+The MIT License (MIT)
+
+Copyright (c) 2013 Armon Dadgar
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff -Naur --color b/vendor/github.com/armon/go-metrics/metrics.go a/vendor/github.com/armon/go-metrics/metrics.go
--- b/vendor/github.com/armon/go-metrics/metrics.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/armon/go-metrics/metrics.go 2022-11-15 23:06:29.382015706 +0100
@@ -0,0 +1,293 @@
+package metrics
+
+import (
+ "runtime"
+ "strings"
+ "time"
+
+ "github.com/hashicorp/go-immutable-radix"
+)
+
+type Label struct {
+ Name string
+ Value string
+}
+
+func (m *Metrics) SetGauge(key []string, val float32) {
+ m.SetGaugeWithLabels(key, val, nil)
+}
+
+func (m *Metrics) SetGaugeWithLabels(key []string, val float32, labels []Label) {
+ if m.HostName != "" {
+ if m.EnableHostnameLabel {
+ labels = append(labels, Label{"host", m.HostName})
+ } else if m.EnableHostname {
+ key = insert(0, m.HostName, key)
+ }
+ }
+ if m.EnableTypePrefix {
+ key = insert(0, "gauge", key)
+ }
+ if m.ServiceName != "" {
+ if m.EnableServiceLabel {
+ labels = append(labels, Label{"service", m.ServiceName})
+ } else {
+ key = insert(0, m.ServiceName, key)
+ }
+ }
+ allowed, labelsFiltered := m.allowMetric(key, labels)
+ if !allowed {
+ return
+ }
+ m.sink.SetGaugeWithLabels(key, val, labelsFiltered)
+}
+
+func (m *Metrics) EmitKey(key []string, val float32) {
+ if m.EnableTypePrefix {
+ key = insert(0, "kv", key)
+ }
+ if m.ServiceName != "" {
+ key = insert(0, m.ServiceName, key)
+ }
+ allowed, _ := m.allowMetric(key, nil)
+ if !allowed {
+ return
+ }
+ m.sink.EmitKey(key, val)
+}
+
+func (m *Metrics) IncrCounter(key []string, val float32) {
+ m.IncrCounterWithLabels(key, val, nil)
+}
+
+func (m *Metrics) IncrCounterWithLabels(key []string, val float32, labels []Label) {
+ if m.HostName != "" && m.EnableHostnameLabel {
+ labels = append(labels, Label{"host", m.HostName})
+ }
+ if m.EnableTypePrefix {
+ key = insert(0, "counter", key)
+ }
+ if m.ServiceName != "" {
+ if m.EnableServiceLabel {
+ labels = append(labels, Label{"service", m.ServiceName})
+ } else {
+ key = insert(0, m.ServiceName, key)
+ }
+ }
+ allowed, labelsFiltered := m.allowMetric(key, labels)
+ if !allowed {
+ return
+ }
+ m.sink.IncrCounterWithLabels(key, val, labelsFiltered)
+}
+
+func (m *Metrics) AddSample(key []string, val float32) {
+ m.AddSampleWithLabels(key, val, nil)
+}
+
+func (m *Metrics) AddSampleWithLabels(key []string, val float32, labels []Label) {
+ if m.HostName != "" && m.EnableHostnameLabel {
+ labels = append(labels, Label{"host", m.HostName})
+ }
+ if m.EnableTypePrefix {
+ key = insert(0, "sample", key)
+ }
+ if m.ServiceName != "" {
+ if m.EnableServiceLabel {
+ labels = append(labels, Label{"service", m.ServiceName})
+ } else {
+ key = insert(0, m.ServiceName, key)
+ }
+ }
+ allowed, labelsFiltered := m.allowMetric(key, labels)
+ if !allowed {
+ return
+ }
+ m.sink.AddSampleWithLabels(key, val, labelsFiltered)
+}
+
+func (m *Metrics) MeasureSince(key []string, start time.Time) {
+ m.MeasureSinceWithLabels(key, start, nil)
+}
+
+func (m *Metrics) MeasureSinceWithLabels(key []string, start time.Time, labels []Label) {
+ if m.HostName != "" && m.EnableHostnameLabel {
+ labels = append(labels, Label{"host", m.HostName})
+ }
+ if m.EnableTypePrefix {
+ key = insert(0, "timer", key)
+ }
+ if m.ServiceName != "" {
+ if m.EnableServiceLabel {
+ labels = append(labels, Label{"service", m.ServiceName})
+ } else {
+ key = insert(0, m.ServiceName, key)
+ }
+ }
+ allowed, labelsFiltered := m.allowMetric(key, labels)
+ if !allowed {
+ return
+ }
+ now := time.Now()
+ elapsed := now.Sub(start)
+ msec := float32(elapsed.Nanoseconds()) / float32(m.TimerGranularity)
+ m.sink.AddSampleWithLabels(key, msec, labelsFiltered)
+}
+
+// UpdateFilter overwrites the existing filter with the given rules.
+func (m *Metrics) UpdateFilter(allow, block []string) {
+ m.UpdateFilterAndLabels(allow, block, m.AllowedLabels, m.BlockedLabels)
+}
+
+// UpdateFilterAndLabels overwrites the existing filter with the given rules.
+func (m *Metrics) UpdateFilterAndLabels(allow, block, allowedLabels, blockedLabels []string) {
+ m.filterLock.Lock()
+ defer m.filterLock.Unlock()
+
+ m.AllowedPrefixes = allow
+ m.BlockedPrefixes = block
+
+ if allowedLabels == nil {
+ // Having a white list means we take only elements from it
+ m.allowedLabels = nil
+ } else {
+ m.allowedLabels = make(map[string]bool)
+ for _, v := range allowedLabels {
+ m.allowedLabels[v] = true
+ }
+ }
+ m.blockedLabels = make(map[string]bool)
+ for _, v := range blockedLabels {
+ m.blockedLabels[v] = true
+ }
+ m.AllowedLabels = allowedLabels
+ m.BlockedLabels = blockedLabels
+
+ m.filter = iradix.New()
+ for _, prefix := range m.AllowedPrefixes {
+ m.filter, _, _ = m.filter.Insert([]byte(prefix), true)
+ }
+ for _, prefix := range m.BlockedPrefixes {
+ m.filter, _, _ = m.filter.Insert([]byte(prefix), false)
+ }
+}
+
+// labelIsAllowed return true if a should be included in metric
+// the caller should lock m.filterLock while calling this method
+func (m *Metrics) labelIsAllowed(label *Label) bool {
+ labelName := (*label).Name
+ if m.blockedLabels != nil {
+ _, ok := m.blockedLabels[labelName]
+ if ok {
+ // If present, let's remove this label
+ return false
+ }
+ }
+ if m.allowedLabels != nil {
+ _, ok := m.allowedLabels[labelName]
+ return ok
+ }
+ // Allow by default
+ return true
+}
+
+// filterLabels return only allowed labels
+// the caller should lock m.filterLock while calling this method
+func (m *Metrics) filterLabels(labels []Label) []Label {
+ if labels == nil {
+ return nil
+ }
+ toReturn := []Label{}
+ for _, label := range labels {
+ if m.labelIsAllowed(&label) {
+ toReturn = append(toReturn, label)
+ }
+ }
+ return toReturn
+}
+
+// Returns whether the metric should be allowed based on configured prefix filters
+// Also return the applicable labels
+func (m *Metrics) allowMetric(key []string, labels []Label) (bool, []Label) {
+ m.filterLock.RLock()
+ defer m.filterLock.RUnlock()
+
+ if m.filter == nil || m.filter.Len() == 0 {
+ return m.Config.FilterDefault, m.filterLabels(labels)
+ }
+
+ _, allowed, ok := m.filter.Root().LongestPrefix([]byte(strings.Join(key, ".")))
+ if !ok {
+ return m.Config.FilterDefault, m.filterLabels(labels)
+ }
+
+ return allowed.(bool), m.filterLabels(labels)
+}
+
+// Periodically collects runtime stats to publish
+func (m *Metrics) collectStats() {
+ for {
+ time.Sleep(m.ProfileInterval)
+ m.EmitRuntimeStats()
+ }
+}
+
+// Emits various runtime statsitics
+func (m *Metrics) EmitRuntimeStats() {
+ // Export number of Goroutines
+ numRoutines := runtime.NumGoroutine()
+ m.SetGauge([]string{"runtime", "num_goroutines"}, float32(numRoutines))
+
+ // Export memory stats
+ var stats runtime.MemStats
+ runtime.ReadMemStats(&stats)
+ m.SetGauge([]string{"runtime", "alloc_bytes"}, float32(stats.Alloc))
+ m.SetGauge([]string{"runtime", "sys_bytes"}, float32(stats.Sys))
+ m.SetGauge([]string{"runtime", "malloc_count"}, float32(stats.Mallocs))
+ m.SetGauge([]string{"runtime", "free_count"}, float32(stats.Frees))
+ m.SetGauge([]string{"runtime", "heap_objects"}, float32(stats.HeapObjects))
+ m.SetGauge([]string{"runtime", "total_gc_pause_ns"}, float32(stats.PauseTotalNs))
+ m.SetGauge([]string{"runtime", "total_gc_runs"}, float32(stats.NumGC))
+
+ // Export info about the last few GC runs
+ num := stats.NumGC
+
+ // Handle wrap around
+ if num < m.lastNumGC {
+ m.lastNumGC = 0
+ }
+
+ // Ensure we don't scan more than 256
+ if num-m.lastNumGC >= 256 {
+ m.lastNumGC = num - 255
+ }
+
+ for i := m.lastNumGC; i < num; i++ {
+ pause := stats.PauseNs[i%256]
+ m.AddSample([]string{"runtime", "gc_pause_ns"}, float32(pause))
+ }
+ m.lastNumGC = num
+}
+
+// Creates a new slice with the provided string value as the first element
+// and the provided slice values as the remaining values.
+// Ordering of the values in the provided input slice is kept in tact in the output slice.
+func insert(i int, v string, s []string) []string {
+ // Allocate new slice to avoid modifying the input slice
+ newS := make([]string, len(s)+1)
+
+ // Copy s[0, i-1] into newS
+ for j := 0; j < i; j++ {
+ newS[j] = s[j]
+ }
+
+ // Insert provided element at index i
+ newS[i] = v
+
+ // Copy s[i, len(s)-1] into newS starting at newS[i+1]
+ for j := i; j < len(s); j++ {
+ newS[j+1] = s[j]
+ }
+
+ return newS
+}
diff -Naur --color b/vendor/github.com/armon/go-metrics/README.md a/vendor/github.com/armon/go-metrics/README.md
--- b/vendor/github.com/armon/go-metrics/README.md 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/armon/go-metrics/README.md 2022-11-15 23:06:29.382015706 +0100
@@ -0,0 +1,91 @@
+go-metrics
+==========
+
+This library provides a `metrics` package which can be used to instrument code,
+expose application metrics, and profile runtime performance in a flexible manner.
+
+Current API: [![GoDoc](https://godoc.org/github.com/armon/go-metrics?status.svg)](https://godoc.org/github.com/armon/go-metrics)
+
+Sinks
+-----
+
+The `metrics` package makes use of a `MetricSink` interface to support delivery
+to any type of backend. Currently the following sinks are provided:
+
+* StatsiteSink : Sinks to a [statsite](https://github.com/armon/statsite/) instance (TCP)
+* StatsdSink: Sinks to a [StatsD](https://github.com/etsy/statsd/) / statsite instance (UDP)
+* PrometheusSink: Sinks to a [Prometheus](http://prometheus.io/) metrics endpoint (exposed via HTTP for scrapes)
+* InmemSink : Provides in-memory aggregation, can be used to export stats
+* FanoutSink : Sinks to multiple sinks. Enables writing to multiple statsite instances for example.
+* BlackholeSink : Sinks to nowhere
+
+In addition to the sinks, the `InmemSignal` can be used to catch a signal,
+and dump a formatted output of recent metrics. For example, when a process gets
+a SIGUSR1, it can dump to stderr recent performance metrics for debugging.
+
+Labels
+------
+
+Most metrics do have an equivalent ending with `WithLabels`, such methods
+allow to push metrics with labels and use some features of underlying Sinks
+(ex: translated into Prometheus labels).
+
+Since some of these labels may increase greatly cardinality of metrics, the
+library allow to filter labels using a blacklist/whitelist filtering system
+which is global to all metrics.
+
+* If `Config.AllowedLabels` is not nil, then only labels specified in this value will be sent to underlying Sink, otherwise, all labels are sent by default.
+* If `Config.BlockedLabels` is not nil, any label specified in this value will not be sent to underlying Sinks.
+
+By default, both `Config.AllowedLabels` and `Config.BlockedLabels` are nil, meaning that
+no tags are filetered at all, but it allow to a user to globally block some tags with high
+cardinality at application level.
+
+Examples
+--------
+
+Here is an example of using the package:
+
+```go
+func SlowMethod() {
+ // Profiling the runtime of a method
+ defer metrics.MeasureSince([]string{"SlowMethod"}, time.Now())
+}
+
+// Configure a statsite sink as the global metrics sink
+sink, _ := metrics.NewStatsiteSink("statsite:8125")
+metrics.NewGlobal(metrics.DefaultConfig("service-name"), sink)
+
+// Emit a Key/Value pair
+metrics.EmitKey([]string{"questions", "meaning of life"}, 42)
+```
+
+Here is an example of setting up a signal handler:
+
+```go
+// Setup the inmem sink and signal handler
+inm := metrics.NewInmemSink(10*time.Second, time.Minute)
+sig := metrics.DefaultInmemSignal(inm)
+metrics.NewGlobal(metrics.DefaultConfig("service-name"), inm)
+
+// Run some code
+inm.SetGauge([]string{"foo"}, 42)
+inm.EmitKey([]string{"bar"}, 30)
+
+inm.IncrCounter([]string{"baz"}, 42)
+inm.IncrCounter([]string{"baz"}, 1)
+inm.IncrCounter([]string{"baz"}, 80)
+
+inm.AddSample([]string{"method", "wow"}, 42)
+inm.AddSample([]string{"method", "wow"}, 100)
+inm.AddSample([]string{"method", "wow"}, 22)
+
+....
+```
+
+When a signal comes in, output like the following will be dumped to stderr:
+
+ [2014-01-28 14:57:33.04 -0800 PST][G] 'foo': 42.000
+ [2014-01-28 14:57:33.04 -0800 PST][P] 'bar': 30.000
+ [2014-01-28 14:57:33.04 -0800 PST][C] 'baz': Count: 3 Min: 1.000 Mean: 41.000 Max: 80.000 Stddev: 39.509
+ [2014-01-28 14:57:33.04 -0800 PST][S] 'method.wow': Count: 3 Min: 22.000 Mean: 54.667 Max: 100.000 Stddev: 40.513
\ No newline at end of file
diff -Naur --color b/vendor/github.com/armon/go-metrics/sink.go a/vendor/github.com/armon/go-metrics/sink.go
--- b/vendor/github.com/armon/go-metrics/sink.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/armon/go-metrics/sink.go 2022-11-15 23:06:29.382015706 +0100
@@ -0,0 +1,115 @@
+package metrics
+
+import (
+ "fmt"
+ "net/url"
+)
+
+// The MetricSink interface is used to transmit metrics information
+// to an external system
+type MetricSink interface {
+ // A Gauge should retain the last value it is set to
+ SetGauge(key []string, val float32)
+ SetGaugeWithLabels(key []string, val float32, labels []Label)
+
+ // Should emit a Key/Value pair for each call
+ EmitKey(key []string, val float32)
+
+ // Counters should accumulate values
+ IncrCounter(key []string, val float32)
+ IncrCounterWithLabels(key []string, val float32, labels []Label)
+
+ // Samples are for timing information, where quantiles are used
+ AddSample(key []string, val float32)
+ AddSampleWithLabels(key []string, val float32, labels []Label)
+}
+
+// BlackholeSink is used to just blackhole messages
+type BlackholeSink struct{}
+
+func (*BlackholeSink) SetGauge(key []string, val float32) {}
+func (*BlackholeSink) SetGaugeWithLabels(key []string, val float32, labels []Label) {}
+func (*BlackholeSink) EmitKey(key []string, val float32) {}
+func (*BlackholeSink) IncrCounter(key []string, val float32) {}
+func (*BlackholeSink) IncrCounterWithLabels(key []string, val float32, labels []Label) {}
+func (*BlackholeSink) AddSample(key []string, val float32) {}
+func (*BlackholeSink) AddSampleWithLabels(key []string, val float32, labels []Label) {}
+
+// FanoutSink is used to sink to fanout values to multiple sinks
+type FanoutSink []MetricSink
+
+func (fh FanoutSink) SetGauge(key []string, val float32) {
+ fh.SetGaugeWithLabels(key, val, nil)
+}
+
+func (fh FanoutSink) SetGaugeWithLabels(key []string, val float32, labels []Label) {
+ for _, s := range fh {
+ s.SetGaugeWithLabels(key, val, labels)
+ }
+}
+
+func (fh FanoutSink) EmitKey(key []string, val float32) {
+ for _, s := range fh {
+ s.EmitKey(key, val)
+ }
+}
+
+func (fh FanoutSink) IncrCounter(key []string, val float32) {
+ fh.IncrCounterWithLabels(key, val, nil)
+}
+
+func (fh FanoutSink) IncrCounterWithLabels(key []string, val float32, labels []Label) {
+ for _, s := range fh {
+ s.IncrCounterWithLabels(key, val, labels)
+ }
+}
+
+func (fh FanoutSink) AddSample(key []string, val float32) {
+ fh.AddSampleWithLabels(key, val, nil)
+}
+
+func (fh FanoutSink) AddSampleWithLabels(key []string, val float32, labels []Label) {
+ for _, s := range fh {
+ s.AddSampleWithLabels(key, val, labels)
+ }
+}
+
+// sinkURLFactoryFunc is an generic interface around the *SinkFromURL() function provided
+// by each sink type
+type sinkURLFactoryFunc func(*url.URL) (MetricSink, error)
+
+// sinkRegistry supports the generic NewMetricSink function by mapping URL
+// schemes to metric sink factory functions
+var sinkRegistry = map[string]sinkURLFactoryFunc{
+ "statsd": NewStatsdSinkFromURL,
+ "statsite": NewStatsiteSinkFromURL,
+ "inmem": NewInmemSinkFromURL,
+}
+
+// NewMetricSinkFromURL allows a generic URL input to configure any of the
+// supported sinks. The scheme of the URL identifies the type of the sink, the
+// and query parameters are used to set options.
+//
+// "statsd://" - Initializes a StatsdSink. The host and port are passed through
+// as the "addr" of the sink
+//
+// "statsite://" - Initializes a StatsiteSink. The host and port become the
+// "addr" of the sink
+//
+// "inmem://" - Initializes an InmemSink. The host and port are ignored. The
+// "interval" and "duration" query parameters must be specified with valid
+// durations, see NewInmemSink for details.
+func NewMetricSinkFromURL(urlStr string) (MetricSink, error) {
+ u, err := url.Parse(urlStr)
+ if err != nil {
+ return nil, err
+ }
+
+ sinkURLFactoryFunc := sinkRegistry[u.Scheme]
+ if sinkURLFactoryFunc == nil {
+ return nil, fmt.Errorf(
+ "cannot create metric sink, unrecognized sink name: %q", u.Scheme)
+ }
+
+ return sinkURLFactoryFunc(u)
+}
diff -Naur --color b/vendor/github.com/armon/go-metrics/start.go a/vendor/github.com/armon/go-metrics/start.go
--- b/vendor/github.com/armon/go-metrics/start.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/armon/go-metrics/start.go 2022-11-15 23:06:29.382015706 +0100
@@ -0,0 +1,146 @@
+package metrics
+
+import (
+ "os"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ iradix "github.com/hashicorp/go-immutable-radix"
+)
+
+// Config is used to configure metrics settings
+type Config struct {
+ ServiceName string // Prefixed with keys to separate services
+ HostName string // Hostname to use. If not provided and EnableHostname, it will be os.Hostname
+ EnableHostname bool // Enable prefixing gauge values with hostname
+ EnableHostnameLabel bool // Enable adding hostname to labels
+ EnableServiceLabel bool // Enable adding service to labels
+ EnableRuntimeMetrics bool // Enables profiling of runtime metrics (GC, Goroutines, Memory)
+ EnableTypePrefix bool // Prefixes key with a type ("counter", "gauge", "timer")
+ TimerGranularity time.Duration // Granularity of timers.
+ ProfileInterval time.Duration // Interval to profile runtime metrics
+
+ AllowedPrefixes []string // A list of metric prefixes to allow, with '.' as the separator
+ BlockedPrefixes []string // A list of metric prefixes to block, with '.' as the separator
+ AllowedLabels []string // A list of metric labels to allow, with '.' as the separator
+ BlockedLabels []string // A list of metric labels to block, with '.' as the separator
+ FilterDefault bool // Whether to allow metrics by default
+}
+
+// Metrics represents an instance of a metrics sink that can
+// be used to emit
+type Metrics struct {
+ Config
+ lastNumGC uint32
+ sink MetricSink
+ filter *iradix.Tree
+ allowedLabels map[string]bool
+ blockedLabels map[string]bool
+ filterLock sync.RWMutex // Lock filters and allowedLabels/blockedLabels access
+}
+
+// Shared global metrics instance
+var globalMetrics atomic.Value // *Metrics
+
+func init() {
+ // Initialize to a blackhole sink to avoid errors
+ globalMetrics.Store(&Metrics{sink: &BlackholeSink{}})
+}
+
+// Default returns the shared global metrics instance.
+func Default() *Metrics {
+ return globalMetrics.Load().(*Metrics)
+}
+
+// DefaultConfig provides a sane default configuration
+func DefaultConfig(serviceName string) *Config {
+ c := &Config{
+ ServiceName: serviceName, // Use client provided service
+ HostName: "",
+ EnableHostname: true, // Enable hostname prefix
+ EnableRuntimeMetrics: true, // Enable runtime profiling
+ EnableTypePrefix: false, // Disable type prefix
+ TimerGranularity: time.Millisecond, // Timers are in milliseconds
+ ProfileInterval: time.Second, // Poll runtime every second
+ FilterDefault: true, // Don't filter metrics by default
+ }
+
+ // Try to get the hostname
+ name, _ := os.Hostname()
+ c.HostName = name
+ return c
+}
+
+// New is used to create a new instance of Metrics
+func New(conf *Config, sink MetricSink) (*Metrics, error) {
+ met := &Metrics{}
+ met.Config = *conf
+ met.sink = sink
+ met.UpdateFilterAndLabels(conf.AllowedPrefixes, conf.BlockedPrefixes, conf.AllowedLabels, conf.BlockedLabels)
+
+ // Start the runtime collector
+ if conf.EnableRuntimeMetrics {
+ go met.collectStats()
+ }
+ return met, nil
+}
+
+// NewGlobal is the same as New, but it assigns the metrics object to be
+// used globally as well as returning it.
+func NewGlobal(conf *Config, sink MetricSink) (*Metrics, error) {
+ metrics, err := New(conf, sink)
+ if err == nil {
+ globalMetrics.Store(metrics)
+ }
+ return metrics, err
+}
+
+// Proxy all the methods to the globalMetrics instance
+func SetGauge(key []string, val float32) {
+ globalMetrics.Load().(*Metrics).SetGauge(key, val)
+}
+
+func SetGaugeWithLabels(key []string, val float32, labels []Label) {
+ globalMetrics.Load().(*Metrics).SetGaugeWithLabels(key, val, labels)
+}
+
+func EmitKey(key []string, val float32) {
+ globalMetrics.Load().(*Metrics).EmitKey(key, val)
+}
+
+func IncrCounter(key []string, val float32) {
+ globalMetrics.Load().(*Metrics).IncrCounter(key, val)
+}
+
+func IncrCounterWithLabels(key []string, val float32, labels []Label) {
+ globalMetrics.Load().(*Metrics).IncrCounterWithLabels(key, val, labels)
+}
+
+func AddSample(key []string, val float32) {
+ globalMetrics.Load().(*Metrics).AddSample(key, val)
+}
+
+func AddSampleWithLabels(key []string, val float32, labels []Label) {
+ globalMetrics.Load().(*Metrics).AddSampleWithLabels(key, val, labels)
+}
+
+func MeasureSince(key []string, start time.Time) {
+ globalMetrics.Load().(*Metrics).MeasureSince(key, start)
+}
+
+func MeasureSinceWithLabels(key []string, start time.Time, labels []Label) {
+ globalMetrics.Load().(*Metrics).MeasureSinceWithLabels(key, start, labels)
+}
+
+func UpdateFilter(allow, block []string) {
+ globalMetrics.Load().(*Metrics).UpdateFilter(allow, block)
+}
+
+// UpdateFilterAndLabels set allow/block prefixes of metrics while allowedLabels
+// and blockedLabels - when not nil - allow filtering of labels in order to
+// block/allow globally labels (especially useful when having large number of
+// values for a given label). See README.md for more information about usage.
+func UpdateFilterAndLabels(allow, block, allowedLabels, blockedLabels []string) {
+ globalMetrics.Load().(*Metrics).UpdateFilterAndLabels(allow, block, allowedLabels, blockedLabels)
+}
diff -Naur --color b/vendor/github.com/armon/go-metrics/statsd.go a/vendor/github.com/armon/go-metrics/statsd.go
--- b/vendor/github.com/armon/go-metrics/statsd.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/armon/go-metrics/statsd.go 2022-11-15 23:06:29.382015706 +0100
@@ -0,0 +1,184 @@
+package metrics
+
+import (
+ "bytes"
+ "fmt"
+ "log"
+ "net"
+ "net/url"
+ "strings"
+ "time"
+)
+
+const (
+ // statsdMaxLen is the maximum size of a packet
+ // to send to statsd
+ statsdMaxLen = 1400
+)
+
+// StatsdSink provides a MetricSink that can be used
+// with a statsite or statsd metrics server. It uses
+// only UDP packets, while StatsiteSink uses TCP.
+type StatsdSink struct {
+ addr string
+ metricQueue chan string
+}
+
+// NewStatsdSinkFromURL creates an StatsdSink from a URL. It is used
+// (and tested) from NewMetricSinkFromURL.
+func NewStatsdSinkFromURL(u *url.URL) (MetricSink, error) {
+ return NewStatsdSink(u.Host)
+}
+
+// NewStatsdSink is used to create a new StatsdSink
+func NewStatsdSink(addr string) (*StatsdSink, error) {
+ s := &StatsdSink{
+ addr: addr,
+ metricQueue: make(chan string, 4096),
+ }
+ go s.flushMetrics()
+ return s, nil
+}
+
+// Close is used to stop flushing to statsd
+func (s *StatsdSink) Shutdown() {
+ close(s.metricQueue)
+}
+
+func (s *StatsdSink) SetGauge(key []string, val float32) {
+ flatKey := s.flattenKey(key)
+ s.pushMetric(fmt.Sprintf("%s:%f|g\n", flatKey, val))
+}
+
+func (s *StatsdSink) SetGaugeWithLabels(key []string, val float32, labels []Label) {
+ flatKey := s.flattenKeyLabels(key, labels)
+ s.pushMetric(fmt.Sprintf("%s:%f|g\n", flatKey, val))
+}
+
+func (s *StatsdSink) EmitKey(key []string, val float32) {
+ flatKey := s.flattenKey(key)
+ s.pushMetric(fmt.Sprintf("%s:%f|kv\n", flatKey, val))
+}
+
+func (s *StatsdSink) IncrCounter(key []string, val float32) {
+ flatKey := s.flattenKey(key)
+ s.pushMetric(fmt.Sprintf("%s:%f|c\n", flatKey, val))
+}
+
+func (s *StatsdSink) IncrCounterWithLabels(key []string, val float32, labels []Label) {
+ flatKey := s.flattenKeyLabels(key, labels)
+ s.pushMetric(fmt.Sprintf("%s:%f|c\n", flatKey, val))
+}
+
+func (s *StatsdSink) AddSample(key []string, val float32) {
+ flatKey := s.flattenKey(key)
+ s.pushMetric(fmt.Sprintf("%s:%f|ms\n", flatKey, val))
+}
+
+func (s *StatsdSink) AddSampleWithLabels(key []string, val float32, labels []Label) {
+ flatKey := s.flattenKeyLabels(key, labels)
+ s.pushMetric(fmt.Sprintf("%s:%f|ms\n", flatKey, val))
+}
+
+// Flattens the key for formatting, removes spaces
+func (s *StatsdSink) flattenKey(parts []string) string {
+ joined := strings.Join(parts, ".")
+ return strings.Map(func(r rune) rune {
+ switch r {
+ case ':':
+ fallthrough
+ case ' ':
+ return '_'
+ default:
+ return r
+ }
+ }, joined)
+}
+
+// Flattens the key along with labels for formatting, removes spaces
+func (s *StatsdSink) flattenKeyLabels(parts []string, labels []Label) string {
+ for _, label := range labels {
+ parts = append(parts, label.Value)
+ }
+ return s.flattenKey(parts)
+}
+
+// Does a non-blocking push to the metrics queue
+func (s *StatsdSink) pushMetric(m string) {
+ select {
+ case s.metricQueue <- m:
+ default:
+ }
+}
+
+// Flushes metrics
+func (s *StatsdSink) flushMetrics() {
+ var sock net.Conn
+ var err error
+ var wait <-chan time.Time
+ ticker := time.NewTicker(flushInterval)
+ defer ticker.Stop()
+
+CONNECT:
+ // Create a buffer
+ buf := bytes.NewBuffer(nil)
+
+ // Attempt to connect
+ sock, err = net.Dial("udp", s.addr)
+ if err != nil {
+ log.Printf("[ERR] Error connecting to statsd! Err: %s", err)
+ goto WAIT
+ }
+
+ for {
+ select {
+ case metric, ok := <-s.metricQueue:
+ // Get a metric from the queue
+ if !ok {
+ goto QUIT
+ }
+
+ // Check if this would overflow the packet size
+ if len(metric)+buf.Len() > statsdMaxLen {
+ _, err := sock.Write(buf.Bytes())
+ buf.Reset()
+ if err != nil {
+ log.Printf("[ERR] Error writing to statsd! Err: %s", err)
+ goto WAIT
+ }
+ }
+
+ // Append to the buffer
+ buf.WriteString(metric)
+
+ case <-ticker.C:
+ if buf.Len() == 0 {
+ continue
+ }
+
+ _, err := sock.Write(buf.Bytes())
+ buf.Reset()
+ if err != nil {
+ log.Printf("[ERR] Error flushing to statsd! Err: %s", err)
+ goto WAIT
+ }
+ }
+ }
+
+WAIT:
+ // Wait for a while
+ wait = time.After(time.Duration(5) * time.Second)
+ for {
+ select {
+ // Dequeue the messages to avoid backlog
+ case _, ok := <-s.metricQueue:
+ if !ok {
+ goto QUIT
+ }
+ case <-wait:
+ goto CONNECT
+ }
+ }
+QUIT:
+ s.metricQueue = nil
+}
diff -Naur --color b/vendor/github.com/armon/go-metrics/statsite.go a/vendor/github.com/armon/go-metrics/statsite.go
--- b/vendor/github.com/armon/go-metrics/statsite.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/armon/go-metrics/statsite.go 2022-11-15 23:06:29.382015706 +0100
@@ -0,0 +1,172 @@
+package metrics
+
+import (
+ "bufio"
+ "fmt"
+ "log"
+ "net"
+ "net/url"
+ "strings"
+ "time"
+)
+
+const (
+ // We force flush the statsite metrics after this period of
+ // inactivity. Prevents stats from getting stuck in a buffer
+ // forever.
+ flushInterval = 100 * time.Millisecond
+)
+
+// NewStatsiteSinkFromURL creates an StatsiteSink from a URL. It is used
+// (and tested) from NewMetricSinkFromURL.
+func NewStatsiteSinkFromURL(u *url.URL) (MetricSink, error) {
+ return NewStatsiteSink(u.Host)
+}
+
+// StatsiteSink provides a MetricSink that can be used with a
+// statsite metrics server
+type StatsiteSink struct {
+ addr string
+ metricQueue chan string
+}
+
+// NewStatsiteSink is used to create a new StatsiteSink
+func NewStatsiteSink(addr string) (*StatsiteSink, error) {
+ s := &StatsiteSink{
+ addr: addr,
+ metricQueue: make(chan string, 4096),
+ }
+ go s.flushMetrics()
+ return s, nil
+}
+
+// Close is used to stop flushing to statsite
+func (s *StatsiteSink) Shutdown() {
+ close(s.metricQueue)
+}
+
+func (s *StatsiteSink) SetGauge(key []string, val float32) {
+ flatKey := s.flattenKey(key)
+ s.pushMetric(fmt.Sprintf("%s:%f|g\n", flatKey, val))
+}
+
+func (s *StatsiteSink) SetGaugeWithLabels(key []string, val float32, labels []Label) {
+ flatKey := s.flattenKeyLabels(key, labels)
+ s.pushMetric(fmt.Sprintf("%s:%f|g\n", flatKey, val))
+}
+
+func (s *StatsiteSink) EmitKey(key []string, val float32) {
+ flatKey := s.flattenKey(key)
+ s.pushMetric(fmt.Sprintf("%s:%f|kv\n", flatKey, val))
+}
+
+func (s *StatsiteSink) IncrCounter(key []string, val float32) {
+ flatKey := s.flattenKey(key)
+ s.pushMetric(fmt.Sprintf("%s:%f|c\n", flatKey, val))
+}
+
+func (s *StatsiteSink) IncrCounterWithLabels(key []string, val float32, labels []Label) {
+ flatKey := s.flattenKeyLabels(key, labels)
+ s.pushMetric(fmt.Sprintf("%s:%f|c\n", flatKey, val))
+}
+
+func (s *StatsiteSink) AddSample(key []string, val float32) {
+ flatKey := s.flattenKey(key)
+ s.pushMetric(fmt.Sprintf("%s:%f|ms\n", flatKey, val))
+}
+
+func (s *StatsiteSink) AddSampleWithLabels(key []string, val float32, labels []Label) {
+ flatKey := s.flattenKeyLabels(key, labels)
+ s.pushMetric(fmt.Sprintf("%s:%f|ms\n", flatKey, val))
+}
+
+// Flattens the key for formatting, removes spaces
+func (s *StatsiteSink) flattenKey(parts []string) string {
+ joined := strings.Join(parts, ".")
+ return strings.Map(func(r rune) rune {
+ switch r {
+ case ':':
+ fallthrough
+ case ' ':
+ return '_'
+ default:
+ return r
+ }
+ }, joined)
+}
+
+// Flattens the key along with labels for formatting, removes spaces
+func (s *StatsiteSink) flattenKeyLabels(parts []string, labels []Label) string {
+ for _, label := range labels {
+ parts = append(parts, label.Value)
+ }
+ return s.flattenKey(parts)
+}
+
+// Does a non-blocking push to the metrics queue
+func (s *StatsiteSink) pushMetric(m string) {
+ select {
+ case s.metricQueue <- m:
+ default:
+ }
+}
+
+// Flushes metrics
+func (s *StatsiteSink) flushMetrics() {
+ var sock net.Conn
+ var err error
+ var wait <-chan time.Time
+ var buffered *bufio.Writer
+ ticker := time.NewTicker(flushInterval)
+ defer ticker.Stop()
+
+CONNECT:
+ // Attempt to connect
+ sock, err = net.Dial("tcp", s.addr)
+ if err != nil {
+ log.Printf("[ERR] Error connecting to statsite! Err: %s", err)
+ goto WAIT
+ }
+
+ // Create a buffered writer
+ buffered = bufio.NewWriter(sock)
+
+ for {
+ select {
+ case metric, ok := <-s.metricQueue:
+ // Get a metric from the queue
+ if !ok {
+ goto QUIT
+ }
+
+ // Try to send to statsite
+ _, err := buffered.Write([]byte(metric))
+ if err != nil {
+ log.Printf("[ERR] Error writing to statsite! Err: %s", err)
+ goto WAIT
+ }
+ case <-ticker.C:
+ if err := buffered.Flush(); err != nil {
+ log.Printf("[ERR] Error flushing to statsite! Err: %s", err)
+ goto WAIT
+ }
+ }
+ }
+
+WAIT:
+ // Wait for a while
+ wait = time.After(time.Duration(5) * time.Second)
+ for {
+ select {
+ // Dequeue the messages to avoid backlog
+ case _, ok := <-s.metricQueue:
+ if !ok {
+ goto QUIT
+ }
+ case <-wait:
+ goto CONNECT
+ }
+ }
+QUIT:
+ s.metricQueue = nil
+}
diff -Naur --color b/vendor/github.com/armon/go-metrics/.travis.yml a/vendor/github.com/armon/go-metrics/.travis.yml
--- b/vendor/github.com/armon/go-metrics/.travis.yml 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/armon/go-metrics/.travis.yml 2022-11-15 23:06:29.378682308 +0100
@@ -0,0 +1,13 @@
+language: go
+
+go:
+ - "1.x"
+
+env:
+ - GO111MODULE=on
+
+install:
+ - go get ./...
+
+script:
+ - go test ./...
diff -Naur --color b/vendor/github.com/boltdb/bolt/appveyor.yml a/vendor/github.com/boltdb/bolt/appveyor.yml
--- b/vendor/github.com/boltdb/bolt/appveyor.yml 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/boltdb/bolt/appveyor.yml 2022-11-15 23:06:29.392015899 +0100
@@ -0,0 +1,18 @@
+version: "{build}"
+
+os: Windows Server 2012 R2
+
+clone_folder: c:\gopath\src\github.com\boltdb\bolt
+
+environment:
+ GOPATH: c:\gopath
+
+install:
+ - echo %PATH%
+ - echo %GOPATH%
+ - go version
+ - go env
+ - go get -v -t ./...
+
+build_script:
+ - go test -v ./...
diff -Naur --color b/vendor/github.com/boltdb/bolt/bolt_386.go a/vendor/github.com/boltdb/bolt/bolt_386.go
--- b/vendor/github.com/boltdb/bolt/bolt_386.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/boltdb/bolt/bolt_386.go 2022-11-15 23:06:29.392015899 +0100
@@ -0,0 +1,10 @@
+package bolt
+
+// maxMapSize represents the largest mmap size supported by Bolt.
+const maxMapSize = 0x7FFFFFFF // 2GB
+
+// maxAllocSize is the size used when creating array pointers.
+const maxAllocSize = 0xFFFFFFF
+
+// Are unaligned load/stores broken on this arch?
+var brokenUnaligned = false
diff -Naur --color b/vendor/github.com/boltdb/bolt/bolt_amd64.go a/vendor/github.com/boltdb/bolt/bolt_amd64.go
--- b/vendor/github.com/boltdb/bolt/bolt_amd64.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/boltdb/bolt/bolt_amd64.go 2022-11-15 23:06:29.392015899 +0100
@@ -0,0 +1,10 @@
+package bolt
+
+// maxMapSize represents the largest mmap size supported by Bolt.
+const maxMapSize = 0xFFFFFFFFFFFF // 256TB
+
+// maxAllocSize is the size used when creating array pointers.
+const maxAllocSize = 0x7FFFFFFF
+
+// Are unaligned load/stores broken on this arch?
+var brokenUnaligned = false
diff -Naur --color b/vendor/github.com/boltdb/bolt/bolt_arm64.go a/vendor/github.com/boltdb/bolt/bolt_arm64.go
--- b/vendor/github.com/boltdb/bolt/bolt_arm64.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/boltdb/bolt/bolt_arm64.go 2022-11-15 23:06:29.392015899 +0100
@@ -0,0 +1,12 @@
+// +build arm64
+
+package bolt
+
+// maxMapSize represents the largest mmap size supported by Bolt.
+const maxMapSize = 0xFFFFFFFFFFFF // 256TB
+
+// maxAllocSize is the size used when creating array pointers.
+const maxAllocSize = 0x7FFFFFFF
+
+// Are unaligned load/stores broken on this arch?
+var brokenUnaligned = false
diff -Naur --color b/vendor/github.com/boltdb/bolt/bolt_arm.go a/vendor/github.com/boltdb/bolt/bolt_arm.go
--- b/vendor/github.com/boltdb/bolt/bolt_arm.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/boltdb/bolt/bolt_arm.go 2022-11-15 23:06:29.392015899 +0100
@@ -0,0 +1,28 @@
+package bolt
+
+import "unsafe"
+
+// maxMapSize represents the largest mmap size supported by Bolt.
+const maxMapSize = 0x7FFFFFFF // 2GB
+
+// maxAllocSize is the size used when creating array pointers.
+const maxAllocSize = 0xFFFFFFF
+
+// Are unaligned load/stores broken on this arch?
+var brokenUnaligned bool
+
+func init() {
+ // Simple check to see whether this arch handles unaligned load/stores
+ // correctly.
+
+ // ARM9 and older devices require load/stores to be from/to aligned
+ // addresses. If not, the lower 2 bits are cleared and that address is
+ // read in a jumbled up order.
+
+ // See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.faqs/ka15414.html
+
+ raw := [6]byte{0xfe, 0xef, 0x11, 0x22, 0x22, 0x11}
+ val := *(*uint32)(unsafe.Pointer(uintptr(unsafe.Pointer(&raw)) + 2))
+
+ brokenUnaligned = val != 0x11222211
+}
diff -Naur --color b/vendor/github.com/boltdb/bolt/bolt_linux.go a/vendor/github.com/boltdb/bolt/bolt_linux.go
--- b/vendor/github.com/boltdb/bolt/bolt_linux.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/boltdb/bolt/bolt_linux.go 2022-11-15 23:06:29.392015899 +0100
@@ -0,0 +1,10 @@
+package bolt
+
+import (
+ "syscall"
+)
+
+// fdatasync flushes written data to a file descriptor.
+func fdatasync(db *DB) error {
+ return syscall.Fdatasync(int(db.file.Fd()))
+}
diff -Naur --color b/vendor/github.com/boltdb/bolt/bolt_openbsd.go a/vendor/github.com/boltdb/bolt/bolt_openbsd.go
--- b/vendor/github.com/boltdb/bolt/bolt_openbsd.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/boltdb/bolt/bolt_openbsd.go 2022-11-15 23:06:29.392015899 +0100
@@ -0,0 +1,27 @@
+package bolt
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+const (
+ msAsync = 1 << iota // perform asynchronous writes
+ msSync // perform synchronous writes
+ msInvalidate // invalidate cached data
+)
+
+func msync(db *DB) error {
+ _, _, errno := syscall.Syscall(syscall.SYS_MSYNC, uintptr(unsafe.Pointer(db.data)), uintptr(db.datasz), msInvalidate)
+ if errno != 0 {
+ return errno
+ }
+ return nil
+}
+
+func fdatasync(db *DB) error {
+ if db.data != nil {
+ return msync(db)
+ }
+ return db.file.Sync()
+}
diff -Naur --color b/vendor/github.com/boltdb/bolt/bolt_ppc64.go a/vendor/github.com/boltdb/bolt/bolt_ppc64.go
--- b/vendor/github.com/boltdb/bolt/bolt_ppc64.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/boltdb/bolt/bolt_ppc64.go 2022-11-15 23:06:29.392015899 +0100
@@ -0,0 +1,12 @@
+// +build ppc64
+
+package bolt
+
+// maxMapSize represents the largest mmap size supported by Bolt.
+const maxMapSize = 0xFFFFFFFFFFFF // 256TB
+
+// maxAllocSize is the size used when creating array pointers.
+const maxAllocSize = 0x7FFFFFFF
+
+// Are unaligned load/stores broken on this arch?
+var brokenUnaligned = false
diff -Naur --color b/vendor/github.com/boltdb/bolt/bolt_ppc64le.go a/vendor/github.com/boltdb/bolt/bolt_ppc64le.go
--- b/vendor/github.com/boltdb/bolt/bolt_ppc64le.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/boltdb/bolt/bolt_ppc64le.go 2022-11-15 23:06:29.392015899 +0100
@@ -0,0 +1,12 @@
+// +build ppc64le
+
+package bolt
+
+// maxMapSize represents the largest mmap size supported by Bolt.
+const maxMapSize = 0xFFFFFFFFFFFF // 256TB
+
+// maxAllocSize is the size used when creating array pointers.
+const maxAllocSize = 0x7FFFFFFF
+
+// Are unaligned load/stores broken on this arch?
+var brokenUnaligned = false
diff -Naur --color b/vendor/github.com/boltdb/bolt/bolt_ppc.go a/vendor/github.com/boltdb/bolt/bolt_ppc.go
--- b/vendor/github.com/boltdb/bolt/bolt_ppc.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/boltdb/bolt/bolt_ppc.go 2022-11-15 23:06:29.392015899 +0100
@@ -0,0 +1,9 @@
+// +build ppc
+
+package bolt
+
+// maxMapSize represents the largest mmap size supported by Bolt.
+const maxMapSize = 0x7FFFFFFF // 2GB
+
+// maxAllocSize is the size used when creating array pointers.
+const maxAllocSize = 0xFFFFFFF
diff -Naur --color b/vendor/github.com/boltdb/bolt/bolt_s390x.go a/vendor/github.com/boltdb/bolt/bolt_s390x.go
--- b/vendor/github.com/boltdb/bolt/bolt_s390x.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/boltdb/bolt/bolt_s390x.go 2022-11-15 23:06:29.392015899 +0100
@@ -0,0 +1,12 @@
+// +build s390x
+
+package bolt
+
+// maxMapSize represents the largest mmap size supported by Bolt.
+const maxMapSize = 0xFFFFFFFFFFFF // 256TB
+
+// maxAllocSize is the size used when creating array pointers.
+const maxAllocSize = 0x7FFFFFFF
+
+// Are unaligned load/stores broken on this arch?
+var brokenUnaligned = false
diff -Naur --color b/vendor/github.com/boltdb/bolt/boltsync_unix.go a/vendor/github.com/boltdb/bolt/boltsync_unix.go
--- b/vendor/github.com/boltdb/bolt/boltsync_unix.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/boltdb/bolt/boltsync_unix.go 2022-11-15 23:06:29.392015899 +0100
@@ -0,0 +1,8 @@
+// +build !windows,!plan9,!linux,!openbsd
+
+package bolt
+
+// fdatasync flushes written data to a file descriptor.
+func fdatasync(db *DB) error {
+ return db.file.Sync()
+}
diff -Naur --color b/vendor/github.com/boltdb/bolt/bolt_unix.go a/vendor/github.com/boltdb/bolt/bolt_unix.go
--- b/vendor/github.com/boltdb/bolt/bolt_unix.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/boltdb/bolt/bolt_unix.go 2022-11-15 23:06:29.392015899 +0100
@@ -0,0 +1,89 @@
+// +build !windows,!plan9,!solaris
+
+package bolt
+
+import (
+ "fmt"
+ "os"
+ "syscall"
+ "time"
+ "unsafe"
+)
+
+// flock acquires an advisory lock on a file descriptor.
+func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Duration) error {
+ var t time.Time
+ for {
+ // If we're beyond our timeout then return an error.
+ // This can only occur after we've attempted a flock once.
+ if t.IsZero() {
+ t = time.Now()
+ } else if timeout > 0 && time.Since(t) > timeout {
+ return ErrTimeout
+ }
+ flag := syscall.LOCK_SH
+ if exclusive {
+ flag = syscall.LOCK_EX
+ }
+
+ // Otherwise attempt to obtain an exclusive lock.
+ err := syscall.Flock(int(db.file.Fd()), flag|syscall.LOCK_NB)
+ if err == nil {
+ return nil
+ } else if err != syscall.EWOULDBLOCK {
+ return err
+ }
+
+ // Wait for a bit and try again.
+ time.Sleep(50 * time.Millisecond)
+ }
+}
+
+// funlock releases an advisory lock on a file descriptor.
+func funlock(db *DB) error {
+ return syscall.Flock(int(db.file.Fd()), syscall.LOCK_UN)
+}
+
+// mmap memory maps a DB's data file.
+func mmap(db *DB, sz int) error {
+ // Map the data file to memory.
+ b, err := syscall.Mmap(int(db.file.Fd()), 0, sz, syscall.PROT_READ, syscall.MAP_SHARED|db.MmapFlags)
+ if err != nil {
+ return err
+ }
+
+ // Advise the kernel that the mmap is accessed randomly.
+ if err := madvise(b, syscall.MADV_RANDOM); err != nil {
+ return fmt.Errorf("madvise: %s", err)
+ }
+
+ // Save the original byte slice and convert to a byte array pointer.
+ db.dataref = b
+ db.data = (*[maxMapSize]byte)(unsafe.Pointer(&b[0]))
+ db.datasz = sz
+ return nil
+}
+
+// munmap unmaps a DB's data file from memory.
+func munmap(db *DB) error {
+ // Ignore the unmap if we have no mapped data.
+ if db.dataref == nil {
+ return nil
+ }
+
+ // Unmap using the original byte slice.
+ err := syscall.Munmap(db.dataref)
+ db.dataref = nil
+ db.data = nil
+ db.datasz = 0
+ return err
+}
+
+// NOTE: This function is copied from stdlib because it is not available on darwin.
+func madvise(b []byte, advice int) (err error) {
+ _, _, e1 := syscall.Syscall(syscall.SYS_MADVISE, uintptr(unsafe.Pointer(&b[0])), uintptr(len(b)), uintptr(advice))
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
diff -Naur --color b/vendor/github.com/boltdb/bolt/bolt_unix_solaris.go a/vendor/github.com/boltdb/bolt/bolt_unix_solaris.go
--- b/vendor/github.com/boltdb/bolt/bolt_unix_solaris.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/boltdb/bolt/bolt_unix_solaris.go 2022-11-15 23:06:29.392015899 +0100
@@ -0,0 +1,90 @@
+package bolt
+
+import (
+ "fmt"
+ "os"
+ "syscall"
+ "time"
+ "unsafe"
+
+ "golang.org/x/sys/unix"
+)
+
+// flock acquires an advisory lock on a file descriptor.
+func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Duration) error {
+ var t time.Time
+ for {
+ // If we're beyond our timeout then return an error.
+ // This can only occur after we've attempted a flock once.
+ if t.IsZero() {
+ t = time.Now()
+ } else if timeout > 0 && time.Since(t) > timeout {
+ return ErrTimeout
+ }
+ var lock syscall.Flock_t
+ lock.Start = 0
+ lock.Len = 0
+ lock.Pid = 0
+ lock.Whence = 0
+ lock.Pid = 0
+ if exclusive {
+ lock.Type = syscall.F_WRLCK
+ } else {
+ lock.Type = syscall.F_RDLCK
+ }
+ err := syscall.FcntlFlock(db.file.Fd(), syscall.F_SETLK, &lock)
+ if err == nil {
+ return nil
+ } else if err != syscall.EAGAIN {
+ return err
+ }
+
+ // Wait for a bit and try again.
+ time.Sleep(50 * time.Millisecond)
+ }
+}
+
+// funlock releases an advisory lock on a file descriptor.
+func funlock(db *DB) error {
+ var lock syscall.Flock_t
+ lock.Start = 0
+ lock.Len = 0
+ lock.Type = syscall.F_UNLCK
+ lock.Whence = 0
+ return syscall.FcntlFlock(uintptr(db.file.Fd()), syscall.F_SETLK, &lock)
+}
+
+// mmap memory maps a DB's data file.
+func mmap(db *DB, sz int) error {
+ // Map the data file to memory.
+ b, err := unix.Mmap(int(db.file.Fd()), 0, sz, syscall.PROT_READ, syscall.MAP_SHARED|db.MmapFlags)
+ if err != nil {
+ return err
+ }
+
+ // Advise the kernel that the mmap is accessed randomly.
+ if err := unix.Madvise(b, syscall.MADV_RANDOM); err != nil {
+ return fmt.Errorf("madvise: %s", err)
+ }
+
+ // Save the original byte slice and convert to a byte array pointer.
+ db.dataref = b
+ db.data = (*[maxMapSize]byte)(unsafe.Pointer(&b[0]))
+ db.datasz = sz
+ return nil
+}
+
+// munmap unmaps a DB's data file from memory.
+func munmap(db *DB) error {
+ // Ignore the unmap if we have no mapped data.
+ if db.dataref == nil {
+ return nil
+ }
+
+ // Unmap using the original byte slice.
+ err := unix.Munmap(db.dataref)
+ db.dataref = nil
+ db.data = nil
+ db.datasz = 0
+ return err
+}
diff -Naur --color b/vendor/github.com/boltdb/bolt/bolt_windows.go a/vendor/github.com/boltdb/bolt/bolt_windows.go
--- b/vendor/github.com/boltdb/bolt/bolt_windows.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/boltdb/bolt/bolt_windows.go 2022-11-15 23:06:29.392015899 +0100
@@ -0,0 +1,144 @@
+package bolt
+
+import (
+ "fmt"
+ "os"
+ "syscall"
+ "time"
+ "unsafe"
+)
+
+// LockFileEx code derived from golang build filemutex_windows.go @ v1.5.1
+var (
+ modkernel32 = syscall.NewLazyDLL("kernel32.dll")
+ procLockFileEx = modkernel32.NewProc("LockFileEx")
+ procUnlockFileEx = modkernel32.NewProc("UnlockFileEx")
+)
+
+const (
+ lockExt = ".lock"
+
+ // see https://msdn.microsoft.com/en-us/library/windows/desktop/aa365203(v=vs.85).aspx
+ flagLockExclusive = 2
+ flagLockFailImmediately = 1
+
+ // see https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx
+ errLockViolation syscall.Errno = 0x21
+)
+
+func lockFileEx(h syscall.Handle, flags, reserved, locklow, lockhigh uint32, ol *syscall.Overlapped) (err error) {
+ r, _, err := procLockFileEx.Call(uintptr(h), uintptr(flags), uintptr(reserved), uintptr(locklow), uintptr(lockhigh), uintptr(unsafe.Pointer(ol)))
+ if r == 0 {
+ return err
+ }
+ return nil
+}
+
+func unlockFileEx(h syscall.Handle, reserved, locklow, lockhigh uint32, ol *syscall.Overlapped) (err error) {
+ r, _, err := procUnlockFileEx.Call(uintptr(h), uintptr(reserved), uintptr(locklow), uintptr(lockhigh), uintptr(unsafe.Pointer(ol)), 0)
+ if r == 0 {
+ return err
+ }
+ return nil
+}
+
+// fdatasync flushes written data to a file descriptor.
+func fdatasync(db *DB) error {
+ return db.file.Sync()
+}
+
+// flock acquires an advisory lock on a file descriptor.
+func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Duration) error {
+ // Create a separate lock file on windows because a process
+ // cannot share an exclusive lock on the same file. This is
+ // needed during Tx.WriteTo().
+ f, err := os.OpenFile(db.path+lockExt, os.O_CREATE, mode)
+ if err != nil {
+ return err
+ }
+ db.lockfile = f
+
+ var t time.Time
+ for {
+ // If we're beyond our timeout then return an error.
+ // This can only occur after we've attempted a flock once.
+ if t.IsZero() {
+ t = time.Now()
+ } else if timeout > 0 && time.Since(t) > timeout {
+ return ErrTimeout
+ }
+
+ var flag uint32 = flagLockFailImmediately
+ if exclusive {
+ flag |= flagLockExclusive
+ }
+
+ err := lockFileEx(syscall.Handle(db.lockfile.Fd()), flag, 0, 1, 0, &syscall.Overlapped{})
+ if err == nil {
+ return nil
+ } else if err != errLockViolation {
+ return err
+ }
+
+ // Wait for a bit and try again.
+ time.Sleep(50 * time.Millisecond)
+ }
+}
+
+// funlock releases an advisory lock on a file descriptor.
+func funlock(db *DB) error {
+ err := unlockFileEx(syscall.Handle(db.lockfile.Fd()), 0, 1, 0, &syscall.Overlapped{})
+ db.lockfile.Close()
+ os.Remove(db.path + lockExt)
+ return err
+}
+
+// mmap memory maps a DB's data file.
+// Based on: https://github.com/edsrzf/mmap-go
+func mmap(db *DB, sz int) error {
+ if !db.readOnly {
+ // Truncate the database to the size of the mmap.
+ if err := db.file.Truncate(int64(sz)); err != nil {
+ return fmt.Errorf("truncate: %s", err)
+ }
+ }
+
+ // Open a file mapping handle.
+ sizelo := uint32(sz >> 32)
+ sizehi := uint32(sz) & 0xffffffff
+ h, errno := syscall.CreateFileMapping(syscall.Handle(db.file.Fd()), nil, syscall.PAGE_READONLY, sizelo, sizehi, nil)
+ if h == 0 {
+ return os.NewSyscallError("CreateFileMapping", errno)
+ }
+
+ // Create the memory map.
+ addr, errno := syscall.MapViewOfFile(h, syscall.FILE_MAP_READ, 0, 0, uintptr(sz))
+ if addr == 0 {
+ return os.NewSyscallError("MapViewOfFile", errno)
+ }
+
+ // Close mapping handle.
+ if err := syscall.CloseHandle(syscall.Handle(h)); err != nil {
+ return os.NewSyscallError("CloseHandle", err)
+ }
+
+ // Convert to a byte array.
+ db.data = ((*[maxMapSize]byte)(unsafe.Pointer(addr)))
+ db.datasz = sz
+
+ return nil
+}
+
+// munmap unmaps a pointer from a file.
+// Based on: https://github.com/edsrzf/mmap-go
+func munmap(db *DB) error {
+ if db.data == nil {
+ return nil
+ }
+
+ addr := (uintptr)(unsafe.Pointer(&db.data[0]))
+ if err := syscall.UnmapViewOfFile(addr); err != nil {
+ return os.NewSyscallError("UnmapViewOfFile", err)
+ }
+ return nil
+}
diff -Naur --color b/vendor/github.com/boltdb/bolt/bucket.go a/vendor/github.com/boltdb/bolt/bucket.go
--- b/vendor/github.com/boltdb/bolt/bucket.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/boltdb/bolt/bucket.go 2022-11-15 23:06:29.392015899 +0100
@@ -0,0 +1,777 @@
+package bolt
+
+import (
+ "bytes"
+ "fmt"
+ "unsafe"
+)
+
+const (
+ // MaxKeySize is the maximum length of a key, in bytes.
+ MaxKeySize = 32768
+
+ // MaxValueSize is the maximum length of a value, in bytes.
+ MaxValueSize = (1 << 31) - 2
+)
+
+const (
+ maxUint = ^uint(0)
+ minUint = 0
+ maxInt = int(^uint(0) >> 1)
+ minInt = -maxInt - 1
+)
+
+const bucketHeaderSize = int(unsafe.Sizeof(bucket{}))
+
+const (
+ minFillPercent = 0.1
+ maxFillPercent = 1.0
+)
+
+// DefaultFillPercent is the percentage that split pages are filled.
+// This value can be changed by setting Bucket.FillPercent.
+const DefaultFillPercent = 0.5
+
+// Bucket represents a collection of key/value pairs inside the database.
+type Bucket struct {
+ *bucket
+ tx *Tx // the associated transaction
+ buckets map[string]*Bucket // subbucket cache
+ page *page // inline page reference
+ rootNode *node // materialized node for the root page.
+ nodes map[pgid]*node // node cache
+
+ // Sets the threshold for filling nodes when they split. By default,
+ // the bucket will fill to 50% but it can be useful to increase this
+ // amount if you know that your write workloads are mostly append-only.
+ //
+ // This is non-persisted across transactions so it must be set in every Tx.
+ FillPercent float64
+}
+
+// bucket represents the on-file representation of a bucket.
+// This is stored as the "value" of a bucket key. If the bucket is small enough,
+// then its root page can be stored inline in the "value", after the bucket
+// header. In the case of inline buckets, the "root" will be 0.
+type bucket struct {
+ root pgid // page id of the bucket's root-level page
+ sequence uint64 // monotonically incrementing, used by NextSequence()
+}
+
+// newBucket returns a new bucket associated with a transaction.
+func newBucket(tx *Tx) Bucket {
+ var b = Bucket{tx: tx, FillPercent: DefaultFillPercent}
+ if tx.writable {
+ b.buckets = make(map[string]*Bucket)
+ b.nodes = make(map[pgid]*node)
+ }
+ return b
+}
+
+// Tx returns the tx of the bucket.
+func (b *Bucket) Tx() *Tx {
+ return b.tx
+}
+
+// Root returns the root of the bucket.
+func (b *Bucket) Root() pgid {
+ return b.root
+}
+
+// Writable returns whether the bucket is writable.
+func (b *Bucket) Writable() bool {
+ return b.tx.writable
+}
+
+// Cursor creates a cursor associated with the bucket.
+// The cursor is only valid as long as the transaction is open.
+// Do not use a cursor after the transaction is closed.
+func (b *Bucket) Cursor() *Cursor {
+ // Update transaction statistics.
+ b.tx.stats.CursorCount++
+
+ // Allocate and return a cursor.
+ return &Cursor{
+ bucket: b,
+ stack: make([]elemRef, 0),
+ }
+}
+
+// Bucket retrieves a nested bucket by name.
+// Returns nil if the bucket does not exist.
+// The bucket instance is only valid for the lifetime of the transaction.
+func (b *Bucket) Bucket(name []byte) *Bucket {
+ if b.buckets != nil {
+ if child := b.buckets[string(name)]; child != nil {
+ return child
+ }
+ }
+
+ // Move cursor to key.
+ c := b.Cursor()
+ k, v, flags := c.seek(name)
+
+ // Return nil if the key doesn't exist or it is not a bucket.
+ if !bytes.Equal(name, k) || (flags&bucketLeafFlag) == 0 {
+ return nil
+ }
+
+ // Otherwise create a bucket and cache it.
+ var child = b.openBucket(v)
+ if b.buckets != nil {
+ b.buckets[string(name)] = child
+ }
+
+ return child
+}
+
+// Helper method that re-interprets a sub-bucket value
+// from a parent into a Bucket
+func (b *Bucket) openBucket(value []byte) *Bucket {
+ var child = newBucket(b.tx)
+
+ // If unaligned load/stores are broken on this arch and value is
+ // unaligned simply clone to an aligned byte array.
+ unaligned := brokenUnaligned && uintptr(unsafe.Pointer(&value[0]))&3 != 0
+
+ if unaligned {
+ value = cloneBytes(value)
+ }
+
+ // If this is a writable transaction then we need to copy the bucket entry.
+ // Read-only transactions can point directly at the mmap entry.
+ if b.tx.writable && !unaligned {
+ child.bucket = &bucket{}
+ *child.bucket = *(*bucket)(unsafe.Pointer(&value[0]))
+ } else {
+ child.bucket = (*bucket)(unsafe.Pointer(&value[0]))
+ }
+
+ // Save a reference to the inline page if the bucket is inline.
+ if child.root == 0 {
+ child.page = (*page)(unsafe.Pointer(&value[bucketHeaderSize]))
+ }
+
+ return &child
+}
+
+// CreateBucket creates a new bucket at the given key and returns the new bucket.
+// Returns an error if the key already exists, if the bucket name is blank, or if the bucket name is too long.
+// The bucket instance is only valid for the lifetime of the transaction.
+func (b *Bucket) CreateBucket(key []byte) (*Bucket, error) {
+ if b.tx.db == nil {
+ return nil, ErrTxClosed
+ } else if !b.tx.writable {
+ return nil, ErrTxNotWritable
+ } else if len(key) == 0 {
+ return nil, ErrBucketNameRequired
+ }
+
+ // Move cursor to correct position.
+ c := b.Cursor()
+ k, _, flags := c.seek(key)
+
+ // Return an error if there is an existing key.
+ if bytes.Equal(key, k) {
+ if (flags & bucketLeafFlag) != 0 {
+ return nil, ErrBucketExists
+ }
+ return nil, ErrIncompatibleValue
+ }
+
+ // Create empty, inline bucket.
+ var bucket = Bucket{
+ bucket: &bucket{},
+ rootNode: &node{isLeaf: true},
+ FillPercent: DefaultFillPercent,
+ }
+ var value = bucket.write()
+
+ // Insert into node.
+ key = cloneBytes(key)
+ c.node().put(key, key, value, 0, bucketLeafFlag)
+
+ // Since subbuckets are not allowed on inline buckets, we need to
+ // dereference the inline page, if it exists. This will cause the bucket
+ // to be treated as a regular, non-inline bucket for the rest of the tx.
+ b.page = nil
+
+ return b.Bucket(key), nil
+}
+
+// CreateBucketIfNotExists creates a new bucket if it doesn't already exist and returns a reference to it.
+// Returns an error if the bucket name is blank, or if the bucket name is too long.
+// The bucket instance is only valid for the lifetime of the transaction.
+func (b *Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error) {
+ child, err := b.CreateBucket(key)
+ if err == ErrBucketExists {
+ return b.Bucket(key), nil
+ } else if err != nil {
+ return nil, err
+ }
+ return child, nil
+}
+
+// DeleteBucket deletes a bucket at the given key.
+// Returns an error if the bucket does not exists, or if the key represents a non-bucket value.
+func (b *Bucket) DeleteBucket(key []byte) error {
+ if b.tx.db == nil {
+ return ErrTxClosed
+ } else if !b.Writable() {
+ return ErrTxNotWritable
+ }
+
+ // Move cursor to correct position.
+ c := b.Cursor()
+ k, _, flags := c.seek(key)
+
+ // Return an error if bucket doesn't exist or is not a bucket.
+ if !bytes.Equal(key, k) {
+ return ErrBucketNotFound
+ } else if (flags & bucketLeafFlag) == 0 {
+ return ErrIncompatibleValue
+ }
+
+ // Recursively delete all child buckets.
+ child := b.Bucket(key)
+ err := child.ForEach(func(k, v []byte) error {
+ if v == nil {
+ if err := child.DeleteBucket(k); err != nil {
+ return fmt.Errorf("delete bucket: %s", err)
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ return err
+ }
+
+ // Remove cached copy.
+ delete(b.buckets, string(key))
+
+ // Release all bucket pages to freelist.
+ child.nodes = nil
+ child.rootNode = nil
+ child.free()
+
+ // Delete the node if we have a matching key.
+ c.node().del(key)
+
+ return nil
+}
+
+// Get retrieves the value for a key in the bucket.
+// Returns a nil value if the key does not exist or if the key is a nested bucket.
+// The returned value is only valid for the life of the transaction.
+func (b *Bucket) Get(key []byte) []byte {
+ k, v, flags := b.Cursor().seek(key)
+
+ // Return nil if this is a bucket.
+ if (flags & bucketLeafFlag) != 0 {
+ return nil
+ }
+
+ // If our target node isn't the same key as what's passed in then return nil.
+ if !bytes.Equal(key, k) {
+ return nil
+ }
+ return v
+}
+
+// Put sets the value for a key in the bucket.
+// If the key exist then its previous value will be overwritten.
+// Supplied value must remain valid for the life of the transaction.
+// Returns an error if the bucket was created from a read-only transaction, if the key is blank, if the key is too large, or if the value is too large.
+func (b *Bucket) Put(key []byte, value []byte) error {
+ if b.tx.db == nil {
+ return ErrTxClosed
+ } else if !b.Writable() {
+ return ErrTxNotWritable
+ } else if len(key) == 0 {
+ return ErrKeyRequired
+ } else if len(key) > MaxKeySize {
+ return ErrKeyTooLarge
+ } else if int64(len(value)) > MaxValueSize {
+ return ErrValueTooLarge
+ }
+
+ // Move cursor to correct position.
+ c := b.Cursor()
+ k, _, flags := c.seek(key)
+
+ // Return an error if there is an existing key with a bucket value.
+ if bytes.Equal(key, k) && (flags&bucketLeafFlag) != 0 {
+ return ErrIncompatibleValue
+ }
+
+ // Insert into node.
+ key = cloneBytes(key)
+ c.node().put(key, key, value, 0, 0)
+
+ return nil
+}
+
+// Delete removes a key from the bucket.
+// If the key does not exist then nothing is done and a nil error is returned.
+// Returns an error if the bucket was created from a read-only transaction.
+func (b *Bucket) Delete(key []byte) error {
+ if b.tx.db == nil {
+ return ErrTxClosed
+ } else if !b.Writable() {
+ return ErrTxNotWritable
+ }
+
+ // Move cursor to correct position.
+ c := b.Cursor()
+ _, _, flags := c.seek(key)
+
+ // Return an error if there is already existing bucket value.
+ if (flags & bucketLeafFlag) != 0 {
+ return ErrIncompatibleValue
+ }
+
+ // Delete the node if we have a matching key.
+ c.node().del(key)
+
+ return nil
+}
+
+// Sequence returns the current integer for the bucket without incrementing it.
+func (b *Bucket) Sequence() uint64 { return b.bucket.sequence }
+
+// SetSequence updates the sequence number for the bucket.
+func (b *Bucket) SetSequence(v uint64) error {
+ if b.tx.db == nil {
+ return ErrTxClosed
+ } else if !b.Writable() {
+ return ErrTxNotWritable
+ }
+
+ // Materialize the root node if it hasn't been already so that the
+ // bucket will be saved during commit.
+ if b.rootNode == nil {
+ _ = b.node(b.root, nil)
+ }
+
+ // Increment and return the sequence.
+ b.bucket.sequence = v
+ return nil
+}
+
+// NextSequence returns an autoincrementing integer for the bucket.
+func (b *Bucket) NextSequence() (uint64, error) {
+ if b.tx.db == nil {
+ return 0, ErrTxClosed
+ } else if !b.Writable() {
+ return 0, ErrTxNotWritable
+ }
+
+ // Materialize the root node if it hasn't been already so that the
+ // bucket will be saved during commit.
+ if b.rootNode == nil {
+ _ = b.node(b.root, nil)
+ }
+
+ // Increment and return the sequence.
+ b.bucket.sequence++
+ return b.bucket.sequence, nil
+}
+
+// ForEach executes a function for each key/value pair in a bucket.
+// If the provided function returns an error then the iteration is stopped and
+// the error is returned to the caller. The provided function must not modify
+// the bucket; this will result in undefined behavior.
+func (b *Bucket) ForEach(fn func(k, v []byte) error) error {
+ if b.tx.db == nil {
+ return ErrTxClosed
+ }
+ c := b.Cursor()
+ for k, v := c.First(); k != nil; k, v = c.Next() {
+ if err := fn(k, v); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// Stat returns stats on a bucket.
+func (b *Bucket) Stats() BucketStats {
+ var s, subStats BucketStats
+ pageSize := b.tx.db.pageSize
+ s.BucketN += 1
+ if b.root == 0 {
+ s.InlineBucketN += 1
+ }
+ b.forEachPage(func(p *page, depth int) {
+ if (p.flags & leafPageFlag) != 0 {
+ s.KeyN += int(p.count)
+
+ // used totals the used bytes for the page
+ used := pageHeaderSize
+
+ if p.count != 0 {
+ // If page has any elements, add all element headers.
+ used += leafPageElementSize * int(p.count-1)
+
+ // Add all element key, value sizes.
+ // The computation takes advantage of the fact that the position
+ // of the last element's key/value equals to the total of the sizes
+ // of all previous elements' keys and values.
+ // It also includes the last element's header.
+ lastElement := p.leafPageElement(p.count - 1)
+ used += int(lastElement.pos + lastElement.ksize + lastElement.vsize)
+ }
+
+ if b.root == 0 {
+ // For inlined bucket just update the inline stats
+ s.InlineBucketInuse += used
+ } else {
+ // For non-inlined bucket update all the leaf stats
+ s.LeafPageN++
+ s.LeafInuse += used
+ s.LeafOverflowN += int(p.overflow)
+
+ // Collect stats from sub-buckets.
+ // Do that by iterating over all element headers
+ // looking for the ones with the bucketLeafFlag.
+ for i := uint16(0); i < p.count; i++ {
+ e := p.leafPageElement(i)
+ if (e.flags & bucketLeafFlag) != 0 {
+ // For any bucket element, open the element value
+ // and recursively call Stats on the contained bucket.
+ subStats.Add(b.openBucket(e.value()).Stats())
+ }
+ }
+ }
+ } else if (p.flags & branchPageFlag) != 0 {
+ s.BranchPageN++
+ lastElement := p.branchPageElement(p.count - 1)
+
+ // used totals the used bytes for the page
+ // Add header and all element headers.
+ used := pageHeaderSize + (branchPageElementSize * int(p.count-1))
+
+ // Add size of all keys and values.
+ // Again, use the fact that last element's position equals to
+ // the total of key, value sizes of all previous elements.
+ used += int(lastElement.pos + lastElement.ksize)
+ s.BranchInuse += used
+ s.BranchOverflowN += int(p.overflow)
+ }
+
+ // Keep track of maximum page depth.
+ if depth+1 > s.Depth {
+ s.Depth = (depth + 1)
+ }
+ })
+
+ // Alloc stats can be computed from page counts and pageSize.
+ s.BranchAlloc = (s.BranchPageN + s.BranchOverflowN) * pageSize
+ s.LeafAlloc = (s.LeafPageN + s.LeafOverflowN) * pageSize
+
+ // Add the max depth of sub-buckets to get total nested depth.
+ s.Depth += subStats.Depth
+ // Add the stats for all sub-buckets
+ s.Add(subStats)
+ return s
+}
+
+// forEachPage iterates over every page in a bucket, including inline pages.
+func (b *Bucket) forEachPage(fn func(*page, int)) {
+ // If we have an inline page then just use that.
+ if b.page != nil {
+ fn(b.page, 0)
+ return
+ }
+
+ // Otherwise traverse the page hierarchy.
+ b.tx.forEachPage(b.root, 0, fn)
+}
+
+// forEachPageNode iterates over every page (or node) in a bucket.
+// This also includes inline pages.
+func (b *Bucket) forEachPageNode(fn func(*page, *node, int)) {
+ // If we have an inline page or root node then just use that.
+ if b.page != nil {
+ fn(b.page, nil, 0)
+ return
+ }
+ b._forEachPageNode(b.root, 0, fn)
+}
+
+func (b *Bucket) _forEachPageNode(pgid pgid, depth int, fn func(*page, *node, int)) {
+ var p, n = b.pageNode(pgid)
+
+ // Execute function.
+ fn(p, n, depth)
+
+ // Recursively loop over children.
+ if p != nil {
+ if (p.flags & branchPageFlag) != 0 {
+ for i := 0; i < int(p.count); i++ {
+ elem := p.branchPageElement(uint16(i))
+ b._forEachPageNode(elem.pgid, depth+1, fn)
+ }
+ }
+ } else {
+ if !n.isLeaf {
+ for _, inode := range n.inodes {
+ b._forEachPageNode(inode.pgid, depth+1, fn)
+ }
+ }
+ }
+}
+
+// spill writes all the nodes for this bucket to dirty pages.
+func (b *Bucket) spill() error {
+ // Spill all child buckets first.
+ for name, child := range b.buckets {
+ // If the child bucket is small enough and it has no child buckets then
+ // write it inline into the parent bucket's page. Otherwise spill it
+ // like a normal bucket and make the parent value a pointer to the page.
+ var value []byte
+ if child.inlineable() {
+ child.free()
+ value = child.write()
+ } else {
+ if err := child.spill(); err != nil {
+ return err
+ }
+
+ // Update the child bucket header in this bucket.
+ value = make([]byte, unsafe.Sizeof(bucket{}))
+ var bucket = (*bucket)(unsafe.Pointer(&value[0]))
+ *bucket = *child.bucket
+ }
+
+ // Skip writing the bucket if there are no materialized nodes.
+ if child.rootNode == nil {
+ continue
+ }
+
+ // Update parent node.
+ var c = b.Cursor()
+ k, _, flags := c.seek([]byte(name))
+ if !bytes.Equal([]byte(name), k) {
+ panic(fmt.Sprintf("misplaced bucket header: %x -> %x", []byte(name), k))
+ }
+ if flags&bucketLeafFlag == 0 {
+ panic(fmt.Sprintf("unexpected bucket header flag: %x", flags))
+ }
+ c.node().put([]byte(name), []byte(name), value, 0, bucketLeafFlag)
+ }
+
+ // Ignore if there's not a materialized root node.
+ if b.rootNode == nil {
+ return nil
+ }
+
+ // Spill nodes.
+ if err := b.rootNode.spill(); err != nil {
+ return err
+ }
+ b.rootNode = b.rootNode.root()
+
+ // Update the root node for this bucket.
+ if b.rootNode.pgid >= b.tx.meta.pgid {
+ panic(fmt.Sprintf("pgid (%d) above high water mark (%d)", b.rootNode.pgid, b.tx.meta.pgid))
+ }
+ b.root = b.rootNode.pgid
+
+ return nil
+}
+
+// inlineable returns true if a bucket is small enough to be written inline
+// and if it contains no subbuckets. Otherwise returns false.
+func (b *Bucket) inlineable() bool {
+ var n = b.rootNode
+
+ // Bucket must only contain a single leaf node.
+ if n == nil || !n.isLeaf {
+ return false
+ }
+
+ // Bucket is not inlineable if it contains subbuckets or if it goes beyond
+ // our threshold for inline bucket size.
+ var size = pageHeaderSize
+ for _, inode := range n.inodes {
+ size += leafPageElementSize + len(inode.key) + len(inode.value)
+
+ if inode.flags&bucketLeafFlag != 0 {
+ return false
+ } else if size > b.maxInlineBucketSize() {
+ return false
+ }
+ }
+
+ return true
+}
+
+// Returns the maximum total size of a bucket to make it a candidate for inlining.
+func (b *Bucket) maxInlineBucketSize() int {
+ return b.tx.db.pageSize / 4
+}
+
+// write allocates and writes a bucket to a byte slice.
+func (b *Bucket) write() []byte {
+ // Allocate the appropriate size.
+ var n = b.rootNode
+ var value = make([]byte, bucketHeaderSize+n.size())
+
+ // Write a bucket header.
+ var bucket = (*bucket)(unsafe.Pointer(&value[0]))
+ *bucket = *b.bucket
+
+ // Convert byte slice to a fake page and write the root node.
+ var p = (*page)(unsafe.Pointer(&value[bucketHeaderSize]))
+ n.write(p)
+
+ return value
+}
+
+// rebalance attempts to balance all nodes.
+func (b *Bucket) rebalance() {
+ for _, n := range b.nodes {
+ n.rebalance()
+ }
+ for _, child := range b.buckets {
+ child.rebalance()
+ }
+}
+
+// node creates a node from a page and associates it with a given parent.
+func (b *Bucket) node(pgid pgid, parent *node) *node {
+ _assert(b.nodes != nil, "nodes map expected")
+
+ // Retrieve node if it's already been created.
+ if n := b.nodes[pgid]; n != nil {
+ return n
+ }
+
+ // Otherwise create a node and cache it.
+ n := &node{bucket: b, parent: parent}
+ if parent == nil {
+ b.rootNode = n
+ } else {
+ parent.children = append(parent.children, n)
+ }
+
+ // Use the inline page if this is an inline bucket.
+ var p = b.page
+ if p == nil {
+ p = b.tx.page(pgid)
+ }
+
+ // Read the page into the node and cache it.
+ n.read(p)
+ b.nodes[pgid] = n
+
+ // Update statistics.
+ b.tx.stats.NodeCount++
+
+ return n
+}
+
+// free recursively frees all pages in the bucket.
+func (b *Bucket) free() {
+ if b.root == 0 {
+ return
+ }
+
+ var tx = b.tx
+ b.forEachPageNode(func(p *page, n *node, _ int) {
+ if p != nil {
+ tx.db.freelist.free(tx.meta.txid, p)
+ } else {
+ n.free()
+ }
+ })
+ b.root = 0
+}
+
+// dereference removes all references to the old mmap.
+func (b *Bucket) dereference() {
+ if b.rootNode != nil {
+ b.rootNode.root().dereference()
+ }
+
+ for _, child := range b.buckets {
+ child.dereference()
+ }
+}
+
+// pageNode returns the in-memory node, if it exists.
+// Otherwise returns the underlying page.
+func (b *Bucket) pageNode(id pgid) (*page, *node) {
+ // Inline buckets have a fake page embedded in their value so treat them
+ // differently. We'll return the rootNode (if available) or the fake page.
+ if b.root == 0 {
+ if id != 0 {
+ panic(fmt.Sprintf("inline bucket non-zero page access(2): %d != 0", id))
+ }
+ if b.rootNode != nil {
+ return nil, b.rootNode
+ }
+ return b.page, nil
+ }
+
+ // Check the node cache for non-inline buckets.
+ if b.nodes != nil {
+ if n := b.nodes[id]; n != nil {
+ return nil, n
+ }
+ }
+
+ // Finally lookup the page from the transaction if no node is materialized.
+ return b.tx.page(id), nil
+}
+
+// BucketStats records statistics about resources used by a bucket.
+type BucketStats struct {
+ // Page count statistics.
+ BranchPageN int // number of logical branch pages
+ BranchOverflowN int // number of physical branch overflow pages
+ LeafPageN int // number of logical leaf pages
+ LeafOverflowN int // number of physical leaf overflow pages
+
+ // Tree statistics.
+ KeyN int // number of keys/value pairs
+ Depth int // number of levels in B+tree
+
+ // Page size utilization.
+ BranchAlloc int // bytes allocated for physical branch pages
+ BranchInuse int // bytes actually used for branch data
+ LeafAlloc int // bytes allocated for physical leaf pages
+ LeafInuse int // bytes actually used for leaf data
+
+ // Bucket statistics
+ BucketN int // total number of buckets including the top bucket
+ InlineBucketN int // total number on inlined buckets
+ InlineBucketInuse int // bytes used for inlined buckets (also accounted for in LeafInuse)
+}
+
+func (s *BucketStats) Add(other BucketStats) {
+ s.BranchPageN += other.BranchPageN
+ s.BranchOverflowN += other.BranchOverflowN
+ s.LeafPageN += other.LeafPageN
+ s.LeafOverflowN += other.LeafOverflowN
+ s.KeyN += other.KeyN
+ if s.Depth < other.Depth {
+ s.Depth = other.Depth
+ }
+ s.BranchAlloc += other.BranchAlloc
+ s.BranchInuse += other.BranchInuse
+ s.LeafAlloc += other.LeafAlloc
+ s.LeafInuse += other.LeafInuse
+
+ s.BucketN += other.BucketN
+ s.InlineBucketN += other.InlineBucketN
+ s.InlineBucketInuse += other.InlineBucketInuse
+}
+
+// cloneBytes returns a copy of a given slice.
+func cloneBytes(v []byte) []byte {
+ var clone = make([]byte, len(v))
+ copy(clone, v)
+ return clone
+}
diff -Naur --color b/vendor/github.com/boltdb/bolt/cursor.go a/vendor/github.com/boltdb/bolt/cursor.go
--- b/vendor/github.com/boltdb/bolt/cursor.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/boltdb/bolt/cursor.go 2022-11-15 23:06:29.392015899 +0100
@@ -0,0 +1,400 @@
+package bolt
+
+import (
+ "bytes"
+ "fmt"
+ "sort"
+)
+
+// Cursor represents an iterator that can traverse over all key/value pairs in a bucket in sorted order.
+// Cursors see nested buckets with value == nil.
+// Cursors can be obtained from a transaction and are valid as long as the transaction is open.
+//
+// Keys and values returned from the cursor are only valid for the life of the transaction.
+//
+// Changing data while traversing with a cursor may cause it to be invalidated
+// and return unexpected keys and/or values. You must reposition your cursor
+// after mutating data.
+type Cursor struct {
+ bucket *Bucket
+ stack []elemRef
+}
+
+// Bucket returns the bucket that this cursor was created from.
+func (c *Cursor) Bucket() *Bucket {
+ return c.bucket
+}
+
+// First moves the cursor to the first item in the bucket and returns its key and value.
+// If the bucket is empty then a nil key and value are returned.
+// The returned key and value are only valid for the life of the transaction.
+func (c *Cursor) First() (key []byte, value []byte) {
+ _assert(c.bucket.tx.db != nil, "tx closed")
+ c.stack = c.stack[:0]
+ p, n := c.bucket.pageNode(c.bucket.root)
+ c.stack = append(c.stack, elemRef{page: p, node: n, index: 0})
+ c.first()
+
+ // If we land on an empty page then move to the next value.
+ // https://github.com/boltdb/bolt/issues/450
+ if c.stack[len(c.stack)-1].count() == 0 {
+ c.next()
+ }
+
+ k, v, flags := c.keyValue()
+ if (flags & uint32(bucketLeafFlag)) != 0 {
+ return k, nil
+ }
+ return k, v
+
+}
+
+// Last moves the cursor to the last item in the bucket and returns its key and value.
+// If the bucket is empty then a nil key and value are returned.
+// The returned key and value are only valid for the life of the transaction.
+func (c *Cursor) Last() (key []byte, value []byte) {
+ _assert(c.bucket.tx.db != nil, "tx closed")
+ c.stack = c.stack[:0]
+ p, n := c.bucket.pageNode(c.bucket.root)
+ ref := elemRef{page: p, node: n}
+ ref.index = ref.count() - 1
+ c.stack = append(c.stack, ref)
+ c.last()
+ k, v, flags := c.keyValue()
+ if (flags & uint32(bucketLeafFlag)) != 0 {
+ return k, nil
+ }
+ return k, v
+}
+
+// Next moves the cursor to the next item in the bucket and returns its key and value.
+// If the cursor is at the end of the bucket then a nil key and value are returned.
+// The returned key and value are only valid for the life of the transaction.
+func (c *Cursor) Next() (key []byte, value []byte) {
+ _assert(c.bucket.tx.db != nil, "tx closed")
+ k, v, flags := c.next()
+ if (flags & uint32(bucketLeafFlag)) != 0 {
+ return k, nil
+ }
+ return k, v
+}
+
+// Prev moves the cursor to the previous item in the bucket and returns its key and value.
+// If the cursor is at the beginning of the bucket then a nil key and value are returned.
+// The returned key and value are only valid for the life of the transaction.
+func (c *Cursor) Prev() (key []byte, value []byte) {
+ _assert(c.bucket.tx.db != nil, "tx closed")
+
+ // Attempt to move back one element until we're successful.
+ // Move up the stack as we hit the beginning of each page in our stack.
+ for i := len(c.stack) - 1; i >= 0; i-- {
+ elem := &c.stack[i]
+ if elem.index > 0 {
+ elem.index--
+ break
+ }
+ c.stack = c.stack[:i]
+ }
+
+ // If we've hit the end then return nil.
+ if len(c.stack) == 0 {
+ return nil, nil
+ }
+
+ // Move down the stack to find the last element of the last leaf under this branch.
+ c.last()
+ k, v, flags := c.keyValue()
+ if (flags & uint32(bucketLeafFlag)) != 0 {
+ return k, nil
+ }
+ return k, v
+}
+
+// Seek moves the cursor to a given key and returns it.
+// If the key does not exist then the next key is used. If no keys
+// follow, a nil key is returned.
+// The returned key and value are only valid for the life of the transaction.
+func (c *Cursor) Seek(seek []byte) (key []byte, value []byte) {
+ k, v, flags := c.seek(seek)
+
+ // If we ended up after the last element of a page then move to the next one.
+ if ref := &c.stack[len(c.stack)-1]; ref.index >= ref.count() {
+ k, v, flags = c.next()
+ }
+
+ if k == nil {
+ return nil, nil
+ } else if (flags & uint32(bucketLeafFlag)) != 0 {
+ return k, nil
+ }
+ return k, v
+}
+
+// Delete removes the current key/value under the cursor from the bucket.
+// Delete fails if current key/value is a bucket or if the transaction is not writable.
+func (c *Cursor) Delete() error {
+ if c.bucket.tx.db == nil {
+ return ErrTxClosed
+ } else if !c.bucket.Writable() {
+ return ErrTxNotWritable
+ }
+
+ key, _, flags := c.keyValue()
+ // Return an error if current value is a bucket.
+ if (flags & bucketLeafFlag) != 0 {
+ return ErrIncompatibleValue
+ }
+ c.node().del(key)
+
+ return nil
+}
+
+// seek moves the cursor to a given key and returns it.
+// If the key does not exist then the next key is used.
+func (c *Cursor) seek(seek []byte) (key []byte, value []byte, flags uint32) {
+ _assert(c.bucket.tx.db != nil, "tx closed")
+
+ // Start from root page/node and traverse to correct page.
+ c.stack = c.stack[:0]
+ c.search(seek, c.bucket.root)
+ ref := &c.stack[len(c.stack)-1]
+
+ // If the cursor is pointing to the end of page/node then return nil.
+ if ref.index >= ref.count() {
+ return nil, nil, 0
+ }
+
+ // If this is a bucket then return a nil value.
+ return c.keyValue()
+}
+
+// first moves the cursor to the first leaf element under the last page in the stack.
+func (c *Cursor) first() {
+ for {
+ // Exit when we hit a leaf page.
+ var ref = &c.stack[len(c.stack)-1]
+ if ref.isLeaf() {
+ break
+ }
+
+ // Keep adding pages pointing to the first element to the stack.
+ var pgid pgid
+ if ref.node != nil {
+ pgid = ref.node.inodes[ref.index].pgid
+ } else {
+ pgid = ref.page.branchPageElement(uint16(ref.index)).pgid
+ }
+ p, n := c.bucket.pageNode(pgid)
+ c.stack = append(c.stack, elemRef{page: p, node: n, index: 0})
+ }
+}
+
+// last moves the cursor to the last leaf element under the last page in the stack.
+func (c *Cursor) last() {
+ for {
+ // Exit when we hit a leaf page.
+ ref := &c.stack[len(c.stack)-1]
+ if ref.isLeaf() {
+ break
+ }
+
+ // Keep adding pages pointing to the last element in the stack.
+ var pgid pgid
+ if ref.node != nil {
+ pgid = ref.node.inodes[ref.index].pgid
+ } else {
+ pgid = ref.page.branchPageElement(uint16(ref.index)).pgid
+ }
+ p, n := c.bucket.pageNode(pgid)
+
+ var nextRef = elemRef{page: p, node: n}
+ nextRef.index = nextRef.count() - 1
+ c.stack = append(c.stack, nextRef)
+ }
+}
+
+// next moves to the next leaf element and returns the key and value.
+// If the cursor is at the last leaf element then it stays there and returns nil.
+func (c *Cursor) next() (key []byte, value []byte, flags uint32) {
+ for {
+ // Attempt to move over one element until we're successful.
+ // Move up the stack as we hit the end of each page in our stack.
+ var i int
+ for i = len(c.stack) - 1; i >= 0; i-- {
+ elem := &c.stack[i]
+ if elem.index < elem.count()-1 {
+ elem.index++
+ break
+ }
+ }
+
+ // If we've hit the root page then stop and return. This will leave the
+ // cursor on the last element of the last page.
+ if i == -1 {
+ return nil, nil, 0
+ }
+
+ // Otherwise start from where we left off in the stack and find the
+ // first element of the first leaf page.
+ c.stack = c.stack[:i+1]
+ c.first()
+
+ // If this is an empty page then restart and move back up the stack.
+ // https://github.com/boltdb/bolt/issues/450
+ if c.stack[len(c.stack)-1].count() == 0 {
+ continue
+ }
+
+ return c.keyValue()
+ }
+}
+
+// search recursively performs a binary search against a given page/node until it finds a given key.
+func (c *Cursor) search(key []byte, pgid pgid) {
+ p, n := c.bucket.pageNode(pgid)
+ if p != nil && (p.flags&(branchPageFlag|leafPageFlag)) == 0 {
+ panic(fmt.Sprintf("invalid page type: %d: %x", p.id, p.flags))
+ }
+ e := elemRef{page: p, node: n}
+ c.stack = append(c.stack, e)
+
+ // If we're on a leaf page/node then find the specific node.
+ if e.isLeaf() {
+ c.nsearch(key)
+ return
+ }
+
+ if n != nil {
+ c.searchNode(key, n)
+ return
+ }
+ c.searchPage(key, p)
+}
+
+func (c *Cursor) searchNode(key []byte, n *node) {
+ var exact bool
+ index := sort.Search(len(n.inodes), func(i int) bool {
+ // TODO(benbjohnson): Optimize this range search. It's a bit hacky right now.
+ // sort.Search() finds the lowest index where f() != -1 but we need the highest index.
+ ret := bytes.Compare(n.inodes[i].key, key)
+ if ret == 0 {
+ exact = true
+ }
+ return ret != -1
+ })
+ if !exact && index > 0 {
+ index--
+ }
+ c.stack[len(c.stack)-1].index = index
+
+ // Recursively search to the next page.
+ c.search(key, n.inodes[index].pgid)
+}
+
+func (c *Cursor) searchPage(key []byte, p *page) {
+ // Binary search for the correct range.
+ inodes := p.branchPageElements()
+
+ var exact bool
+ index := sort.Search(int(p.count), func(i int) bool {
+ // TODO(benbjohnson): Optimize this range search. It's a bit hacky right now.
+ // sort.Search() finds the lowest index where f() != -1 but we need the highest index.
+ ret := bytes.Compare(inodes[i].key(), key)
+ if ret == 0 {
+ exact = true
+ }
+ return ret != -1
+ })
+ if !exact && index > 0 {
+ index--
+ }
+ c.stack[len(c.stack)-1].index = index
+
+ // Recursively search to the next page.
+ c.search(key, inodes[index].pgid)
+}
+
+// nsearch searches the leaf node on the top of the stack for a key.
+func (c *Cursor) nsearch(key []byte) {
+ e := &c.stack[len(c.stack)-1]
+ p, n := e.page, e.node
+
+ // If we have a node then search its inodes.
+ if n != nil {
+ index := sort.Search(len(n.inodes), func(i int) bool {
+ return bytes.Compare(n.inodes[i].key, key) != -1
+ })
+ e.index = index
+ return
+ }
+
+ // If we have a page then search its leaf elements.
+ inodes := p.leafPageElements()
+ index := sort.Search(int(p.count), func(i int) bool {
+ return bytes.Compare(inodes[i].key(), key) != -1
+ })
+ e.index = index
+}
+
+// keyValue returns the key and value of the current leaf element.
+func (c *Cursor) keyValue() ([]byte, []byte, uint32) {
+ ref := &c.stack[len(c.stack)-1]
+ if ref.count() == 0 || ref.index >= ref.count() {
+ return nil, nil, 0
+ }
+
+ // Retrieve value from node.
+ if ref.node != nil {
+ inode := &ref.node.inodes[ref.index]
+ return inode.key, inode.value, inode.flags
+ }
+
+ // Or retrieve value from page.
+ elem := ref.page.leafPageElement(uint16(ref.index))
+ return elem.key(), elem.value(), elem.flags
+}
+
+// node returns the node that the cursor is currently positioned on.
+func (c *Cursor) node() *node {
+ _assert(len(c.stack) > 0, "accessing a node with a zero-length cursor stack")
+
+ // If the top of the stack is a leaf node then just return it.
+ if ref := &c.stack[len(c.stack)-1]; ref.node != nil && ref.isLeaf() {
+ return ref.node
+ }
+
+ // Start from root and traverse down the hierarchy.
+ var n = c.stack[0].node
+ if n == nil {
+ n = c.bucket.node(c.stack[0].page.id, nil)
+ }
+ for _, ref := range c.stack[:len(c.stack)-1] {
+ _assert(!n.isLeaf, "expected branch node")
+ n = n.childAt(int(ref.index))
+ }
+ _assert(n.isLeaf, "expected leaf node")
+ return n
+}
+
+// elemRef represents a reference to an element on a given page/node.
+type elemRef struct {
+ page *page
+ node *node
+ index int
+}
+
+// isLeaf returns whether the ref is pointing at a leaf page/node.
+func (r *elemRef) isLeaf() bool {
+ if r.node != nil {
+ return r.node.isLeaf
+ }
+ return (r.page.flags & leafPageFlag) != 0
+}
+
+// count returns the number of inodes or page elements.
+func (r *elemRef) count() int {
+ if r.node != nil {
+ return len(r.node.inodes)
+ }
+ return int(r.page.count)
+}
diff -Naur --color b/vendor/github.com/boltdb/bolt/db.go a/vendor/github.com/boltdb/bolt/db.go
--- b/vendor/github.com/boltdb/bolt/db.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/boltdb/bolt/db.go 2022-11-15 23:06:29.392015899 +0100
@@ -0,0 +1,1039 @@
+package bolt
+
+import (
+ "errors"
+ "fmt"
+ "hash/fnv"
+ "log"
+ "os"
+ "runtime"
+ "runtime/debug"
+ "strings"
+ "sync"
+ "time"
+ "unsafe"
+)
+
+// The largest step that can be taken when remapping the mmap.
+const maxMmapStep = 1 << 30 // 1GB
+
+// The data file format version.
+const version = 2
+
+// Represents a marker value to indicate that a file is a Bolt DB.
+const magic uint32 = 0xED0CDAED
+
+// IgnoreNoSync specifies whether the NoSync field of a DB is ignored when
+// syncing changes to a file. This is required as some operating systems,
+// such as OpenBSD, do not have a unified buffer cache (UBC) and writes
+// must be synchronized using the msync(2) syscall.
+const IgnoreNoSync = runtime.GOOS == "openbsd"
+
+// Default values if not set in a DB instance.
+const (
+ DefaultMaxBatchSize int = 1000
+ DefaultMaxBatchDelay = 10 * time.Millisecond
+ DefaultAllocSize = 16 * 1024 * 1024
+)
+
+// default page size for db is set to the OS page size.
+var defaultPageSize = os.Getpagesize()
+
+// DB represents a collection of buckets persisted to a file on disk.
+// All data access is performed through transactions which can be obtained through the DB.
+// All the functions on DB will return a ErrDatabaseNotOpen if accessed before Open() is called.
+type DB struct {
+ // When enabled, the database will perform a Check() after every commit.
+ // A panic is issued if the database is in an inconsistent state. This
+ // flag has a large performance impact so it should only be used for
+ // debugging purposes.
+ StrictMode bool
+
+ // Setting the NoSync flag will cause the database to skip fsync()
+ // calls after each commit. This can be useful when bulk loading data
+ // into a database and you can restart the bulk load in the event of
+ // a system failure or database corruption. Do not set this flag for
+ // normal use.
+ //
+ // If the package global IgnoreNoSync constant is true, this value is
+ // ignored. See the comment on that constant for more details.
+ //
+ // THIS IS UNSAFE. PLEASE USE WITH CAUTION.
+ NoSync bool
+
+ // When true, skips the truncate call when growing the database.
+ // Setting this to true is only safe on non-ext3/ext4 systems.
+ // Skipping truncation avoids preallocation of hard drive space and
+ // bypasses a truncate() and fsync() syscall on remapping.
+ //
+ // https://github.com/boltdb/bolt/issues/284
+ NoGrowSync bool
+
+ // If you want to read the entire database fast, you can set MmapFlag to
+ // syscall.MAP_POPULATE on Linux 2.6.23+ for sequential read-ahead.
+ MmapFlags int
+
+ // MaxBatchSize is the maximum size of a batch. Default value is
+ // copied from DefaultMaxBatchSize in Open.
+ //
+ // If <=0, disables batching.
+ //
+ // Do not change concurrently with calls to Batch.
+ MaxBatchSize int
+
+ // MaxBatchDelay is the maximum delay before a batch starts.
+ // Default value is copied from DefaultMaxBatchDelay in Open.
+ //
+ // If <=0, effectively disables batching.
+ //
+ // Do not change concurrently with calls to Batch.
+ MaxBatchDelay time.Duration
+
+ // AllocSize is the amount of space allocated when the database
+ // needs to create new pages. This is done to amortize the cost
+ // of truncate() and fsync() when growing the data file.
+ AllocSize int
+
+ path string
+ file *os.File
+ lockfile *os.File // windows only
+ dataref []byte // mmap'ed readonly, write throws SEGV
+ data *[maxMapSize]byte
+ datasz int
+ filesz int // current on disk file size
+ meta0 *meta
+ meta1 *meta
+ pageSize int
+ opened bool
+ rwtx *Tx
+ txs []*Tx
+ freelist *freelist
+ stats Stats
+
+ pagePool sync.Pool
+
+ batchMu sync.Mutex
+ batch *batch
+
+ rwlock sync.Mutex // Allows only one writer at a time.
+ metalock sync.Mutex // Protects meta page access.
+ mmaplock sync.RWMutex // Protects mmap access during remapping.
+ statlock sync.RWMutex // Protects stats access.
+
+ ops struct {
+ writeAt func(b []byte, off int64) (n int, err error)
+ }
+
+ // Read only mode.
+ // When true, Update() and Begin(true) return ErrDatabaseReadOnly immediately.
+ readOnly bool
+}
+
+// Path returns the path to currently open database file.
+func (db *DB) Path() string {
+ return db.path
+}
+
+// GoString returns the Go string representation of the database.
+func (db *DB) GoString() string {
+ return fmt.Sprintf("bolt.DB{path:%q}", db.path)
+}
+
+// String returns the string representation of the database.
+func (db *DB) String() string {
+ return fmt.Sprintf("DB<%q>", db.path)
+}
+
+// Open creates and opens a database at the given path.
+// If the file does not exist then it will be created automatically.
+// Passing in nil options will cause Bolt to open the database with the default options.
+func Open(path string, mode os.FileMode, options *Options) (*DB, error) {
+ var db = &DB{opened: true}
+
+ // Set default options if no options are provided.
+ if options == nil {
+ options = DefaultOptions
+ }
+ db.NoGrowSync = options.NoGrowSync
+ db.MmapFlags = options.MmapFlags
+
+ // Set default values for later DB operations.
+ db.MaxBatchSize = DefaultMaxBatchSize
+ db.MaxBatchDelay = DefaultMaxBatchDelay
+ db.AllocSize = DefaultAllocSize
+
+ flag := os.O_RDWR
+ if options.ReadOnly {
+ flag = os.O_RDONLY
+ db.readOnly = true
+ }
+
+ // Open data file and separate sync handler for metadata writes.
+ db.path = path
+ var err error
+ if db.file, err = os.OpenFile(db.path, flag|os.O_CREATE, mode); err != nil {
+ _ = db.close()
+ return nil, err
+ }
+
+ // Lock file so that other processes using Bolt in read-write mode cannot
+ // use the database at the same time. This would cause corruption since
+ // the two processes would write meta pages and free pages separately.
+ // The database file is locked exclusively (only one process can grab the lock)
+ // if !options.ReadOnly.
+ // The database file is locked using the shared lock (more than one process may
+ // hold a lock at the same time) otherwise (options.ReadOnly is set).
+ if err := flock(db, mode, !db.readOnly, options.Timeout); err != nil {
+ _ = db.close()
+ return nil, err
+ }
+
+ // Default values for test hooks
+ db.ops.writeAt = db.file.WriteAt
+
+ // Initialize the database if it doesn't exist.
+ if info, err := db.file.Stat(); err != nil {
+ return nil, err
+ } else if info.Size() == 0 {
+ // Initialize new files with meta pages.
+ if err := db.init(); err != nil {
+ return nil, err
+ }
+ } else {
+ // Read the first meta page to determine the page size.
+ var buf [0x1000]byte
+ if _, err := db.file.ReadAt(buf[:], 0); err == nil {
+ m := db.pageInBuffer(buf[:], 0).meta()
+ if err := m.validate(); err != nil {
+ // If we can't read the page size, we can assume it's the same
+ // as the OS -- since that's how the page size was chosen in the
+ // first place.
+ //
+ // If the first page is invalid and this OS uses a different
+ // page size than what the database was created with then we
+ // are out of luck and cannot access the database.
+ db.pageSize = os.Getpagesize()
+ } else {
+ db.pageSize = int(m.pageSize)
+ }
+ }
+ }
+
+ // Initialize page pool.
+ db.pagePool = sync.Pool{
+ New: func() interface{} {
+ return make([]byte, db.pageSize)
+ },
+ }
+
+ // Memory map the data file.
+ if err := db.mmap(options.InitialMmapSize); err != nil {
+ _ = db.close()
+ return nil, err
+ }
+
+ // Read in the freelist.
+ db.freelist = newFreelist()
+ db.freelist.read(db.page(db.meta().freelist))
+
+ // Mark the database as opened and return.
+ return db, nil
+}
+
+// mmap opens the underlying memory-mapped file and initializes the meta references.
+// minsz is the minimum size that the new mmap can be.
+func (db *DB) mmap(minsz int) error {
+ db.mmaplock.Lock()
+ defer db.mmaplock.Unlock()
+
+ info, err := db.file.Stat()
+ if err != nil {
+ return fmt.Errorf("mmap stat error: %s", err)
+ } else if int(info.Size()) < db.pageSize*2 {
+ return fmt.Errorf("file size too small")
+ }
+
+ // Ensure the size is at least the minimum size.
+ var size = int(info.Size())
+ if size < minsz {
+ size = minsz
+ }
+ size, err = db.mmapSize(size)
+ if err != nil {
+ return err
+ }
+
+ // Dereference all mmap references before unmapping.
+ if db.rwtx != nil {
+ db.rwtx.root.dereference()
+ }
+
+ // Unmap existing data before continuing.
+ if err := db.munmap(); err != nil {
+ return err
+ }
+
+ // Memory-map the data file as a byte slice.
+ if err := mmap(db, size); err != nil {
+ return err
+ }
+
+ // Save references to the meta pages.
+ db.meta0 = db.page(0).meta()
+ db.meta1 = db.page(1).meta()
+
+ // Validate the meta pages. We only return an error if both meta pages fail
+ // validation, since meta0 failing validation means that it wasn't saved
+ // properly -- but we can recover using meta1. And vice-versa.
+ err0 := db.meta0.validate()
+ err1 := db.meta1.validate()
+ if err0 != nil && err1 != nil {
+ return err0
+ }
+
+ return nil
+}
+
+// munmap unmaps the data file from memory.
+func (db *DB) munmap() error {
+ if err := munmap(db); err != nil {
+ return fmt.Errorf("unmap error: " + err.Error())
+ }
+ return nil
+}
+
+// mmapSize determines the appropriate size for the mmap given the current size
+// of the database. The minimum size is 32KB and doubles until it reaches 1GB.
+// Returns an error if the new mmap size is greater than the max allowed.
+func (db *DB) mmapSize(size int) (int, error) {
+ // Double the size from 32KB until 1GB.
+ for i := uint(15); i <= 30; i++ {
+ if size <= 1<<i {
+ return 1 << i, nil
+ }
+ }
+
+ // Verify the requested size is not above the maximum allowed.
+ if size > maxMapSize {
+ return 0, fmt.Errorf("mmap too large")
+ }
+
+ // If larger than 1GB then grow by 1GB at a time.
+ sz := int64(size)
+ if remainder := sz % int64(maxMmapStep); remainder > 0 {
+ sz += int64(maxMmapStep) - remainder
+ }
+
+ // Ensure that the mmap size is a multiple of the page size.
+ // This should always be true since we're incrementing in MBs.
+ pageSize := int64(db.pageSize)
+ if (sz % pageSize) != 0 {
+ sz = ((sz / pageSize) + 1) * pageSize
+ }
+
+ // If we've exceeded the max size then only grow up to the max size.
+ if sz > maxMapSize {
+ sz = maxMapSize
+ }
+
+ return int(sz), nil
+}
+
+// init creates a new database file and initializes its meta pages.
+func (db *DB) init() error {
+ // Set the page size to the OS page size.
+ db.pageSize = os.Getpagesize()
+
+ // Create two meta pages on a buffer.
+ buf := make([]byte, db.pageSize*4)
+ for i := 0; i < 2; i++ {
+ p := db.pageInBuffer(buf[:], pgid(i))
+ p.id = pgid(i)
+ p.flags = metaPageFlag
+
+ // Initialize the meta page.
+ m := p.meta()
+ m.magic = magic
+ m.version = version
+ m.pageSize = uint32(db.pageSize)
+ m.freelist = 2
+ m.root = bucket{root: 3}
+ m.pgid = 4
+ m.txid = txid(i)
+ m.checksum = m.sum64()
+ }
+
+ // Write an empty freelist at page 3.
+ p := db.pageInBuffer(buf[:], pgid(2))
+ p.id = pgid(2)
+ p.flags = freelistPageFlag
+ p.count = 0
+
+ // Write an empty leaf page at page 4.
+ p = db.pageInBuffer(buf[:], pgid(3))
+ p.id = pgid(3)
+ p.flags = leafPageFlag
+ p.count = 0
+
+ // Write the buffer to our data file.
+ if _, err := db.ops.writeAt(buf, 0); err != nil {
+ return err
+ }
+ if err := fdatasync(db); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+// Close releases all database resources.
+// All transactions must be closed before closing the database.
+func (db *DB) Close() error {
+ db.rwlock.Lock()
+ defer db.rwlock.Unlock()
+
+ db.metalock.Lock()
+ defer db.metalock.Unlock()
+
+ db.mmaplock.RLock()
+ defer db.mmaplock.RUnlock()
+
+ return db.close()
+}
+
+func (db *DB) close() error {
+ if !db.opened {
+ return nil
+ }
+
+ db.opened = false
+
+ db.freelist = nil
+
+ // Clear ops.
+ db.ops.writeAt = nil
+
+ // Close the mmap.
+ if err := db.munmap(); err != nil {
+ return err
+ }
+
+ // Close file handles.
+ if db.file != nil {
+ // No need to unlock read-only file.
+ if !db.readOnly {
+ // Unlock the file.
+ if err := funlock(db); err != nil {
+ log.Printf("bolt.Close(): funlock error: %s", err)
+ }
+ }
+
+ // Close the file descriptor.
+ if err := db.file.Close(); err != nil {
+ return fmt.Errorf("db file close: %s", err)
+ }
+ db.file = nil
+ }
+
+ db.path = ""
+ return nil
+}
+
+// Begin starts a new transaction.
+// Multiple read-only transactions can be used concurrently but only one
+// write transaction can be used at a time. Starting multiple write transactions
+// will cause the calls to block and be serialized until the current write
+// transaction finishes.
+//
+// Transactions should not be dependent on one another. Opening a read
+// transaction and a write transaction in the same goroutine can cause the
+// writer to deadlock because the database periodically needs to re-mmap itself
+// as it grows and it cannot do that while a read transaction is open.
+//
+// If a long running read transaction (for example, a snapshot transaction) is
+// needed, you might want to set DB.InitialMmapSize to a large enough value
+// to avoid potential blocking of write transaction.
+//
+// IMPORTANT: You must close read-only transactions after you are finished or
+// else the database will not reclaim old pages.
+func (db *DB) Begin(writable bool) (*Tx, error) {
+ if writable {
+ return db.beginRWTx()
+ }
+ return db.beginTx()
+}
+
+func (db *DB) beginTx() (*Tx, error) {
+ // Lock the meta pages while we initialize the transaction. We obtain
+ // the meta lock before the mmap lock because that's the order that the
+ // write transaction will obtain them.
+ db.metalock.Lock()
+
+ // Obtain a read-only lock on the mmap. When the mmap is remapped it will
+ // obtain a write lock so all transactions must finish before it can be
+ // remapped.
+ db.mmaplock.RLock()
+
+ // Exit if the database is not open yet.
+ if !db.opened {
+ db.mmaplock.RUnlock()
+ db.metalock.Unlock()
+ return nil, ErrDatabaseNotOpen
+ }
+
+ // Create a transaction associated with the database.
+ t := &Tx{}
+ t.init(db)
+
+ // Keep track of transaction until it closes.
+ db.txs = append(db.txs, t)
+ n := len(db.txs)
+
+ // Unlock the meta pages.
+ db.metalock.Unlock()
+
+ // Update the transaction stats.
+ db.statlock.Lock()
+ db.stats.TxN++
+ db.stats.OpenTxN = n
+ db.statlock.Unlock()
+
+ return t, nil
+}
+
+func (db *DB) beginRWTx() (*Tx, error) {
+ // If the database was opened with Options.ReadOnly, return an error.
+ if db.readOnly {
+ return nil, ErrDatabaseReadOnly
+ }
+
+ // Obtain writer lock. This is released by the transaction when it closes.
+ // This enforces only one writer transaction at a time.
+ db.rwlock.Lock()
+
+ // Once we have the writer lock then we can lock the meta pages so that
+ // we can set up the transaction.
+ db.metalock.Lock()
+ defer db.metalock.Unlock()
+
+ // Exit if the database is not open yet.
+ if !db.opened {
+ db.rwlock.Unlock()
+ return nil, ErrDatabaseNotOpen
+ }
+
+ // Create a transaction associated with the database.
+ t := &Tx{writable: true}
+ t.init(db)
+ db.rwtx = t
+
+ // Free any pages associated with closed read-only transactions.
+ var minid txid = 0xFFFFFFFFFFFFFFFF
+ for _, t := range db.txs {
+ if t.meta.txid < minid {
+ minid = t.meta.txid
+ }
+ }
+ if minid > 0 {
+ db.freelist.release(minid - 1)
+ }
+
+ return t, nil
+}
+
+// removeTx removes a transaction from the database.
+func (db *DB) removeTx(tx *Tx) {
+ // Release the read lock on the mmap.
+ db.mmaplock.RUnlock()
+
+ // Use the meta lock to restrict access to the DB object.
+ db.metalock.Lock()
+
+ // Remove the transaction.
+ for i, t := range db.txs {
+ if t == tx {
+ last := len(db.txs) - 1
+ db.txs[i] = db.txs[last]
+ db.txs[last] = nil
+ db.txs = db.txs[:last]
+ break
+ }
+ }
+ n := len(db.txs)
+
+ // Unlock the meta pages.
+ db.metalock.Unlock()
+
+ // Merge statistics.
+ db.statlock.Lock()
+ db.stats.OpenTxN = n
+ db.stats.TxStats.add(&tx.stats)
+ db.statlock.Unlock()
+}
+
+// Update executes a function within the context of a read-write managed transaction.
+// If no error is returned from the function then the transaction is committed.
+// If an error is returned then the entire transaction is rolled back.
+// Any error that is returned from the function or returned from the commit is
+// returned from the Update() method.
+//
+// Attempting to manually commit or rollback within the function will cause a panic.
+func (db *DB) Update(fn func(*Tx) error) error {
+ t, err := db.Begin(true)
+ if err != nil {
+ return err
+ }
+
+ // Make sure the transaction rolls back in the event of a panic.
+ defer func() {
+ if t.db != nil {
+ t.rollback()
+ }
+ }()
+
+ // Mark as a managed tx so that the inner function cannot manually commit.
+ t.managed = true
+
+ // If an error is returned from the function then rollback and return error.
+ err = fn(t)
+ t.managed = false
+ if err != nil {
+ _ = t.Rollback()
+ return err
+ }
+
+ return t.Commit()
+}
+
+// View executes a function within the context of a managed read-only transaction.
+// Any error that is returned from the function is returned from the View() method.
+//
+// Attempting to manually rollback within the function will cause a panic.
+func (db *DB) View(fn func(*Tx) error) error {
+ t, err := db.Begin(false)
+ if err != nil {
+ return err
+ }
+
+ // Make sure the transaction rolls back in the event of a panic.
+ defer func() {
+ if t.db != nil {
+ t.rollback()
+ }
+ }()
+
+ // Mark as a managed tx so that the inner function cannot manually rollback.
+ t.managed = true
+
+ // If an error is returned from the function then pass it through.
+ err = fn(t)
+ t.managed = false
+ if err != nil {
+ _ = t.Rollback()
+ return err
+ }
+
+ if err := t.Rollback(); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+// Batch calls fn as part of a batch. It behaves similar to Update,
+// except:
+//
+// 1. concurrent Batch calls can be combined into a single Bolt
+// transaction.
+//
+// 2. the function passed to Batch may be called multiple times,
+// regardless of whether it returns error or not.
+//
+// This means that Batch function side effects must be idempotent and
+// take permanent effect only after a successful return is seen in
+// caller.
+//
+// The maximum batch size and delay can be adjusted with DB.MaxBatchSize
+// and DB.MaxBatchDelay, respectively.
+//
+// Batch is only useful when there are multiple goroutines calling it.
+func (db *DB) Batch(fn func(*Tx) error) error {
+ errCh := make(chan error, 1)
+
+ db.batchMu.Lock()
+ if (db.batch == nil) || (db.batch != nil && len(db.batch.calls) >= db.MaxBatchSize) {
+ // There is no existing batch, or the existing batch is full; start a new one.
+ db.batch = &batch{
+ db: db,
+ }
+ db.batch.timer = time.AfterFunc(db.MaxBatchDelay, db.batch.trigger)
+ }
+ db.batch.calls = append(db.batch.calls, call{fn: fn, err: errCh})
+ if len(db.batch.calls) >= db.MaxBatchSize {
+ // wake up batch, it's ready to run
+ go db.batch.trigger()
+ }
+ db.batchMu.Unlock()
+
+ err := <-errCh
+ if err == trySolo {
+ err = db.Update(fn)
+ }
+ return err
+}
+
+type call struct {
+ fn func(*Tx) error
+ err chan<- error
+}
+
+type batch struct {
+ db *DB
+ timer *time.Timer
+ start sync.Once
+ calls []call
+}
+
+// trigger runs the batch if it hasn't already been run.
+func (b *batch) trigger() {
+ b.start.Do(b.run)
+}
+
+// run performs the transactions in the batch and communicates results
+// back to DB.Batch.
+func (b *batch) run() {
+ b.db.batchMu.Lock()
+ b.timer.Stop()
+ // Make sure no new work is added to this batch, but don't break
+ // other batches.
+ if b.db.batch == b {
+ b.db.batch = nil
+ }
+ b.db.batchMu.Unlock()
+
+retry:
+ for len(b.calls) > 0 {
+ var failIdx = -1
+ err := b.db.Update(func(tx *Tx) error {
+ for i, c := range b.calls {
+ if err := safelyCall(c.fn, tx); err != nil {
+ failIdx = i
+ return err
+ }
+ }
+ return nil
+ })
+
+ if failIdx >= 0 {
+ // take the failing transaction out of the batch. it's
+ // safe to shorten b.calls here because db.batch no longer
+ // points to us, and we hold the mutex anyway.
+ c := b.calls[failIdx]
+ b.calls[failIdx], b.calls = b.calls[len(b.calls)-1], b.calls[:len(b.calls)-1]
+ // tell the submitter re-run it solo, continue with the rest of the batch
+ c.err <- trySolo
+ continue retry
+ }
+
+ // pass success, or bolt internal errors, to all callers
+ for _, c := range b.calls {
+ if c.err != nil {
+ c.err <- err
+ }
+ }
+ break retry
+ }
+}
+
+// trySolo is a special sentinel error value used for signaling that a
+// transaction function should be re-run. It should never be seen by
+// callers.
+var trySolo = errors.New("batch function returned an error and should be re-run solo")
+
+type panicked struct {
+ reason interface{}
+}
+
+func (p panicked) Error() string {
+ if err, ok := p.reason.(error); ok {
+ return err.Error()
+ }
+ return fmt.Sprintf("panic: %v", p.reason)
+}
+
+func safelyCall(fn func(*Tx) error, tx *Tx) (err error) {
+ defer func() {
+ if p := recover(); p != nil {
+ err = panicked{p}
+ }
+ }()
+ return fn(tx)
+}
+
+// Sync executes fdatasync() against the database file handle.
+//
+// This is not necessary under normal operation, however, if you use NoSync
+// then it allows you to force the database file to sync against the disk.
+func (db *DB) Sync() error { return fdatasync(db) }
+
+// Stats retrieves ongoing performance stats for the database.
+// This is only updated when a transaction closes.
+func (db *DB) Stats() Stats {
+ db.statlock.RLock()
+ defer db.statlock.RUnlock()
+ return db.stats
+}
+
+// This is for internal access to the raw data bytes from the C cursor, use
+// carefully, or not at all.
+func (db *DB) Info() *Info {
+ return &Info{uintptr(unsafe.Pointer(&db.data[0])), db.pageSize}
+}
+
+// page retrieves a page reference from the mmap based on the current page size.
+func (db *DB) page(id pgid) *page {
+ pos := id * pgid(db.pageSize)
+ return (*page)(unsafe.Pointer(&db.data[pos]))
+}
+
+// pageInBuffer retrieves a page reference from a given byte array based on the current page size.
+func (db *DB) pageInBuffer(b []byte, id pgid) *page {
+ return (*page)(unsafe.Pointer(&b[id*pgid(db.pageSize)]))
+}
+
+// meta retrieves the current meta page reference.
+func (db *DB) meta() *meta {
+ // We have to return the meta with the highest txid which doesn't fail
+ // validation. Otherwise, we can cause errors when in fact the database is
+ // in a consistent state. metaA is the one with the higher txid.
+ metaA := db.meta0
+ metaB := db.meta1
+ if db.meta1.txid > db.meta0.txid {
+ metaA = db.meta1
+ metaB = db.meta0
+ }
+
+ // Use higher meta page if valid. Otherwise fallback to previous, if valid.
+ if err := metaA.validate(); err == nil {
+ return metaA
+ } else if err := metaB.validate(); err == nil {
+ return metaB
+ }
+
+ // This should never be reached, because both meta1 and meta0 were validated
+ // on mmap() and we do fsync() on every write.
+ panic("bolt.DB.meta(): invalid meta pages")
+}
+
+// allocate returns a contiguous block of memory starting at a given page.
+func (db *DB) allocate(count int) (*page, error) {
+ // Allocate a temporary buffer for the page.
+ var buf []byte
+ if count == 1 {
+ buf = db.pagePool.Get().([]byte)
+ } else {
+ buf = make([]byte, count*db.pageSize)
+ }
+ p := (*page)(unsafe.Pointer(&buf[0]))
+ p.overflow = uint32(count - 1)
+
+ // Use pages from the freelist if they are available.
+ if p.id = db.freelist.allocate(count); p.id != 0 {
+ return p, nil
+ }
+
+ // Resize mmap() if we're at the end.
+ p.id = db.rwtx.meta.pgid
+ var minsz = int((p.id+pgid(count))+1) * db.pageSize
+ if minsz >= db.datasz {
+ if err := db.mmap(minsz); err != nil {
+ return nil, fmt.Errorf("mmap allocate error: %s", err)
+ }
+ }
+
+ // Move the page id high water mark.
+ db.rwtx.meta.pgid += pgid(count)
+
+ return p, nil
+}
+
+// grow grows the size of the database to the given sz.
+func (db *DB) grow(sz int) error {
+ // Ignore if the new size is less than available file size.
+ if sz <= db.filesz {
+ return nil
+ }
+
+ // If the data is smaller than the alloc size then only allocate what's needed.
+ // Once it goes over the allocation size then allocate in chunks.
+ if db.datasz < db.AllocSize {
+ sz = db.datasz
+ } else {
+ sz += db.AllocSize
+ }
+
+ // Truncate and fsync to ensure file size metadata is flushed.
+ // https://github.com/boltdb/bolt/issues/284
+ if !db.NoGrowSync && !db.readOnly {
+ if runtime.GOOS != "windows" {
+ if err := db.file.Truncate(int64(sz)); err != nil {
+ return fmt.Errorf("file resize error: %s", err)
+ }
+ }
+ if err := db.file.Sync(); err != nil {
+ return fmt.Errorf("file sync error: %s", err)
+ }
+ }
+
+ db.filesz = sz
+ return nil
+}
+
+func (db *DB) IsReadOnly() bool {
+ return db.readOnly
+}
+
+// Options represents the options that can be set when opening a database.
+type Options struct {
+ // Timeout is the amount of time to wait to obtain a file lock.
+ // When set to zero it will wait indefinitely. This option is only
+ // available on Darwin and Linux.
+ Timeout time.Duration
+
+ // Sets the DB.NoGrowSync flag before memory mapping the file.
+ NoGrowSync bool
+
+ // Open database in read-only mode. Uses flock(..., LOCK_SH |LOCK_NB) to
+ // grab a shared lock (UNIX).
+ ReadOnly bool
+
+ // Sets the DB.MmapFlags flag before memory mapping the file.
+ MmapFlags int
+
+ // InitialMmapSize is the initial mmap size of the database
+ // in bytes. Read transactions won't block write transaction
+ // if the InitialMmapSize is large enough to hold database mmap
+ // size. (See DB.Begin for more information)
+ //
+ // If <=0, the initial map size is 0.
+ // If initialMmapSize is smaller than the previous database size,
+ // it takes no effect.
+ InitialMmapSize int
+}
+
+// DefaultOptions represent the options used if nil options are passed into Open().
+// No timeout is used which will cause Bolt to wait indefinitely for a lock.
+var DefaultOptions = &Options{
+ Timeout: 0,
+ NoGrowSync: false,
+}
+
+// Stats represents statistics about the database.
+type Stats struct {
+ // Freelist stats
+ FreePageN int // total number of free pages on the freelist
+ PendingPageN int // total number of pending pages on the freelist
+ FreeAlloc int // total bytes allocated in free pages
+ FreelistInuse int // total bytes used by the freelist
+
+ // Transaction stats
+ TxN int // total number of started read transactions
+ OpenTxN int // number of currently open read transactions
+
+ TxStats TxStats // global, ongoing stats.
+}
+
+// Sub calculates and returns the difference between two sets of database stats.
+// This is useful when obtaining stats at two different points and time and
+// you need the performance counters that occurred within that time span.
+func (s *Stats) Sub(other *Stats) Stats {
+ if other == nil {
+ return *s
+ }
+ var diff Stats
+ diff.FreePageN = s.FreePageN
+ diff.PendingPageN = s.PendingPageN
+ diff.FreeAlloc = s.FreeAlloc
+ diff.FreelistInuse = s.FreelistInuse
+ diff.TxN = s.TxN - other.TxN
+ diff.TxStats = s.TxStats.Sub(&other.TxStats)
+ return diff
+}
+
+func (s *Stats) add(other *Stats) {
+ s.TxStats.add(&other.TxStats)
+}
+
+type Info struct {
+ Data uintptr
+ PageSize int
+}
+
+type meta struct {
+ magic uint32
+ version uint32
+ pageSize uint32
+ flags uint32
+ root bucket
+ freelist pgid
+ pgid pgid
+ txid txid
+ checksum uint64
+}
+
+// validate checks the marker bytes and version of the meta page to ensure it matches this binary.
+func (m *meta) validate() error {
+ if m.magic != magic {
+ return ErrInvalid
+ } else if m.version != version {
+ return ErrVersionMismatch
+ } else if m.checksum != 0 && m.checksum != m.sum64() {
+ return ErrChecksum
+ }
+ return nil
+}
+
+// copy copies one meta object to another.
+func (m *meta) copy(dest *meta) {
+ *dest = *m
+}
+
+// write writes the meta onto a page.
+func (m *meta) write(p *page) {
+ if m.root.root >= m.pgid {
+ panic(fmt.Sprintf("root bucket pgid (%d) above high water mark (%d)", m.root.root, m.pgid))
+ } else if m.freelist >= m.pgid {
+ panic(fmt.Sprintf("freelist pgid (%d) above high water mark (%d)", m.freelist, m.pgid))
+ }
+
+ // Page id is either going to be 0 or 1 which we can determine by the transaction ID.
+ p.id = pgid(m.txid % 2)
+ p.flags |= metaPageFlag
+
+ // Calculate the checksum.
+ m.checksum = m.sum64()
+
+ m.copy(p.meta())
+}
+
+// generates the checksum for the meta.
+func (m *meta) sum64() uint64 {
+ var h = fnv.New64a()
+ _, _ = h.Write((*[unsafe.Offsetof(meta{}.checksum)]byte)(unsafe.Pointer(m))[:])
+ return h.Sum64()
+}
+
+// _assert will panic with a given formatted message if the given condition is false.
+func _assert(condition bool, msg string, v ...interface{}) {
+ if !condition {
+ panic(fmt.Sprintf("assertion failed: "+msg, v...))
+ }
+}
+
+func warn(v ...interface{}) { fmt.Fprintln(os.Stderr, v...) }
+func warnf(msg string, v ...interface{}) { fmt.Fprintf(os.Stderr, msg+"\n", v...) }
+
+func printstack() {
+ stack := strings.Join(strings.Split(string(debug.Stack()), "\n")[2:], "\n")
+ fmt.Fprintln(os.Stderr, stack)
+}
diff -Naur --color b/vendor/github.com/boltdb/bolt/doc.go a/vendor/github.com/boltdb/bolt/doc.go
--- b/vendor/github.com/boltdb/bolt/doc.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/boltdb/bolt/doc.go 2022-11-15 23:06:29.392015899 +0100
@@ -0,0 +1,44 @@
+/*
+Package bolt implements a low-level key/value store in pure Go. It supports
+fully serializable transactions, ACID semantics, and lock-free MVCC with
+multiple readers and a single writer. Bolt can be used for projects that
+want a simple data store without the need to add large dependencies such as
+Postgres or MySQL.
+
+Bolt is a single-level, zero-copy, B+tree data store. This means that Bolt is
+optimized for fast read access and does not require recovery in the event of a
+system crash. Transactions which have not finished committing will simply be
+rolled back in the event of a crash.
+
+The design of Bolt is based on Howard Chu's LMDB database project.
+
+Bolt currently works on Windows, Mac OS X, and Linux.
+
+
+Basics
+
+There are only a few types in Bolt: DB, Bucket, Tx, and Cursor. The DB is
+a collection of buckets and is represented by a single file on disk. A bucket is
+a collection of unique keys that are associated with values.
+
+Transactions provide either read-only or read-write access to the database.
+Read-only transactions can retrieve key/value pairs and can use Cursors to
+iterate over the dataset sequentially. Read-write transactions can create and
+delete buckets and can insert and remove keys. Only one read-write transaction
+is allowed at a time.
+
+
+Caveats
+
+The database uses a read-only, memory-mapped data file to ensure that
+applications cannot corrupt the database, however, this means that keys and
+values returned from Bolt cannot be changed. Writing to a read-only byte slice
+will cause Go to panic.
+
+Keys and values retrieved from the database are only valid for the life of
+the transaction. When used outside the transaction, these byte slices can
+point to different data or can point to invalid memory which will cause a panic.
+
+
+*/
+package bolt
diff -Naur --color b/vendor/github.com/boltdb/bolt/errors.go a/vendor/github.com/boltdb/bolt/errors.go
--- b/vendor/github.com/boltdb/bolt/errors.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/boltdb/bolt/errors.go 2022-11-15 23:06:29.392015899 +0100
@@ -0,0 +1,71 @@
+package bolt
+
+import "errors"
+
+// These errors can be returned when opening or calling methods on a DB.
+var (
+ // ErrDatabaseNotOpen is returned when a DB instance is accessed before it
+ // is opened or after it is closed.
+ ErrDatabaseNotOpen = errors.New("database not open")
+
+ // ErrDatabaseOpen is returned when opening a database that is
+ // already open.
+ ErrDatabaseOpen = errors.New("database already open")
+
+ // ErrInvalid is returned when both meta pages on a database are invalid.
+ // This typically occurs when a file is not a bolt database.
+ ErrInvalid = errors.New("invalid database")
+
+ // ErrVersionMismatch is returned when the data file was created with a
+ // different version of Bolt.
+ ErrVersionMismatch = errors.New("version mismatch")
+
+ // ErrChecksum is returned when either meta page checksum does not match.
+ ErrChecksum = errors.New("checksum error")
+
+ // ErrTimeout is returned when a database cannot obtain an exclusive lock
+ // on the data file after the timeout passed to Open().
+ ErrTimeout = errors.New("timeout")
+)
+
+// These errors can occur when beginning or committing a Tx.
+var (
+ // ErrTxNotWritable is returned when performing a write operation on a
+ // read-only transaction.
+ ErrTxNotWritable = errors.New("tx not writable")
+
+ // ErrTxClosed is returned when committing or rolling back a transaction
+ // that has already been committed or rolled back.
+ ErrTxClosed = errors.New("tx closed")
+
+ // ErrDatabaseReadOnly is returned when a mutating transaction is started on a
+ // read-only database.
+ ErrDatabaseReadOnly = errors.New("database is in read-only mode")
+)
+
+// These errors can occur when putting or deleting a value or a bucket.
+var (
+ // ErrBucketNotFound is returned when trying to access a bucket that has
+ // not been created yet.
+ ErrBucketNotFound = errors.New("bucket not found")
+
+ // ErrBucketExists is returned when creating a bucket that already exists.
+ ErrBucketExists = errors.New("bucket already exists")
+
+ // ErrBucketNameRequired is returned when creating a bucket with a blank name.
+ ErrBucketNameRequired = errors.New("bucket name required")
+
+ // ErrKeyRequired is returned when inserting a zero-length key.
+ ErrKeyRequired = errors.New("key required")
+
+ // ErrKeyTooLarge is returned when inserting a key that is larger than MaxKeySize.
+ ErrKeyTooLarge = errors.New("key too large")
+
+ // ErrValueTooLarge is returned when inserting a value that is larger than MaxValueSize.
+ ErrValueTooLarge = errors.New("value too large")
+
+ // ErrIncompatibleValue is returned when trying create or delete a bucket
+ // on an existing non-bucket key or when trying to create or delete a
+ // non-bucket key on an existing bucket key.
+ ErrIncompatibleValue = errors.New("incompatible value")
+)
diff -Naur --color b/vendor/github.com/boltdb/bolt/freelist.go a/vendor/github.com/boltdb/bolt/freelist.go
--- b/vendor/github.com/boltdb/bolt/freelist.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/boltdb/bolt/freelist.go 2022-11-15 23:06:29.392015899 +0100
@@ -0,0 +1,252 @@
+package bolt
+
+import (
+ "fmt"
+ "sort"
+ "unsafe"
+)
+
+// freelist represents a list of all pages that are available for allocation.
+// It also tracks pages that have been freed but are still in use by open transactions.
+type freelist struct {
+ ids []pgid // all free and available free page ids.
+ pending map[txid][]pgid // mapping of soon-to-be free page ids by tx.
+ cache map[pgid]bool // fast lookup of all free and pending page ids.
+}
+
+// newFreelist returns an empty, initialized freelist.
+func newFreelist() *freelist {
+ return &freelist{
+ pending: make(map[txid][]pgid),
+ cache: make(map[pgid]bool),
+ }
+}
+
+// size returns the size of the page after serialization.
+func (f *freelist) size() int {
+ n := f.count()
+ if n >= 0xFFFF {
+ // The first element will be used to store the count. See freelist.write.
+ n++
+ }
+ return pageHeaderSize + (int(unsafe.Sizeof(pgid(0))) * n)
+}
+
+// count returns count of pages on the freelist
+func (f *freelist) count() int {
+ return f.free_count() + f.pending_count()
+}
+
+// free_count returns count of free pages
+func (f *freelist) free_count() int {
+ return len(f.ids)
+}
+
+// pending_count returns count of pending pages
+func (f *freelist) pending_count() int {
+ var count int
+ for _, list := range f.pending {
+ count += len(list)
+ }
+ return count
+}
+
+// copyall copies into dst a list of all free ids and all pending ids in one sorted list.
+// f.count returns the minimum length required for dst.
+func (f *freelist) copyall(dst []pgid) {
+ m := make(pgids, 0, f.pending_count())
+ for _, list := range f.pending {
+ m = append(m, list...)
+ }
+ sort.Sort(m)
+ mergepgids(dst, f.ids, m)
+}
+
+// allocate returns the starting page id of a contiguous list of pages of a given size.
+// If a contiguous block cannot be found then 0 is returned.
+func (f *freelist) allocate(n int) pgid {
+ if len(f.ids) == 0 {
+ return 0
+ }
+
+ var initial, previd pgid
+ for i, id := range f.ids {
+ if id <= 1 {
+ panic(fmt.Sprintf("invalid page allocation: %d", id))
+ }
+
+ // Reset initial page if this is not contiguous.
+ if previd == 0 || id-previd != 1 {
+ initial = id
+ }
+
+ // If we found a contiguous block then remove it and return it.
+ if (id-initial)+1 == pgid(n) {
+ // If we're allocating off the beginning then take the fast path
+ // and just adjust the existing slice. This will use extra memory
+ // temporarily but the append() in free() will realloc the slice
+ // as is necessary.
+ if (i + 1) == n {
+ f.ids = f.ids[i+1:]
+ } else {
+ copy(f.ids[i-n+1:], f.ids[i+1:])
+ f.ids = f.ids[:len(f.ids)-n]
+ }
+
+ // Remove from the free cache.
+ for i := pgid(0); i < pgid(n); i++ {
+ delete(f.cache, initial+i)
+ }
+
+ return initial
+ }
+
+ previd = id
+ }
+ return 0
+}
+
+// free releases a page and its overflow for a given transaction id.
+// If the page is already free then a panic will occur.
+func (f *freelist) free(txid txid, p *page) {
+ if p.id <= 1 {
+ panic(fmt.Sprintf("cannot free page 0 or 1: %d", p.id))
+ }
+
+ // Free page and all its overflow pages.
+ var ids = f.pending[txid]
+ for id := p.id; id <= p.id+pgid(p.overflow); id++ {
+ // Verify that page is not already free.
+ if f.cache[id] {
+ panic(fmt.Sprintf("page %d already freed", id))
+ }
+
+ // Add to the freelist and cache.
+ ids = append(ids, id)
+ f.cache[id] = true
+ }
+ f.pending[txid] = ids
+}
+
+// release moves all page ids for a transaction id (or older) to the freelist.
+func (f *freelist) release(txid txid) {
+ m := make(pgids, 0)
+ for tid, ids := range f.pending {
+ if tid <= txid {
+ // Move transaction's pending pages to the available freelist.
+ // Don't remove from the cache since the page is still free.
+ m = append(m, ids...)
+ delete(f.pending, tid)
+ }
+ }
+ sort.Sort(m)
+ f.ids = pgids(f.ids).merge(m)
+}
+
+// rollback removes the pages from a given pending tx.
+func (f *freelist) rollback(txid txid) {
+ // Remove page ids from cache.
+ for _, id := range f.pending[txid] {
+ delete(f.cache, id)
+ }
+
+ // Remove pages from pending list.
+ delete(f.pending, txid)
+}
+
+// freed returns whether a given page is in the free list.
+func (f *freelist) freed(pgid pgid) bool {
+ return f.cache[pgid]
+}
+
+// read initializes the freelist from a freelist page.
+func (f *freelist) read(p *page) {
+ // If the page.count is at the max uint16 value (64k) then it's considered
+ // an overflow and the size of the freelist is stored as the first element.
+ idx, count := 0, int(p.count)
+ if count == 0xFFFF {
+ idx = 1
+ count = int(((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[0])
+ }
+
+ // Copy the list of page ids from the freelist.
+ if count == 0 {
+ f.ids = nil
+ } else {
+ ids := ((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[idx:count]
+ f.ids = make([]pgid, len(ids))
+ copy(f.ids, ids)
+
+ // Make sure they're sorted.
+ sort.Sort(pgids(f.ids))
+ }
+
+ // Rebuild the page cache.
+ f.reindex()
+}
+
+// write writes the page ids onto a freelist page. All free and pending ids are
+// saved to disk since in the event of a program crash, all pending ids will
+// become free.
+func (f *freelist) write(p *page) error {
+ // Combine the old free pgids and pgids waiting on an open transaction.
+
+ // Update the header flag.
+ p.flags |= freelistPageFlag
+
+ // The page.count can only hold up to 64k elements so if we overflow that
+ // number then we handle it by putting the size in the first element.
+ lenids := f.count()
+ if lenids == 0 {
+ p.count = uint16(lenids)
+ } else if lenids < 0xFFFF {
+ p.count = uint16(lenids)
+ f.copyall(((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[:])
+ } else {
+ p.count = 0xFFFF
+ ((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[0] = pgid(lenids)
+ f.copyall(((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[1:])
+ }
+
+ return nil
+}
+
+// reload reads the freelist from a page and filters out pending items.
+func (f *freelist) reload(p *page) {
+ f.read(p)
+
+ // Build a cache of only pending pages.
+ pcache := make(map[pgid]bool)
+ for _, pendingIDs := range f.pending {
+ for _, pendingID := range pendingIDs {
+ pcache[pendingID] = true
+ }
+ }
+
+ // Check each page in the freelist and build a new available freelist
+ // with any pages not in the pending lists.
+ var a []pgid
+ for _, id := range f.ids {
+ if !pcache[id] {
+ a = append(a, id)
+ }
+ }
+ f.ids = a
+
+ // Once the available list is rebuilt then rebuild the free cache so that
+ // it includes the available and pending free pages.
+ f.reindex()
+}
+
+// reindex rebuilds the free cache based on available and pending free lists.
+func (f *freelist) reindex() {
+ f.cache = make(map[pgid]bool, len(f.ids))
+ for _, id := range f.ids {
+ f.cache[id] = true
+ }
+ for _, pendingIDs := range f.pending {
+ for _, pendingID := range pendingIDs {
+ f.cache[pendingID] = true
+ }
+ }
+}
diff -Naur --color b/vendor/github.com/boltdb/bolt/.gitignore a/vendor/github.com/boltdb/bolt/.gitignore
--- b/vendor/github.com/boltdb/bolt/.gitignore 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/boltdb/bolt/.gitignore 2022-11-15 23:06:29.392015899 +0100
@@ -0,0 +1,4 @@
+*.prof
+*.test
+*.swp
+/bin/
diff -Naur --color b/vendor/github.com/boltdb/bolt/LICENSE a/vendor/github.com/boltdb/bolt/LICENSE
--- b/vendor/github.com/boltdb/bolt/LICENSE 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/boltdb/bolt/LICENSE 2022-11-15 23:06:29.392015899 +0100
@@ -0,0 +1,20 @@
+The MIT License (MIT)
+
+Copyright (c) 2013 Ben Johnson
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff -Naur --color b/vendor/github.com/boltdb/bolt/Makefile a/vendor/github.com/boltdb/bolt/Makefile
--- b/vendor/github.com/boltdb/bolt/Makefile 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/boltdb/bolt/Makefile 2022-11-15 23:06:29.392015899 +0100
@@ -0,0 +1,18 @@
+BRANCH=`git rev-parse --abbrev-ref HEAD`
+COMMIT=`git rev-parse --short HEAD`
+GOLDFLAGS="-X main.branch $(BRANCH) -X main.commit $(COMMIT)"
+
+default: build
+
+race:
+ @go test -v -race -test.run="TestSimulate_(100op|1000op)"
+
+# go get github.com/kisielk/errcheck
+errcheck:
+ @errcheck -ignorepkg=bytes -ignore=os:Remove github.com/boltdb/bolt
+
+test:
+ @go test -v -cover .
+ @go test -v ./cmd/bolt
+
+.PHONY: fmt test
diff -Naur --color b/vendor/github.com/boltdb/bolt/node.go a/vendor/github.com/boltdb/bolt/node.go
--- b/vendor/github.com/boltdb/bolt/node.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/boltdb/bolt/node.go 2022-11-15 23:06:29.392015899 +0100
@@ -0,0 +1,604 @@
+package bolt
+
+import (
+ "bytes"
+ "fmt"
+ "sort"
+ "unsafe"
+)
+
+// node represents an in-memory, deserialized page.
+type node struct {
+ bucket *Bucket
+ isLeaf bool
+ unbalanced bool
+ spilled bool
+ key []byte
+ pgid pgid
+ parent *node
+ children nodes
+ inodes inodes
+}
+
+// root returns the top-level node this node is attached to.
+func (n *node) root() *node {
+ if n.parent == nil {
+ return n
+ }
+ return n.parent.root()
+}
+
+// minKeys returns the minimum number of inodes this node should have.
+func (n *node) minKeys() int {
+ if n.isLeaf {
+ return 1
+ }
+ return 2
+}
+
+// size returns the size of the node after serialization.
+func (n *node) size() int {
+ sz, elsz := pageHeaderSize, n.pageElementSize()
+ for i := 0; i < len(n.inodes); i++ {
+ item := &n.inodes[i]
+ sz += elsz + len(item.key) + len(item.value)
+ }
+ return sz
+}
+
+// sizeLessThan returns true if the node is less than a given size.
+// This is an optimization to avoid calculating a large node when we only need
+// to know if it fits inside a certain page size.
+func (n *node) sizeLessThan(v int) bool {
+ sz, elsz := pageHeaderSize, n.pageElementSize()
+ for i := 0; i < len(n.inodes); i++ {
+ item := &n.inodes[i]
+ sz += elsz + len(item.key) + len(item.value)
+ if sz >= v {
+ return false
+ }
+ }
+ return true
+}
+
+// pageElementSize returns the size of each page element based on the type of node.
+func (n *node) pageElementSize() int {
+ if n.isLeaf {
+ return leafPageElementSize
+ }
+ return branchPageElementSize
+}
+
+// childAt returns the child node at a given index.
+func (n *node) childAt(index int) *node {
+ if n.isLeaf {
+ panic(fmt.Sprintf("invalid childAt(%d) on a leaf node", index))
+ }
+ return n.bucket.node(n.inodes[index].pgid, n)
+}
+
+// childIndex returns the index of a given child node.
+func (n *node) childIndex(child *node) int {
+ index := sort.Search(len(n.inodes), func(i int) bool { return bytes.Compare(n.inodes[i].key, child.key) != -1 })
+ return index
+}
+
+// numChildren returns the number of children.
+func (n *node) numChildren() int {
+ return len(n.inodes)
+}
+
+// nextSibling returns the next node with the same parent.
+func (n *node) nextSibling() *node {
+ if n.parent == nil {
+ return nil
+ }
+ index := n.parent.childIndex(n)
+ if index >= n.parent.numChildren()-1 {
+ return nil
+ }
+ return n.parent.childAt(index + 1)
+}
+
+// prevSibling returns the previous node with the same parent.
+func (n *node) prevSibling() *node {
+ if n.parent == nil {
+ return nil
+ }
+ index := n.parent.childIndex(n)
+ if index == 0 {
+ return nil
+ }
+ return n.parent.childAt(index - 1)
+}
+
+// put inserts a key/value.
+func (n *node) put(oldKey, newKey, value []byte, pgid pgid, flags uint32) {
+ if pgid >= n.bucket.tx.meta.pgid {
+ panic(fmt.Sprintf("pgid (%d) above high water mark (%d)", pgid, n.bucket.tx.meta.pgid))
+ } else if len(oldKey) <= 0 {
+ panic("put: zero-length old key")
+ } else if len(newKey) <= 0 {
+ panic("put: zero-length new key")
+ }
+
+ // Find insertion index.
+ index := sort.Search(len(n.inodes), func(i int) bool { return bytes.Compare(n.inodes[i].key, oldKey) != -1 })
+
+ // Add capacity and shift nodes if we don't have an exact match and need to insert.
+ exact := (len(n.inodes) > 0 && index < len(n.inodes) && bytes.Equal(n.inodes[index].key, oldKey))
+ if !exact {
+ n.inodes = append(n.inodes, inode{})
+ copy(n.inodes[index+1:], n.inodes[index:])
+ }
+
+ inode := &n.inodes[index]
+ inode.flags = flags
+ inode.key = newKey
+ inode.value = value
+ inode.pgid = pgid
+ _assert(len(inode.key) > 0, "put: zero-length inode key")
+}
+
+// del removes a key from the node.
+func (n *node) del(key []byte) {
+ // Find index of key.
+ index := sort.Search(len(n.inodes), func(i int) bool { return bytes.Compare(n.inodes[i].key, key) != -1 })
+
+ // Exit if the key isn't found.
+ if index >= len(n.inodes) || !bytes.Equal(n.inodes[index].key, key) {
+ return
+ }
+
+ // Delete inode from the node.
+ n.inodes = append(n.inodes[:index], n.inodes[index+1:]...)
+
+ // Mark the node as needing rebalancing.
+ n.unbalanced = true
+}
+
+// read initializes the node from a page.
+func (n *node) read(p *page) {
+ n.pgid = p.id
+ n.isLeaf = ((p.flags & leafPageFlag) != 0)
+ n.inodes = make(inodes, int(p.count))
+
+ for i := 0; i < int(p.count); i++ {
+ inode := &n.inodes[i]
+ if n.isLeaf {
+ elem := p.leafPageElement(uint16(i))
+ inode.flags = elem.flags
+ inode.key = elem.key()
+ inode.value = elem.value()
+ } else {
+ elem := p.branchPageElement(uint16(i))
+ inode.pgid = elem.pgid
+ inode.key = elem.key()
+ }
+ _assert(len(inode.key) > 0, "read: zero-length inode key")
+ }
+
+ // Save first key so we can find the node in the parent when we spill.
+ if len(n.inodes) > 0 {
+ n.key = n.inodes[0].key
+ _assert(len(n.key) > 0, "read: zero-length node key")
+ } else {
+ n.key = nil
+ }
+}
+
+// write writes the items onto one or more pages.
+func (n *node) write(p *page) {
+ // Initialize page.
+ if n.isLeaf {
+ p.flags |= leafPageFlag
+ } else {
+ p.flags |= branchPageFlag
+ }
+
+ if len(n.inodes) >= 0xFFFF {
+ panic(fmt.Sprintf("inode overflow: %d (pgid=%d)", len(n.inodes), p.id))
+ }
+ p.count = uint16(len(n.inodes))
+
+ // Stop here if there are no items to write.
+ if p.count == 0 {
+ return
+ }
+
+ // Loop over each item and write it to the page.
+ b := (*[maxAllocSize]byte)(unsafe.Pointer(&p.ptr))[n.pageElementSize()*len(n.inodes):]
+ for i, item := range n.inodes {
+ _assert(len(item.key) > 0, "write: zero-length inode key")
+
+ // Write the page element.
+ if n.isLeaf {
+ elem := p.leafPageElement(uint16(i))
+ elem.pos = uint32(uintptr(unsafe.Pointer(&b[0])) - uintptr(unsafe.Pointer(elem)))
+ elem.flags = item.flags
+ elem.ksize = uint32(len(item.key))
+ elem.vsize = uint32(len(item.value))
+ } else {
+ elem := p.branchPageElement(uint16(i))
+ elem.pos = uint32(uintptr(unsafe.Pointer(&b[0])) - uintptr(unsafe.Pointer(elem)))
+ elem.ksize = uint32(len(item.key))
+ elem.pgid = item.pgid
+ _assert(elem.pgid != p.id, "write: circular dependency occurred")
+ }
+
+ // If the length of key+value is larger than the max allocation size
+ // then we need to reallocate the byte array pointer.
+ //
+ // See: https://github.com/boltdb/bolt/pull/335
+ klen, vlen := len(item.key), len(item.value)
+ if len(b) < klen+vlen {
+ b = (*[maxAllocSize]byte)(unsafe.Pointer(&b[0]))[:]
+ }
+
+ // Write data for the element to the end of the page.
+ copy(b[0:], item.key)
+ b = b[klen:]
+ copy(b[0:], item.value)
+ b = b[vlen:]
+ }
+
+ // DEBUG ONLY: n.dump()
+}
+
+// split breaks up a node into multiple smaller nodes, if appropriate.
+// This should only be called from the spill() function.
+func (n *node) split(pageSize int) []*node {
+ var nodes []*node
+
+ node := n
+ for {
+ // Split node into two.
+ a, b := node.splitTwo(pageSize)
+ nodes = append(nodes, a)
+
+ // If we can't split then exit the loop.
+ if b == nil {
+ break
+ }
+
+ // Set node to b so it gets split on the next iteration.
+ node = b
+ }
+
+ return nodes
+}
+
+// splitTwo breaks up a node into two smaller nodes, if appropriate.
+// This should only be called from the split() function.
+func (n *node) splitTwo(pageSize int) (*node, *node) {
+ // Ignore the split if the page doesn't have at least enough nodes for
+ // two pages or if the nodes can fit in a single page.
+ if len(n.inodes) <= (minKeysPerPage*2) || n.sizeLessThan(pageSize) {
+ return n, nil
+ }
+
+ // Determine the threshold before starting a new node.
+ var fillPercent = n.bucket.FillPercent
+ if fillPercent < minFillPercent {
+ fillPercent = minFillPercent
+ } else if fillPercent > maxFillPercent {
+ fillPercent = maxFillPercent
+ }
+ threshold := int(float64(pageSize) * fillPercent)
+
+ // Determine split position and sizes of the two pages.
+ splitIndex, _ := n.splitIndex(threshold)
+
+ // Split node into two separate nodes.
+ // If there's no parent then we'll need to create one.
+ if n.parent == nil {
+ n.parent = &node{bucket: n.bucket, children: []*node{n}}
+ }
+
+ // Create a new node and add it to the parent.
+ next := &node{bucket: n.bucket, isLeaf: n.isLeaf, parent: n.parent}
+ n.parent.children = append(n.parent.children, next)
+
+ // Split inodes across two nodes.
+ next.inodes = n.inodes[splitIndex:]
+ n.inodes = n.inodes[:splitIndex]
+
+ // Update the statistics.
+ n.bucket.tx.stats.Split++
+
+ return n, next
+}
+
+// splitIndex finds the position where a page will fill a given threshold.
+// It returns the index as well as the size of the first page.
+// This is only be called from split().
+func (n *node) splitIndex(threshold int) (index, sz int) {
+ sz = pageHeaderSize
+
+ // Loop until we only have the minimum number of keys required for the second page.
+ for i := 0; i < len(n.inodes)-minKeysPerPage; i++ {
+ index = i
+ inode := n.inodes[i]
+ elsize := n.pageElementSize() + len(inode.key) + len(inode.value)
+
+ // If we have at least the minimum number of keys and adding another
+ // node would put us over the threshold then exit and return.
+ if i >= minKeysPerPage && sz+elsize > threshold {
+ break
+ }
+
+ // Add the element size to the total size.
+ sz += elsize
+ }
+
+ return
+}
+
+// spill writes the nodes to dirty pages and splits nodes as it goes.
+// Returns an error if dirty pages cannot be allocated.
+func (n *node) spill() error {
+ var tx = n.bucket.tx
+ if n.spilled {
+ return nil
+ }
+
+ // Spill child nodes first. Child nodes can materialize sibling nodes in
+ // the case of split-merge so we cannot use a range loop. We have to check
+ // the children size on every loop iteration.
+ sort.Sort(n.children)
+ for i := 0; i < len(n.children); i++ {
+ if err := n.children[i].spill(); err != nil {
+ return err
+ }
+ }
+
+ // We no longer need the child list because it's only used for spill tracking.
+ n.children = nil
+
+ // Split nodes into appropriate sizes. The first node will always be n.
+ var nodes = n.split(tx.db.pageSize)
+ for _, node := range nodes {
+ // Add node's page to the freelist if it's not new.
+ if node.pgid > 0 {
+ tx.db.freelist.free(tx.meta.txid, tx.page(node.pgid))
+ node.pgid = 0
+ }
+
+ // Allocate contiguous space for the node.
+ p, err := tx.allocate((node.size() / tx.db.pageSize) + 1)
+ if err != nil {
+ return err
+ }
+
+ // Write the node.
+ if p.id >= tx.meta.pgid {
+ panic(fmt.Sprintf("pgid (%d) above high water mark (%d)", p.id, tx.meta.pgid))
+ }
+ node.pgid = p.id
+ node.write(p)
+ node.spilled = true
+
+ // Insert into parent inodes.
+ if node.parent != nil {
+ var key = node.key
+ if key == nil {
+ key = node.inodes[0].key
+ }
+
+ node.parent.put(key, node.inodes[0].key, nil, node.pgid, 0)
+ node.key = node.inodes[0].key
+ _assert(len(node.key) > 0, "spill: zero-length node key")
+ }
+
+ // Update the statistics.
+ tx.stats.Spill++
+ }
+
+ // If the root node split and created a new root then we need to spill that
+ // as well. We'll clear out the children to make sure it doesn't try to respill.
+ if n.parent != nil && n.parent.pgid == 0 {
+ n.children = nil
+ return n.parent.spill()
+ }
+
+ return nil
+}
+
+// rebalance attempts to combine the node with sibling nodes if the node fill
+// size is below a threshold or if there are not enough keys.
+func (n *node) rebalance() {
+ if !n.unbalanced {
+ return
+ }
+ n.unbalanced = false
+
+ // Update statistics.
+ n.bucket.tx.stats.Rebalance++
+
+ // Ignore if node is above threshold (25%) and has enough keys.
+ var threshold = n.bucket.tx.db.pageSize / 4
+ if n.size() > threshold && len(n.inodes) > n.minKeys() {
+ return
+ }
+
+ // Root node has special handling.
+ if n.parent == nil {
+ // If root node is a branch and only has one node then collapse it.
+ if !n.isLeaf && len(n.inodes) == 1 {
+ // Move root's child up.
+ child := n.bucket.node(n.inodes[0].pgid, n)
+ n.isLeaf = child.isLeaf
+ n.inodes = child.inodes[:]
+ n.children = child.children
+
+ // Reparent all child nodes being moved.
+ for _, inode := range n.inodes {
+ if child, ok := n.bucket.nodes[inode.pgid]; ok {
+ child.parent = n
+ }
+ }
+
+ // Remove old child.
+ child.parent = nil
+ delete(n.bucket.nodes, child.pgid)
+ child.free()
+ }
+
+ return
+ }
+
+ // If node has no keys then just remove it.
+ if n.numChildren() == 0 {
+ n.parent.del(n.key)
+ n.parent.removeChild(n)
+ delete(n.bucket.nodes, n.pgid)
+ n.free()
+ n.parent.rebalance()
+ return
+ }
+
+ _assert(n.parent.numChildren() > 1, "parent must have at least 2 children")
+
+ // Destination node is right sibling if idx == 0, otherwise left sibling.
+ var target *node
+ var useNextSibling = (n.parent.childIndex(n) == 0)
+ if useNextSibling {
+ target = n.nextSibling()
+ } else {
+ target = n.prevSibling()
+ }
+
+ // If both this node and the target node are too small then merge them.
+ if useNextSibling {
+ // Reparent all child nodes being moved.
+ for _, inode := range target.inodes {
+ if child, ok := n.bucket.nodes[inode.pgid]; ok {
+ child.parent.removeChild(child)
+ child.parent = n
+ child.parent.children = append(child.parent.children, child)
+ }
+ }
+
+ // Copy over inodes from target and remove target.
+ n.inodes = append(n.inodes, target.inodes...)
+ n.parent.del(target.key)
+ n.parent.removeChild(target)
+ delete(n.bucket.nodes, target.pgid)
+ target.free()
+ } else {
+ // Reparent all child nodes being moved.
+ for _, inode := range n.inodes {
+ if child, ok := n.bucket.nodes[inode.pgid]; ok {
+ child.parent.removeChild(child)
+ child.parent = target
+ child.parent.children = append(child.parent.children, child)
+ }
+ }
+
+ // Copy over inodes to target and remove node.
+ target.inodes = append(target.inodes, n.inodes...)
+ n.parent.del(n.key)
+ n.parent.removeChild(n)
+ delete(n.bucket.nodes, n.pgid)
+ n.free()
+ }
+
+ // Either this node or the target node was deleted from the parent so rebalance it.
+ n.parent.rebalance()
+}
+
+// removes a node from the list of in-memory children.
+// This does not affect the inodes.
+func (n *node) removeChild(target *node) {
+ for i, child := range n.children {
+ if child == target {
+ n.children = append(n.children[:i], n.children[i+1:]...)
+ return
+ }
+ }
+}
+
+// dereference causes the node to copy all its inode key/value references to heap memory.
+// This is required when the mmap is reallocated so inodes are not pointing to stale data.
+func (n *node) dereference() {
+ if n.key != nil {
+ key := make([]byte, len(n.key))
+ copy(key, n.key)
+ n.key = key
+ _assert(n.pgid == 0 || len(n.key) > 0, "dereference: zero-length node key on existing node")
+ }
+
+ for i := range n.inodes {
+ inode := &n.inodes[i]
+
+ key := make([]byte, len(inode.key))
+ copy(key, inode.key)
+ inode.key = key
+ _assert(len(inode.key) > 0, "dereference: zero-length inode key")
+
+ value := make([]byte, len(inode.value))
+ copy(value, inode.value)
+ inode.value = value
+ }
+
+ // Recursively dereference children.
+ for _, child := range n.children {
+ child.dereference()
+ }
+
+ // Update statistics.
+ n.bucket.tx.stats.NodeDeref++
+}
+
+// free adds the node's underlying page to the freelist.
+func (n *node) free() {
+ if n.pgid != 0 {
+ n.bucket.tx.db.freelist.free(n.bucket.tx.meta.txid, n.bucket.tx.page(n.pgid))
+ n.pgid = 0
+ }
+}
+
+// dump writes the contents of the node to STDERR for debugging purposes.
+/*
+func (n *node) dump() {
+ // Write node header.
+ var typ = "branch"
+ if n.isLeaf {
+ typ = "leaf"
+ }
+ warnf("[NODE %d {type=%s count=%d}]", n.pgid, typ, len(n.inodes))
+
+ // Write out abbreviated version of each item.
+ for _, item := range n.inodes {
+ if n.isLeaf {
+ if item.flags&bucketLeafFlag != 0 {
+ bucket := (*bucket)(unsafe.Pointer(&item.value[0]))
+ warnf("+L %08x -> (bucket root=%d)", trunc(item.key, 4), bucket.root)
+ } else {
+ warnf("+L %08x -> %08x", trunc(item.key, 4), trunc(item.value, 4))
+ }
+ } else {
+ warnf("+B %08x -> pgid=%d", trunc(item.key, 4), item.pgid)
+ }
+ }
+ warn("")
+}
+*/
+
+type nodes []*node
+
+func (s nodes) Len() int { return len(s) }
+func (s nodes) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
+func (s nodes) Less(i, j int) bool { return bytes.Compare(s[i].inodes[0].key, s[j].inodes[0].key) == -1 }
+
+// inode represents an internal node inside of a node.
+// It can be used to point to elements in a page or point
+// to an element which hasn't been added to a page yet.
+type inode struct {
+ flags uint32
+ pgid pgid
+ key []byte
+ value []byte
+}
+
+type inodes []inode
diff -Naur --color b/vendor/github.com/boltdb/bolt/page.go a/vendor/github.com/boltdb/bolt/page.go
--- b/vendor/github.com/boltdb/bolt/page.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/boltdb/bolt/page.go 2022-11-15 23:06:29.392015899 +0100
@@ -0,0 +1,197 @@
+package bolt
+
+import (
+ "fmt"
+ "os"
+ "sort"
+ "unsafe"
+)
+
+const pageHeaderSize = int(unsafe.Offsetof(((*page)(nil)).ptr))
+
+const minKeysPerPage = 2
+
+const branchPageElementSize = int(unsafe.Sizeof(branchPageElement{}))
+const leafPageElementSize = int(unsafe.Sizeof(leafPageElement{}))
+
+const (
+ branchPageFlag = 0x01
+ leafPageFlag = 0x02
+ metaPageFlag = 0x04
+ freelistPageFlag = 0x10
+)
+
+const (
+ bucketLeafFlag = 0x01
+)
+
+type pgid uint64
+
+type page struct {
+ id pgid
+ flags uint16
+ count uint16
+ overflow uint32
+ ptr uintptr
+}
+
+// typ returns a human readable page type string used for debugging.
+func (p *page) typ() string {
+ if (p.flags & branchPageFlag) != 0 {
+ return "branch"
+ } else if (p.flags & leafPageFlag) != 0 {
+ return "leaf"
+ } else if (p.flags & metaPageFlag) != 0 {
+ return "meta"
+ } else if (p.flags & freelistPageFlag) != 0 {
+ return "freelist"
+ }
+ return fmt.Sprintf("unknown<%02x>", p.flags)
+}
+
+// meta returns a pointer to the metadata section of the page.
+func (p *page) meta() *meta {
+ return (*meta)(unsafe.Pointer(&p.ptr))
+}
+
+// leafPageElement retrieves the leaf node by index
+func (p *page) leafPageElement(index uint16) *leafPageElement {
+ n := &((*[0x7FFFFFF]leafPageElement)(unsafe.Pointer(&p.ptr)))[index]
+ return n
+}
+
+// leafPageElements retrieves a list of leaf nodes.
+func (p *page) leafPageElements() []leafPageElement {
+ if p.count == 0 {
+ return nil
+ }
+ return ((*[0x7FFFFFF]leafPageElement)(unsafe.Pointer(&p.ptr)))[:]
+}
+
+// branchPageElement retrieves the branch node by index
+func (p *page) branchPageElement(index uint16) *branchPageElement {
+ return &((*[0x7FFFFFF]branchPageElement)(unsafe.Pointer(&p.ptr)))[index]
+}
+
+// branchPageElements retrieves a list of branch nodes.
+func (p *page) branchPageElements() []branchPageElement {
+ if p.count == 0 {
+ return nil
+ }
+ return ((*[0x7FFFFFF]branchPageElement)(unsafe.Pointer(&p.ptr)))[:]
+}
+
+// dump writes n bytes of the page to STDERR as hex output.
+func (p *page) hexdump(n int) {
+ buf := (*[maxAllocSize]byte)(unsafe.Pointer(p))[:n]
+ fmt.Fprintf(os.Stderr, "%x\n", buf)
+}
+
+type pages []*page
+
+func (s pages) Len() int { return len(s) }
+func (s pages) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
+func (s pages) Less(i, j int) bool { return s[i].id < s[j].id }
+
+// branchPageElement represents a node on a branch page.
+type branchPageElement struct {
+ pos uint32
+ ksize uint32
+ pgid pgid
+}
+
+// key returns a byte slice of the node key.
+func (n *branchPageElement) key() []byte {
+ buf := (*[maxAllocSize]byte)(unsafe.Pointer(n))
+ return (*[maxAllocSize]byte)(unsafe.Pointer(&buf[n.pos]))[:n.ksize]
+}
+
+// leafPageElement represents a node on a leaf page.
+type leafPageElement struct {
+ flags uint32
+ pos uint32
+ ksize uint32
+ vsize uint32
+}
+
+// key returns a byte slice of the node key.
+func (n *leafPageElement) key() []byte {
+ buf := (*[maxAllocSize]byte)(unsafe.Pointer(n))
+ return (*[maxAllocSize]byte)(unsafe.Pointer(&buf[n.pos]))[:n.ksize:n.ksize]
+}
+
+// value returns a byte slice of the node value.
+func (n *leafPageElement) value() []byte {
+ buf := (*[maxAllocSize]byte)(unsafe.Pointer(n))
+ return (*[maxAllocSize]byte)(unsafe.Pointer(&buf[n.pos+n.ksize]))[:n.vsize:n.vsize]
+}
+
+// PageInfo represents human readable information about a page.
+type PageInfo struct {
+ ID int
+ Type string
+ Count int
+ OverflowCount int
+}
+
+type pgids []pgid
+
+func (s pgids) Len() int { return len(s) }
+func (s pgids) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
+func (s pgids) Less(i, j int) bool { return s[i] < s[j] }
+
+// merge returns the sorted union of a and b.
+func (a pgids) merge(b pgids) pgids {
+ // Return the opposite slice if one is nil.
+ if len(a) == 0 {
+ return b
+ }
+ if len(b) == 0 {
+ return a
+ }
+ merged := make(pgids, len(a)+len(b))
+ mergepgids(merged, a, b)
+ return merged
+}
+
+// mergepgids copies the sorted union of a and b into dst.
+// If dst is too small, it panics.
+func mergepgids(dst, a, b pgids) {
+ if len(dst) < len(a)+len(b) {
+ panic(fmt.Errorf("mergepgids bad len %d < %d + %d", len(dst), len(a), len(b)))
+ }
+ // Copy in the opposite slice if one is nil.
+ if len(a) == 0 {
+ copy(dst, b)
+ return
+ }
+ if len(b) == 0 {
+ copy(dst, a)
+ return
+ }
+
+ // Merged will hold all elements from both lists.
+ merged := dst[:0]
+
+ // Assign lead to the slice with a lower starting value, follow to the higher value.
+ lead, follow := a, b
+ if b[0] < a[0] {
+ lead, follow = b, a
+ }
+
+ // Continue while there are elements in the lead.
+ for len(lead) > 0 {
+ // Merge largest prefix of lead that is ahead of follow[0].
+ n := sort.Search(len(lead), func(i int) bool { return lead[i] > follow[0] })
+ merged = append(merged, lead[:n]...)
+ if n >= len(lead) {
+ break
+ }
+
+ // Swap lead and follow.
+ lead, follow = follow, lead[n:]
+ }
+
+ // Append what's left in follow.
+ _ = append(merged, follow...)
+}
diff -Naur --color b/vendor/github.com/boltdb/bolt/README.md a/vendor/github.com/boltdb/bolt/README.md
--- b/vendor/github.com/boltdb/bolt/README.md 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/boltdb/bolt/README.md 2022-11-15 23:06:29.392015899 +0100
@@ -0,0 +1,916 @@
+Bolt [![Coverage Status](https://coveralls.io/repos/boltdb/bolt/badge.svg?branch=master)](https://coveralls.io/r/boltdb/bolt?branch=master) [![GoDoc](https://godoc.org/github.com/boltdb/bolt?status.svg)](https://godoc.org/github.com/boltdb/bolt) ![Version](https://img.shields.io/badge/version-1.2.1-green.svg)
+====
+
+Bolt is a pure Go key/value store inspired by [Howard Chu's][hyc_symas]
+[LMDB project][lmdb]. The goal of the project is to provide a simple,
+fast, and reliable database for projects that don't require a full database
+server such as Postgres or MySQL.
+
+Since Bolt is meant to be used as such a low-level piece of functionality,
+simplicity is key. The API will be small and only focus on getting values
+and setting values. That's it.
+
+[hyc_symas]: https://twitter.com/hyc_symas
+[lmdb]: http://symas.com/mdb/
+
+## Project Status
+
+Bolt is stable, the API is fixed, and the file format is fixed. Full unit
+test coverage and randomized black box testing are used to ensure database
+consistency and thread safety. Bolt is currently used in high-load production
+environments serving databases as large as 1TB. Many companies such as
+Shopify and Heroku use Bolt-backed services every day.
+
+## Table of Contents
+
+- [Getting Started](#getting-started)
+ - [Installing](#installing)
+ - [Opening a database](#opening-a-database)
+ - [Transactions](#transactions)
+ - [Read-write transactions](#read-write-transactions)
+ - [Read-only transactions](#read-only-transactions)
+ - [Batch read-write transactions](#batch-read-write-transactions)
+ - [Managing transactions manually](#managing-transactions-manually)
+ - [Using buckets](#using-buckets)
+ - [Using key/value pairs](#using-keyvalue-pairs)
+ - [Autoincrementing integer for the bucket](#autoincrementing-integer-for-the-bucket)
+ - [Iterating over keys](#iterating-over-keys)
+ - [Prefix scans](#prefix-scans)
+ - [Range scans](#range-scans)
+ - [ForEach()](#foreach)
+ - [Nested buckets](#nested-buckets)
+ - [Database backups](#database-backups)
+ - [Statistics](#statistics)
+ - [Read-Only Mode](#read-only-mode)
+ - [Mobile Use (iOS/Android)](#mobile-use-iosandroid)
+- [Resources](#resources)
+- [Comparison with other databases](#comparison-with-other-databases)
+ - [Postgres, MySQL, & other relational databases](#postgres-mysql--other-relational-databases)
+ - [LevelDB, RocksDB](#leveldb-rocksdb)
+ - [LMDB](#lmdb)
+- [Caveats & Limitations](#caveats--limitations)
+- [Reading the Source](#reading-the-source)
+- [Other Projects Using Bolt](#other-projects-using-bolt)
+
+## Getting Started
+
+### Installing
+
+To start using Bolt, install Go and run `go get`:
+
+```sh
+$ go get github.com/boltdb/bolt/...
+```
+
+This will retrieve the library and install the `bolt` command line utility into
+your `$GOBIN` path.
+
+
+### Opening a database
+
+The top-level object in Bolt is a `DB`. It is represented as a single file on
+your disk and represents a consistent snapshot of your data.
+
+To open your database, simply use the `bolt.Open()` function:
+
+```go
+package main
+
+import (
+ "log"
+
+ "github.com/boltdb/bolt"
+)
+
+func main() {
+ // Open the my.db data file in your current directory.
+ // It will be created if it doesn't exist.
+ db, err := bolt.Open("my.db", 0600, nil)
+ if err != nil {
+ log.Fatal(err)
+ }
+ defer db.Close()
+
+ ...
+}
+```
+
+Please note that Bolt obtains a file lock on the data file so multiple processes
+cannot open the same database at the same time. Opening an already open Bolt
+database will cause it to hang until the other process closes it. To prevent
+an indefinite wait you can pass a timeout option to the `Open()` function:
+
+```go
+db, err := bolt.Open("my.db", 0600, &bolt.Options{Timeout: 1 * time.Second})
+```
+
+
+### Transactions
+
+Bolt allows only one read-write transaction at a time but allows as many
+read-only transactions as you want at a time. Each transaction has a consistent
+view of the data as it existed when the transaction started.
+
+Individual transactions and all objects created from them (e.g. buckets, keys)
+are not thread safe. To work with data in multiple goroutines you must start
+a transaction for each one or use locking to ensure only one goroutine accesses
+a transaction at a time. Creating transaction from the `DB` is thread safe.
+
+Read-only transactions and read-write transactions should not depend on one
+another and generally shouldn't be opened simultaneously in the same goroutine.
+This can cause a deadlock as the read-write transaction needs to periodically
+re-map the data file but it cannot do so while a read-only transaction is open.
+
+
+#### Read-write transactions
+
+To start a read-write transaction, you can use the `DB.Update()` function:
+
+```go
+err := db.Update(func(tx *bolt.Tx) error {
+ ...
+ return nil
+})
+```
+
+Inside the closure, you have a consistent view of the database. You commit the
+transaction by returning `nil` at the end. You can also rollback the transaction
+at any point by returning an error. All database operations are allowed inside
+a read-write transaction.
+
+Always check the return error as it will report any disk failures that can cause
+your transaction to not complete. If you return an error within your closure
+it will be passed through.
+
+
+#### Read-only transactions
+
+To start a read-only transaction, you can use the `DB.View()` function:
+
+```go
+err := db.View(func(tx *bolt.Tx) error {
+ ...
+ return nil
+})
+```
+
+You also get a consistent view of the database within this closure, however,
+no mutating operations are allowed within a read-only transaction. You can only
+retrieve buckets, retrieve values, and copy the database within a read-only
+transaction.
+
+
+#### Batch read-write transactions
+
+Each `DB.Update()` waits for disk to commit the writes. This overhead
+can be minimized by combining multiple updates with the `DB.Batch()`
+function:
+
+```go
+err := db.Batch(func(tx *bolt.Tx) error {
+ ...
+ return nil
+})
+```
+
+Concurrent Batch calls are opportunistically combined into larger
+transactions. Batch is only useful when there are multiple goroutines
+calling it.
+
+The trade-off is that `Batch` can call the given
+function multiple times, if parts of the transaction fail. The
+function must be idempotent and side effects must take effect only
+after a successful return from `DB.Batch()`.
+
+For example: don't display messages from inside the function, instead
+set variables in the enclosing scope:
+
+```go
+var id uint64
+err := db.Batch(func(tx *bolt.Tx) error {
+ // Find last key in bucket, decode as bigendian uint64, increment
+ // by one, encode back to []byte, and add new key.
+ ...
+ id = newValue
+ return nil
+})
+if err != nil {
+ return ...
+}
+fmt.Println("Allocated ID %d", id)
+```
+
+
+#### Managing transactions manually
+
+The `DB.View()` and `DB.Update()` functions are wrappers around the `DB.Begin()`
+function. These helper functions will start the transaction, execute a function,
+and then safely close your transaction if an error is returned. This is the
+recommended way to use Bolt transactions.
+
+However, sometimes you may want to manually start and end your transactions.
+You can use the `DB.Begin()` function directly but **please** be sure to close
+the transaction.
+
+```go
+// Start a writable transaction.
+tx, err := db.Begin(true)
+if err != nil {
+ return err
+}
+defer tx.Rollback()
+
+// Use the transaction...
+_, err := tx.CreateBucket([]byte("MyBucket"))
+if err != nil {
+ return err
+}
+
+// Commit the transaction and check for error.
+if err := tx.Commit(); err != nil {
+ return err
+}
+```
+
+The first argument to `DB.Begin()` is a boolean stating if the transaction
+should be writable.
+
+
+### Using buckets
+
+Buckets are collections of key/value pairs within the database. All keys in a
+bucket must be unique. You can create a bucket using the `DB.CreateBucket()`
+function:
+
+```go
+db.Update(func(tx *bolt.Tx) error {
+ b, err := tx.CreateBucket([]byte("MyBucket"))
+ if err != nil {
+ return fmt.Errorf("create bucket: %s", err)
+ }
+ return nil
+})
+```
+
+You can also create a bucket only if it doesn't exist by using the
+`Tx.CreateBucketIfNotExists()` function. It's a common pattern to call this
+function for all your top-level buckets after you open your database so you can
+guarantee that they exist for future transactions.
+
+To delete a bucket, simply call the `Tx.DeleteBucket()` function.
+
+
+### Using key/value pairs
+
+To save a key/value pair to a bucket, use the `Bucket.Put()` function:
+
+```go
+db.Update(func(tx *bolt.Tx) error {
+ b := tx.Bucket([]byte("MyBucket"))
+ err := b.Put([]byte("answer"), []byte("42"))
+ return err
+})
+```
+
+This will set the value of the `"answer"` key to `"42"` in the `MyBucket`
+bucket. To retrieve this value, we can use the `Bucket.Get()` function:
+
+```go
+db.View(func(tx *bolt.Tx) error {
+ b := tx.Bucket([]byte("MyBucket"))
+ v := b.Get([]byte("answer"))
+ fmt.Printf("The answer is: %s\n", v)
+ return nil
+})
+```
+
+The `Get()` function does not return an error because its operation is
+guaranteed to work (unless there is some kind of system failure). If the key
+exists then it will return its byte slice value. If it doesn't exist then it
+will return `nil`. It's important to note that you can have a zero-length value
+set to a key which is different than the key not existing.
+
+Use the `Bucket.Delete()` function to delete a key from the bucket.
+
+Please note that values returned from `Get()` are only valid while the
+transaction is open. If you need to use a value outside of the transaction
+then you must use `copy()` to copy it to another byte slice.
+
+
+### Autoincrementing integer for the bucket
+By using the `NextSequence()` function, you can let Bolt determine a sequence
+which can be used as the unique identifier for your key/value pairs. See the
+example below.
+
+```go
+// CreateUser saves u to the store. The new user ID is set on u once the data is persisted.
+func (s *Store) CreateUser(u *User) error {
+ return s.db.Update(func(tx *bolt.Tx) error {
+ // Retrieve the users bucket.
+ // This should be created when the DB is first opened.
+ b := tx.Bucket([]byte("users"))
+
+ // Generate ID for the user.
+ // This returns an error only if the Tx is closed or not writeable.
+ // That can't happen in an Update() call so I ignore the error check.
+ id, _ := b.NextSequence()
+ u.ID = int(id)
+
+ // Marshal user data into bytes.
+ buf, err := json.Marshal(u)
+ if err != nil {
+ return err
+ }
+
+ // Persist bytes to users bucket.
+ return b.Put(itob(u.ID), buf)
+ })
+}
+
+// itob returns an 8-byte big endian representation of v.
+func itob(v int) []byte {
+ b := make([]byte, 8)
+ binary.BigEndian.PutUint64(b, uint64(v))
+ return b
+}
+
+type User struct {
+ ID int
+ ...
+}
+```
+
+### Iterating over keys
+
+Bolt stores its keys in byte-sorted order within a bucket. This makes sequential
+iteration over these keys extremely fast. To iterate over keys we'll use a
+`Cursor`:
+
+```go
+db.View(func(tx *bolt.Tx) error {
+ // Assume bucket exists and has keys
+ b := tx.Bucket([]byte("MyBucket"))
+
+ c := b.Cursor()
+
+ for k, v := c.First(); k != nil; k, v = c.Next() {
+ fmt.Printf("key=%s, value=%s\n", k, v)
+ }
+
+ return nil
+})
+```
+
+The cursor allows you to move to a specific point in the list of keys and move
+forward or backward through the keys one at a time.
+
+The following functions are available on the cursor:
+
+```
+First() Move to the first key.
+Last() Move to the last key.
+Seek() Move to a specific key.
+Next() Move to the next key.
+Prev() Move to the previous key.
+```
+
+Each of those functions has a return signature of `(key []byte, value []byte)`.
+When you have iterated to the end of the cursor then `Next()` will return a
+`nil` key. You must seek to a position using `First()`, `Last()`, or `Seek()`
+before calling `Next()` or `Prev()`. If you do not seek to a position then
+these functions will return a `nil` key.
+
+During iteration, if the key is non-`nil` but the value is `nil`, that means
+the key refers to a bucket rather than a value. Use `Bucket.Bucket()` to
+access the sub-bucket.
+
+
+#### Prefix scans
+
+To iterate over a key prefix, you can combine `Seek()` and `bytes.HasPrefix()`:
+
+```go
+db.View(func(tx *bolt.Tx) error {
+ // Assume bucket exists and has keys
+ c := tx.Bucket([]byte("MyBucket")).Cursor()
+
+ prefix := []byte("1234")
+ for k, v := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, v = c.Next() {
+ fmt.Printf("key=%s, value=%s\n", k, v)
+ }
+
+ return nil
+})
+```
+
+#### Range scans
+
+Another common use case is scanning over a range such as a time range. If you
+use a sortable time encoding such as RFC3339 then you can query a specific
+date range like this:
+
+```go
+db.View(func(tx *bolt.Tx) error {
+ // Assume our events bucket exists and has RFC3339 encoded time keys.
+ c := tx.Bucket([]byte("Events")).Cursor()
+
+ // Our time range spans the 90's decade.
+ min := []byte("1990-01-01T00:00:00Z")
+ max := []byte("2000-01-01T00:00:00Z")
+
+ // Iterate over the 90's.
+ for k, v := c.Seek(min); k != nil && bytes.Compare(k, max) <= 0; k, v = c.Next() {
+ fmt.Printf("%s: %s\n", k, v)
+ }
+
+ return nil
+})
+```
+
+Note that, while RFC3339 is sortable, the Golang implementation of RFC3339Nano does not use a fixed number of digits after the decimal point and is therefore not sortable.
+
+
+#### ForEach()
+
+You can also use the function `ForEach()` if you know you'll be iterating over
+all the keys in a bucket:
+
+```go
+db.View(func(tx *bolt.Tx) error {
+ // Assume bucket exists and has keys
+ b := tx.Bucket([]byte("MyBucket"))
+
+ b.ForEach(func(k, v []byte) error {
+ fmt.Printf("key=%s, value=%s\n", k, v)
+ return nil
+ })
+ return nil
+})
+```
+
+Please note that keys and values in `ForEach()` are only valid while
+the transaction is open. If you need to use a key or value outside of
+the transaction, you must use `copy()` to copy it to another byte
+slice.
+
+### Nested buckets
+
+You can also store a bucket in a key to create nested buckets. The API is the
+same as the bucket management API on the `DB` object:
+
+```go
+func (*Bucket) CreateBucket(key []byte) (*Bucket, error)
+func (*Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error)
+func (*Bucket) DeleteBucket(key []byte) error
+```
+
+Say you had a multi-tenant application where the root level bucket was the account bucket. Inside of this bucket was a sequence of accounts which themselves are buckets. And inside the sequence bucket you could have many buckets pertaining to the Account itself (Users, Notes, etc) isolating the information into logical groupings.
+
+```go
+
+// createUser creates a new user in the given account.
+func createUser(accountID int, u *User) error {
+ // Start the transaction.
+ tx, err := db.Begin(true)
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+
+ // Retrieve the root bucket for the account.
+ // Assume this has already been created when the account was set up.
+ root := tx.Bucket([]byte(strconv.FormatUint(accountID, 10)))
+
+ // Setup the users bucket.
+ bkt, err := root.CreateBucketIfNotExists([]byte("USERS"))
+ if err != nil {
+ return err
+ }
+
+ // Generate an ID for the new user.
+ userID, err := bkt.NextSequence()
+ if err != nil {
+ return err
+ }
+ u.ID = userID
+
+ // Marshal and save the encoded user.
+ if buf, err := json.Marshal(u); err != nil {
+ return err
+ } else if err := bkt.Put([]byte(strconv.FormatUint(u.ID, 10)), buf); err != nil {
+ return err
+ }
+
+ // Commit the transaction.
+ if err := tx.Commit(); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+```
+
+
+
+
+### Database backups
+
+Bolt is a single file so it's easy to backup. You can use the `Tx.WriteTo()`
+function to write a consistent view of the database to a writer. If you call
+this from a read-only transaction, it will perform a hot backup and not block
+your other database reads and writes.
+
+By default, it will use a regular file handle which will utilize the operating
+system's page cache. See the [`Tx`](https://godoc.org/github.com/boltdb/bolt#Tx)
+documentation for information about optimizing for larger-than-RAM datasets.
+
+One common use case is to backup over HTTP so you can use tools like `cURL` to
+do database backups:
+
+```go
+func BackupHandleFunc(w http.ResponseWriter, req *http.Request) {
+ err := db.View(func(tx *bolt.Tx) error {
+ w.Header().Set("Content-Type", "application/octet-stream")
+ w.Header().Set("Content-Disposition", `attachment; filename="my.db"`)
+ w.Header().Set("Content-Length", strconv.Itoa(int(tx.Size())))
+ _, err := tx.WriteTo(w)
+ return err
+ })
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ }
+}
+```
+
+Then you can backup using this command:
+
+```sh
+$ curl http://localhost/backup > my.db
+```
+
+Or you can open your browser to `http://localhost/backup` and it will download
+automatically.
+
+If you want to backup to another file you can use the `Tx.CopyFile()` helper
+function.
+
+
+### Statistics
+
+The database keeps a running count of many of the internal operations it
+performs so you can better understand what's going on. By grabbing a snapshot
+of these stats at two points in time we can see what operations were performed
+in that time range.
+
+For example, we could start a goroutine to log stats every 10 seconds:
+
+```go
+go func() {
+ // Grab the initial stats.
+ prev := db.Stats()
+
+ for {
+ // Wait for 10s.
+ time.Sleep(10 * time.Second)
+
+ // Grab the current stats and diff them.
+ stats := db.Stats()
+ diff := stats.Sub(&prev)
+
+ // Encode stats to JSON and print to STDERR.
+ json.NewEncoder(os.Stderr).Encode(diff)
+
+ // Save stats for the next loop.
+ prev = stats
+ }
+}()
+```
+
+It's also useful to pipe these stats to a service such as statsd for monitoring
+or to provide an HTTP endpoint that will perform a fixed-length sample.
+
+
+### Read-Only Mode
+
+Sometimes it is useful to create a shared, read-only Bolt database. To this,
+set the `Options.ReadOnly` flag when opening your database. Read-only mode
+uses a shared lock to allow multiple processes to read from the database but
+it will block any processes from opening the database in read-write mode.
+
+```go
+db, err := bolt.Open("my.db", 0666, &bolt.Options{ReadOnly: true})
+if err != nil {
+ log.Fatal(err)
+}
+```
+
+### Mobile Use (iOS/Android)
+
+Bolt is able to run on mobile devices by leveraging the binding feature of the
+[gomobile](https://github.com/golang/mobile) tool. Create a struct that will
+contain your database logic and a reference to a `*bolt.DB` with a initializing
+constructor that takes in a filepath where the database file will be stored.
+Neither Android nor iOS require extra permissions or cleanup from using this method.
+
+```go
+func NewBoltDB(filepath string) *BoltDB {
+ db, err := bolt.Open(filepath+"/demo.db", 0600, nil)
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ return &BoltDB{db}
+}
+
+type BoltDB struct {
+ db *bolt.DB
+ ...
+}
+
+func (b *BoltDB) Path() string {
+ return b.db.Path()
+}
+
+func (b *BoltDB) Close() {
+ b.db.Close()
+}
+```
+
+Database logic should be defined as methods on this wrapper struct.
+
+To initialize this struct from the native language (both platforms now sync
+their local storage to the cloud. These snippets disable that functionality for the
+database file):
+
+#### Android
+
+```java
+String path;
+if (android.os.Build.VERSION.SDK_INT >=android.os.Build.VERSION_CODES.LOLLIPOP){
+ path = getNoBackupFilesDir().getAbsolutePath();
+} else{
+ path = getFilesDir().getAbsolutePath();
+}
+Boltmobiledemo.BoltDB boltDB = Boltmobiledemo.NewBoltDB(path)
+```
+
+#### iOS
+
+```objc
+- (void)demo {
+ NSString* path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
+ NSUserDomainMask,
+ YES) objectAtIndex:0];
+ GoBoltmobiledemoBoltDB * demo = GoBoltmobiledemoNewBoltDB(path);
+ [self addSkipBackupAttributeToItemAtPath:demo.path];
+ //Some DB Logic would go here
+ [demo close];
+}
+
+- (BOOL)addSkipBackupAttributeToItemAtPath:(NSString *) filePathString
+{
+ NSURL* URL= [NSURL fileURLWithPath: filePathString];
+ assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);
+
+ NSError *error = nil;
+ BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]
+ forKey: NSURLIsExcludedFromBackupKey error: &error];
+ if(!success){
+ NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
+ }
+ return success;
+}
+
+```
+
+## Resources
+
+For more information on getting started with Bolt, check out the following articles:
+
+* [Intro to BoltDB: Painless Performant Persistence](http://npf.io/2014/07/intro-to-boltdb-painless-performant-persistence/) by [Nate Finch](https://github.com/natefinch).
+* [Bolt -- an embedded key/value database for Go](https://www.progville.com/go/bolt-embedded-db-golang/) by Progville
+
+
+## Comparison with other databases
+
+### Postgres, MySQL, & other relational databases
+
+Relational databases structure data into rows and are only accessible through
+the use of SQL. This approach provides flexibility in how you store and query
+your data but also incurs overhead in parsing and planning SQL statements. Bolt
+accesses all data by a byte slice key. This makes Bolt fast to read and write
+data by key but provides no built-in support for joining values together.
+
+Most relational databases (with the exception of SQLite) are standalone servers
+that run separately from your application. This gives your systems
+flexibility to connect multiple application servers to a single database
+server but also adds overhead in serializing and transporting data over the
+network. Bolt runs as a library included in your application so all data access
+has to go through your application's process. This brings data closer to your
+application but limits multi-process access to the data.
+
+
+### LevelDB, RocksDB
+
+LevelDB and its derivatives (RocksDB, HyperLevelDB) are similar to Bolt in that
+they are libraries bundled into the application, however, their underlying
+structure is a log-structured merge-tree (LSM tree). An LSM tree optimizes
+random writes by using a write ahead log and multi-tiered, sorted files called
+SSTables. Bolt uses a B+tree internally and only a single file. Both approaches
+have trade-offs.
+
+If you require a high random write throughput (>10,000 w/sec) or you need to use
+spinning disks then LevelDB could be a good choice. If your application is
+read-heavy or does a lot of range scans then Bolt could be a good choice.
+
+One other important consideration is that LevelDB does not have transactions.
+It supports batch writing of key/values pairs and it supports read snapshots
+but it will not give you the ability to do a compare-and-swap operation safely.
+Bolt supports fully serializable ACID transactions.
+
+
+### LMDB
+
+Bolt was originally a port of LMDB so it is architecturally similar. Both use
+a B+tree, have ACID semantics with fully serializable transactions, and support
+lock-free MVCC using a single writer and multiple readers.
+
+The two projects have somewhat diverged. LMDB heavily focuses on raw performance
+while Bolt has focused on simplicity and ease of use. For example, LMDB allows
+several unsafe actions such as direct writes for the sake of performance. Bolt
+opts to disallow actions which can leave the database in a corrupted state. The
+only exception to this in Bolt is `DB.NoSync`.
+
+There are also a few differences in API. LMDB requires a maximum mmap size when
+opening an `mdb_env` whereas Bolt will handle incremental mmap resizing
+automatically. LMDB overloads the getter and setter functions with multiple
+flags whereas Bolt splits these specialized cases into their own functions.
+
+
+## Caveats & Limitations
+
+It's important to pick the right tool for the job and Bolt is no exception.
+Here are a few things to note when evaluating and using Bolt:
+
+* Bolt is good for read intensive workloads. Sequential write performance is
+ also fast but random writes can be slow. You can use `DB.Batch()` or add a
+ write-ahead log to help mitigate this issue.
+
+* Bolt uses a B+tree internally so there can be a lot of random page access.
+ SSDs provide a significant performance boost over spinning disks.
+
+* Try to avoid long running read transactions. Bolt uses copy-on-write so
+ old pages cannot be reclaimed while an old transaction is using them.
+
+* Byte slices returned from Bolt are only valid during a transaction. Once the
+ transaction has been committed or rolled back then the memory they point to
+ can be reused by a new page or can be unmapped from virtual memory and you'll
+ see an `unexpected fault address` panic when accessing it.
+
+* Bolt uses an exclusive write lock on the database file so it cannot be
+ shared by multiple processes.
+
+* Be careful when using `Bucket.FillPercent`. Setting a high fill percent for
+ buckets that have random inserts will cause your database to have very poor
+ page utilization.
+
+* Use larger buckets in general. Smaller buckets causes poor page utilization
+ once they become larger than the page size (typically 4KB).
+
+* Bulk loading a lot of random writes into a new bucket can be slow as the
+ page will not split until the transaction is committed. Randomly inserting
+ more than 100,000 key/value pairs into a single new bucket in a single
+ transaction is not advised.
+
+* Bolt uses a memory-mapped file so the underlying operating system handles the
+ caching of the data. Typically, the OS will cache as much of the file as it
+ can in memory and will release memory as needed to other processes. This means
+ that Bolt can show very high memory usage when working with large databases.
+ However, this is expected and the OS will release memory as needed. Bolt can
+ handle databases much larger than the available physical RAM, provided its
+ memory-map fits in the process virtual address space. It may be problematic
+ on 32-bits systems.
+
+* The data structures in the Bolt database are memory mapped so the data file
+ will be endian specific. This means that you cannot copy a Bolt file from a
+ little endian machine to a big endian machine and have it work. For most
+ users this is not a concern since most modern CPUs are little endian.
+
+* Because of the way pages are laid out on disk, Bolt cannot truncate data files
+ and return free pages back to the disk. Instead, Bolt maintains a free list
+ of unused pages within its data file. These free pages can be reused by later
+ transactions. This works well for many use cases as databases generally tend
+ to grow. However, it's important to note that deleting large chunks of data
+ will not allow you to reclaim that space on disk.
+
+ For more information on page allocation, [see this comment][page-allocation].
+
+[page-allocation]: https://github.com/boltdb/bolt/issues/308#issuecomment-74811638
+
+
+## Reading the Source
+
+Bolt is a relatively small code base (<3KLOC) for an embedded, serializable,
+transactional key/value database so it can be a good starting point for people
+interested in how databases work.
+
+The best places to start are the main entry points into Bolt:
+
+- `Open()` - Initializes the reference to the database. It's responsible for
+ creating the database if it doesn't exist, obtaining an exclusive lock on the
+ file, reading the meta pages, & memory-mapping the file.
+
+- `DB.Begin()` - Starts a read-only or read-write transaction depending on the
+ value of the `writable` argument. This requires briefly obtaining the "meta"
+ lock to keep track of open transactions. Only one read-write transaction can
+ exist at a time so the "rwlock" is acquired during the life of a read-write
+ transaction.
+
+- `Bucket.Put()` - Writes a key/value pair into a bucket. After validating the
+ arguments, a cursor is used to traverse the B+tree to the page and position
+ where they key & value will be written. Once the position is found, the bucket
+ materializes the underlying page and the page's parent pages into memory as
+ "nodes". These nodes are where mutations occur during read-write transactions.
+ These changes get flushed to disk during commit.
+
+- `Bucket.Get()` - Retrieves a key/value pair from a bucket. This uses a cursor
+ to move to the page & position of a key/value pair. During a read-only
+ transaction, the key and value data is returned as a direct reference to the
+ underlying mmap file so there's no allocation overhead. For read-write
+ transactions, this data may reference the mmap file or one of the in-memory
+ node values.
+
+- `Cursor` - This object is simply for traversing the B+tree of on-disk pages
+ or in-memory nodes. It can seek to a specific key, move to the first or last
+ value, or it can move forward or backward. The cursor handles the movement up
+ and down the B+tree transparently to the end user.
+
+- `Tx.Commit()` - Converts the in-memory dirty nodes and the list of free pages
+ into pages to be written to disk. Writing to disk then occurs in two phases.
+ First, the dirty pages are written to disk and an `fsync()` occurs. Second, a
+ new meta page with an incremented transaction ID is written and another
+ `fsync()` occurs. This two phase write ensures that partially written data
+ pages are ignored in the event of a crash since the meta page pointing to them
+ is never written. Partially written meta pages are invalidated because they
+ are written with a checksum.
+
+If you have additional notes that could be helpful for others, please submit
+them via pull request.
+
+
+## Other Projects Using Bolt
+
+Below is a list of public, open source projects that use Bolt:
+
+* [BoltDbWeb](https://github.com/evnix/boltdbweb) - A web based GUI for BoltDB files.
+* [Operation Go: A Routine Mission](http://gocode.io) - An online programming game for Golang using Bolt for user accounts and a leaderboard.
+* [Bazil](https://bazil.org/) - A file system that lets your data reside where it is most convenient for it to reside.
+* [DVID](https://github.com/janelia-flyem/dvid) - Added Bolt as optional storage engine and testing it against Basho-tuned leveldb.
+* [Skybox Analytics](https://github.com/skybox/skybox) - A standalone funnel analysis tool for web analytics.
+* [Scuttlebutt](https://github.com/benbjohnson/scuttlebutt) - Uses Bolt to store and process all Twitter mentions of GitHub projects.
+* [Wiki](https://github.com/peterhellberg/wiki) - A tiny wiki using Goji, BoltDB and Blackfriday.
+* [ChainStore](https://github.com/pressly/chainstore) - Simple key-value interface to a variety of storage engines organized as a chain of operations.
+* [MetricBase](https://github.com/msiebuhr/MetricBase) - Single-binary version of Graphite.
+* [Gitchain](https://github.com/gitchain/gitchain) - Decentralized, peer-to-peer Git repositories aka "Git meets Bitcoin".
+* [event-shuttle](https://github.com/sclasen/event-shuttle) - A Unix system service to collect and reliably deliver messages to Kafka.
+* [ipxed](https://github.com/kelseyhightower/ipxed) - Web interface and api for ipxed.
+* [BoltStore](https://github.com/yosssi/boltstore) - Session store using Bolt.
+* [photosite/session](https://godoc.org/bitbucket.org/kardianos/photosite/session) - Sessions for a photo viewing site.
+* [LedisDB](https://github.com/siddontang/ledisdb) - A high performance NoSQL, using Bolt as optional storage.
+* [ipLocator](https://github.com/AndreasBriese/ipLocator) - A fast ip-geo-location-server using bolt with bloom filters.
+* [cayley](https://github.com/google/cayley) - Cayley is an open-source graph database using Bolt as optional backend.
+* [bleve](http://www.blevesearch.com/) - A pure Go search engine similar to ElasticSearch that uses Bolt as the default storage backend.
+* [tentacool](https://github.com/optiflows/tentacool) - REST api server to manage system stuff (IP, DNS, Gateway...) on a linux server.
+* [Seaweed File System](https://github.com/chrislusf/seaweedfs) - Highly scalable distributed key~file system with O(1) disk read.
+* [InfluxDB](https://influxdata.com) - Scalable datastore for metrics, events, and real-time analytics.
+* [Freehold](http://tshannon.bitbucket.org/freehold/) - An open, secure, and lightweight platform for your files and data.
+* [Prometheus Annotation Server](https://github.com/oliver006/prom_annotation_server) - Annotation server for PromDash & Prometheus service monitoring system.
+* [Consul](https://github.com/hashicorp/consul) - Consul is service discovery and configuration made easy. Distributed, highly available, and datacenter-aware.
+* [Kala](https://github.com/ajvb/kala) - Kala is a modern job scheduler optimized to run on a single node. It is persistent, JSON over HTTP API, ISO 8601 duration notation, and dependent jobs.
+* [drive](https://github.com/odeke-em/drive) - drive is an unofficial Google Drive command line client for \*NIX operating systems.
+* [stow](https://github.com/djherbis/stow) - a persistence manager for objects
+ backed by boltdb.
+* [buckets](https://github.com/joyrexus/buckets) - a bolt wrapper streamlining
+ simple tx and key scans.
+* [mbuckets](https://github.com/abhigupta912/mbuckets) - A Bolt wrapper that allows easy operations on multi level (nested) buckets.
+* [Request Baskets](https://github.com/darklynx/request-baskets) - A web service to collect arbitrary HTTP requests and inspect them via REST API or simple web UI, similar to [RequestBin](http://requestb.in/) service
+* [Go Report Card](https://goreportcard.com/) - Go code quality report cards as a (free and open source) service.
+* [Boltdb Boilerplate](https://github.com/bobintornado/boltdb-boilerplate) - Boilerplate wrapper around bolt aiming to make simple calls one-liners.
+* [lru](https://github.com/crowdriff/lru) - Easy to use Bolt-backed Least-Recently-Used (LRU) read-through cache with chainable remote stores.
+* [Storm](https://github.com/asdine/storm) - Simple and powerful ORM for BoltDB.
+* [GoWebApp](https://github.com/josephspurrier/gowebapp) - A basic MVC web application in Go using BoltDB.
+* [SimpleBolt](https://github.com/xyproto/simplebolt) - A simple way to use BoltDB. Deals mainly with strings.
+* [Algernon](https://github.com/xyproto/algernon) - A HTTP/2 web server with built-in support for Lua. Uses BoltDB as the default database backend.
+* [MuLiFS](https://github.com/dankomiocevic/mulifs) - Music Library Filesystem creates a filesystem to organise your music files.
+* [GoShort](https://github.com/pankajkhairnar/goShort) - GoShort is a URL shortener written in Golang and BoltDB for persistent key/value storage and for routing it's using high performent HTTPRouter.
+* [torrent](https://github.com/anacrolix/torrent) - Full-featured BitTorrent client package and utilities in Go. BoltDB is a storage backend in development.
+* [gopherpit](https://github.com/gopherpit/gopherpit) - A web service to manage Go remote import paths with custom domains
+* [bolter](https://github.com/hasit/bolter) - Command-line app for viewing BoltDB file in your terminal.
+* [btcwallet](https://github.com/btcsuite/btcwallet) - A bitcoin wallet.
+* [dcrwallet](https://github.com/decred/dcrwallet) - A wallet for the Decred cryptocurrency.
+* [Ironsmith](https://github.com/timshannon/ironsmith) - A simple, script-driven continuous integration (build - > test -> release) tool, with no external dependencies
+* [BoltHold](https://github.com/timshannon/bolthold) - An embeddable NoSQL store for Go types built on BoltDB
+* [Ponzu CMS](https://ponzu-cms.org) - Headless CMS + automatic JSON API with auto-HTTPS, HTTP/2 Server Push, and flexible server framework.
+
+If you are using Bolt in a project please send a pull request to add it to the list.
diff -Naur --color b/vendor/github.com/boltdb/bolt/tx.go a/vendor/github.com/boltdb/bolt/tx.go
--- b/vendor/github.com/boltdb/bolt/tx.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/boltdb/bolt/tx.go 2022-11-15 23:06:29.392015899 +0100
@@ -0,0 +1,684 @@
+package bolt
+
+import (
+ "fmt"
+ "io"
+ "os"
+ "sort"
+ "strings"
+ "time"
+ "unsafe"
+)
+
+// txid represents the internal transaction identifier.
+type txid uint64
+
+// Tx represents a read-only or read/write transaction on the database.
+// Read-only transactions can be used for retrieving values for keys and creating cursors.
+// Read/write transactions can create and remove buckets and create and remove keys.
+//
+// IMPORTANT: You must commit or rollback transactions when you are done with
+// them. Pages can not be reclaimed by the writer until no more transactions
+// are using them. A long running read transaction can cause the database to
+// quickly grow.
+type Tx struct {
+ writable bool
+ managed bool
+ db *DB
+ meta *meta
+ root Bucket
+ pages map[pgid]*page
+ stats TxStats
+ commitHandlers []func()
+
+ // WriteFlag specifies the flag for write-related methods like WriteTo().
+ // Tx opens the database file with the specified flag to copy the data.
+ //
+ // By default, the flag is unset, which works well for mostly in-memory
+ // workloads. For databases that are much larger than available RAM,
+ // set the flag to syscall.O_DIRECT to avoid trashing the page cache.
+ WriteFlag int
+}
+
+// init initializes the transaction.
+func (tx *Tx) init(db *DB) {
+ tx.db = db
+ tx.pages = nil
+
+ // Copy the meta page since it can be changed by the writer.
+ tx.meta = &meta{}
+ db.meta().copy(tx.meta)
+
+ // Copy over the root bucket.
+ tx.root = newBucket(tx)
+ tx.root.bucket = &bucket{}
+ *tx.root.bucket = tx.meta.root
+
+ // Increment the transaction id and add a page cache for writable transactions.
+ if tx.writable {
+ tx.pages = make(map[pgid]*page)
+ tx.meta.txid += txid(1)
+ }
+}
+
+// ID returns the transaction id.
+func (tx *Tx) ID() int {
+ return int(tx.meta.txid)
+}
+
+// DB returns a reference to the database that created the transaction.
+func (tx *Tx) DB() *DB {
+ return tx.db
+}
+
+// Size returns current database size in bytes as seen by this transaction.
+func (tx *Tx) Size() int64 {
+ return int64(tx.meta.pgid) * int64(tx.db.pageSize)
+}
+
+// Writable returns whether the transaction can perform write operations.
+func (tx *Tx) Writable() bool {
+ return tx.writable
+}
+
+// Cursor creates a cursor associated with the root bucket.
+// All items in the cursor will return a nil value because all root bucket keys point to buckets.
+// The cursor is only valid as long as the transaction is open.
+// Do not use a cursor after the transaction is closed.
+func (tx *Tx) Cursor() *Cursor {
+ return tx.root.Cursor()
+}
+
+// Stats retrieves a copy of the current transaction statistics.
+func (tx *Tx) Stats() TxStats {
+ return tx.stats
+}
+
+// Bucket retrieves a bucket by name.
+// Returns nil if the bucket does not exist.
+// The bucket instance is only valid for the lifetime of the transaction.
+func (tx *Tx) Bucket(name []byte) *Bucket {
+ return tx.root.Bucket(name)
+}
+
+// CreateBucket creates a new bucket.
+// Returns an error if the bucket already exists, if the bucket name is blank, or if the bucket name is too long.
+// The bucket instance is only valid for the lifetime of the transaction.
+func (tx *Tx) CreateBucket(name []byte) (*Bucket, error) {
+ return tx.root.CreateBucket(name)
+}
+
+// CreateBucketIfNotExists creates a new bucket if it doesn't already exist.
+// Returns an error if the bucket name is blank, or if the bucket name is too long.
+// The bucket instance is only valid for the lifetime of the transaction.
+func (tx *Tx) CreateBucketIfNotExists(name []byte) (*Bucket, error) {
+ return tx.root.CreateBucketIfNotExists(name)
+}
+
+// DeleteBucket deletes a bucket.
+// Returns an error if the bucket cannot be found or if the key represents a non-bucket value.
+func (tx *Tx) DeleteBucket(name []byte) error {
+ return tx.root.DeleteBucket(name)
+}
+
+// ForEach executes a function for each bucket in the root.
+// If the provided function returns an error then the iteration is stopped and
+// the error is returned to the caller.
+func (tx *Tx) ForEach(fn func(name []byte, b *Bucket) error) error {
+ return tx.root.ForEach(func(k, v []byte) error {
+ if err := fn(k, tx.root.Bucket(k)); err != nil {
+ return err
+ }
+ return nil
+ })
+}
+
+// OnCommit adds a handler function to be executed after the transaction successfully commits.
+func (tx *Tx) OnCommit(fn func()) {
+ tx.commitHandlers = append(tx.commitHandlers, fn)
+}
+
+// Commit writes all changes to disk and updates the meta page.
+// Returns an error if a disk write error occurs, or if Commit is
+// called on a read-only transaction.
+func (tx *Tx) Commit() error {
+ _assert(!tx.managed, "managed tx commit not allowed")
+ if tx.db == nil {
+ return ErrTxClosed
+ } else if !tx.writable {
+ return ErrTxNotWritable
+ }
+
+ // TODO(benbjohnson): Use vectorized I/O to write out dirty pages.
+
+ // Rebalance nodes which have had deletions.
+ var startTime = time.Now()
+ tx.root.rebalance()
+ if tx.stats.Rebalance > 0 {
+ tx.stats.RebalanceTime += time.Since(startTime)
+ }
+
+ // spill data onto dirty pages.
+ startTime = time.Now()
+ if err := tx.root.spill(); err != nil {
+ tx.rollback()
+ return err
+ }
+ tx.stats.SpillTime += time.Since(startTime)
+
+ // Free the old root bucket.
+ tx.meta.root.root = tx.root.root
+
+ opgid := tx.meta.pgid
+
+ // Free the freelist and allocate new pages for it. This will overestimate
+ // the size of the freelist but not underestimate the size (which would be bad).
+ tx.db.freelist.free(tx.meta.txid, tx.db.page(tx.meta.freelist))
+ p, err := tx.allocate((tx.db.freelist.size() / tx.db.pageSize) + 1)
+ if err != nil {
+ tx.rollback()
+ return err
+ }
+ if err := tx.db.freelist.write(p); err != nil {
+ tx.rollback()
+ return err
+ }
+ tx.meta.freelist = p.id
+
+ // If the high water mark has moved up then attempt to grow the database.
+ if tx.meta.pgid > opgid {
+ if err := tx.db.grow(int(tx.meta.pgid+1) * tx.db.pageSize); err != nil {
+ tx.rollback()
+ return err
+ }
+ }
+
+ // Write dirty pages to disk.
+ startTime = time.Now()
+ if err := tx.write(); err != nil {
+ tx.rollback()
+ return err
+ }
+
+ // If strict mode is enabled then perform a consistency check.
+ // Only the first consistency error is reported in the panic.
+ if tx.db.StrictMode {
+ ch := tx.Check()
+ var errs []string
+ for {
+ err, ok := <-ch
+ if !ok {
+ break
+ }
+ errs = append(errs, err.Error())
+ }
+ if len(errs) > 0 {
+ panic("check fail: " + strings.Join(errs, "\n"))
+ }
+ }
+
+ // Write meta to disk.
+ if err := tx.writeMeta(); err != nil {
+ tx.rollback()
+ return err
+ }
+ tx.stats.WriteTime += time.Since(startTime)
+
+ // Finalize the transaction.
+ tx.close()
+
+ // Execute commit handlers now that the locks have been removed.
+ for _, fn := range tx.commitHandlers {
+ fn()
+ }
+
+ return nil
+}
+
+// Rollback closes the transaction and ignores all previous updates. Read-only
+// transactions must be rolled back and not committed.
+func (tx *Tx) Rollback() error {
+ _assert(!tx.managed, "managed tx rollback not allowed")
+ if tx.db == nil {
+ return ErrTxClosed
+ }
+ tx.rollback()
+ return nil
+}
+
+func (tx *Tx) rollback() {
+ if tx.db == nil {
+ return
+ }
+ if tx.writable {
+ tx.db.freelist.rollback(tx.meta.txid)
+ tx.db.freelist.reload(tx.db.page(tx.db.meta().freelist))
+ }
+ tx.close()
+}
+
+func (tx *Tx) close() {
+ if tx.db == nil {
+ return
+ }
+ if tx.writable {
+ // Grab freelist stats.
+ var freelistFreeN = tx.db.freelist.free_count()
+ var freelistPendingN = tx.db.freelist.pending_count()
+ var freelistAlloc = tx.db.freelist.size()
+
+ // Remove transaction ref & writer lock.
+ tx.db.rwtx = nil
+ tx.db.rwlock.Unlock()
+
+ // Merge statistics.
+ tx.db.statlock.Lock()
+ tx.db.stats.FreePageN = freelistFreeN
+ tx.db.stats.PendingPageN = freelistPendingN
+ tx.db.stats.FreeAlloc = (freelistFreeN + freelistPendingN) * tx.db.pageSize
+ tx.db.stats.FreelistInuse = freelistAlloc
+ tx.db.stats.TxStats.add(&tx.stats)
+ tx.db.statlock.Unlock()
+ } else {
+ tx.db.removeTx(tx)
+ }
+
+ // Clear all references.
+ tx.db = nil
+ tx.meta = nil
+ tx.root = Bucket{tx: tx}
+ tx.pages = nil
+}
+
+// Copy writes the entire database to a writer.
+// This function exists for backwards compatibility. Use WriteTo() instead.
+func (tx *Tx) Copy(w io.Writer) error {
+ _, err := tx.WriteTo(w)
+ return err
+}
+
+// WriteTo writes the entire database to a writer.
+// If err == nil then exactly tx.Size() bytes will be written into the writer.
+func (tx *Tx) WriteTo(w io.Writer) (n int64, err error) {
+ // Attempt to open reader with WriteFlag
+ f, err := os.OpenFile(tx.db.path, os.O_RDONLY|tx.WriteFlag, 0)
+ if err != nil {
+ return 0, err
+ }
+ defer func() { _ = f.Close() }()
+
+ // Generate a meta page. We use the same page data for both meta pages.
+ buf := make([]byte, tx.db.pageSize)
+ page := (*page)(unsafe.Pointer(&buf[0]))
+ page.flags = metaPageFlag
+ *page.meta() = *tx.meta
+
+ // Write meta 0.
+ page.id = 0
+ page.meta().checksum = page.meta().sum64()
+ nn, err := w.Write(buf)
+ n += int64(nn)
+ if err != nil {
+ return n, fmt.Errorf("meta 0 copy: %s", err)
+ }
+
+ // Write meta 1 with a lower transaction id.
+ page.id = 1
+ page.meta().txid -= 1
+ page.meta().checksum = page.meta().sum64()
+ nn, err = w.Write(buf)
+ n += int64(nn)
+ if err != nil {
+ return n, fmt.Errorf("meta 1 copy: %s", err)
+ }
+
+ // Move past the meta pages in the file.
+ if _, err := f.Seek(int64(tx.db.pageSize*2), os.SEEK_SET); err != nil {
+ return n, fmt.Errorf("seek: %s", err)
+ }
+
+ // Copy data pages.
+ wn, err := io.CopyN(w, f, tx.Size()-int64(tx.db.pageSize*2))
+ n += wn
+ if err != nil {
+ return n, err
+ }
+
+ return n, f.Close()
+}
+
+// CopyFile copies the entire database to file at the given path.
+// A reader transaction is maintained during the copy so it is safe to continue
+// using the database while a copy is in progress.
+func (tx *Tx) CopyFile(path string, mode os.FileMode) error {
+ f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, mode)
+ if err != nil {
+ return err
+ }
+
+ err = tx.Copy(f)
+ if err != nil {
+ _ = f.Close()
+ return err
+ }
+ return f.Close()
+}
+
+// Check performs several consistency checks on the database for this transaction.
+// An error is returned if any inconsistency is found.
+//
+// It can be safely run concurrently on a writable transaction. However, this
+// incurs a high cost for large databases and databases with a lot of subbuckets
+// because of caching. This overhead can be removed if running on a read-only
+// transaction, however, it is not safe to execute other writer transactions at
+// the same time.
+func (tx *Tx) Check() <-chan error {
+ ch := make(chan error)
+ go tx.check(ch)
+ return ch
+}
+
+func (tx *Tx) check(ch chan error) {
+ // Check if any pages are double freed.
+ freed := make(map[pgid]bool)
+ all := make([]pgid, tx.db.freelist.count())
+ tx.db.freelist.copyall(all)
+ for _, id := range all {
+ if freed[id] {
+ ch <- fmt.Errorf("page %d: already freed", id)
+ }
+ freed[id] = true
+ }
+
+ // Track every reachable page.
+ reachable := make(map[pgid]*page)
+ reachable[0] = tx.page(0) // meta0
+ reachable[1] = tx.page(1) // meta1
+ for i := uint32(0); i <= tx.page(tx.meta.freelist).overflow; i++ {
+ reachable[tx.meta.freelist+pgid(i)] = tx.page(tx.meta.freelist)
+ }
+
+ // Recursively check buckets.
+ tx.checkBucket(&tx.root, reachable, freed, ch)
+
+ // Ensure all pages below high water mark are either reachable or freed.
+ for i := pgid(0); i < tx.meta.pgid; i++ {
+ _, isReachable := reachable[i]
+ if !isReachable && !freed[i] {
+ ch <- fmt.Errorf("page %d: unreachable unfreed", int(i))
+ }
+ }
+
+ // Close the channel to signal completion.
+ close(ch)
+}
+
+func (tx *Tx) checkBucket(b *Bucket, reachable map[pgid]*page, freed map[pgid]bool, ch chan error) {
+ // Ignore inline buckets.
+ if b.root == 0 {
+ return
+ }
+
+ // Check every page used by this bucket.
+ b.tx.forEachPage(b.root, 0, func(p *page, _ int) {
+ if p.id > tx.meta.pgid {
+ ch <- fmt.Errorf("page %d: out of bounds: %d", int(p.id), int(b.tx.meta.pgid))
+ }
+
+ // Ensure each page is only referenced once.
+ for i := pgid(0); i <= pgid(p.overflow); i++ {
+ var id = p.id + i
+ if _, ok := reachable[id]; ok {
+ ch <- fmt.Errorf("page %d: multiple references", int(id))
+ }
+ reachable[id] = p
+ }
+
+ // We should only encounter un-freed leaf and branch pages.
+ if freed[p.id] {
+ ch <- fmt.Errorf("page %d: reachable freed", int(p.id))
+ } else if (p.flags&branchPageFlag) == 0 && (p.flags&leafPageFlag) == 0 {
+ ch <- fmt.Errorf("page %d: invalid type: %s", int(p.id), p.typ())
+ }
+ })
+
+ // Check each bucket within this bucket.
+ _ = b.ForEach(func(k, v []byte) error {
+ if child := b.Bucket(k); child != nil {
+ tx.checkBucket(child, reachable, freed, ch)
+ }
+ return nil
+ })
+}
+
+// allocate returns a contiguous block of memory starting at a given page.
+func (tx *Tx) allocate(count int) (*page, error) {
+ p, err := tx.db.allocate(count)
+ if err != nil {
+ return nil, err
+ }
+
+ // Save to our page cache.
+ tx.pages[p.id] = p
+
+ // Update statistics.
+ tx.stats.PageCount++
+ tx.stats.PageAlloc += count * tx.db.pageSize
+
+ return p, nil
+}
+
+// write writes any dirty pages to disk.
+func (tx *Tx) write() error {
+ // Sort pages by id.
+ pages := make(pages, 0, len(tx.pages))
+ for _, p := range tx.pages {
+ pages = append(pages, p)
+ }
+ // Clear out page cache early.
+ tx.pages = make(map[pgid]*page)
+ sort.Sort(pages)
+
+ // Write pages to disk in order.
+ for _, p := range pages {
+ size := (int(p.overflow) + 1) * tx.db.pageSize
+ offset := int64(p.id) * int64(tx.db.pageSize)
+
+ // Write out page in "max allocation" sized chunks.
+ ptr := (*[maxAllocSize]byte)(unsafe.Pointer(p))
+ for {
+ // Limit our write to our max allocation size.
+ sz := size
+ if sz > maxAllocSize-1 {
+ sz = maxAllocSize - 1
+ }
+
+ // Write chunk to disk.
+ buf := ptr[:sz]
+ if _, err := tx.db.ops.writeAt(buf, offset); err != nil {
+ return err
+ }
+
+ // Update statistics.
+ tx.stats.Write++
+
+ // Exit inner for loop if we've written all the chunks.
+ size -= sz
+ if size == 0 {
+ break
+ }
+
+ // Otherwise move offset forward and move pointer to next chunk.
+ offset += int64(sz)
+ ptr = (*[maxAllocSize]byte)(unsafe.Pointer(&ptr[sz]))
+ }
+ }
+
+ // Ignore file sync if flag is set on DB.
+ if !tx.db.NoSync || IgnoreNoSync {
+ if err := fdatasync(tx.db); err != nil {
+ return err
+ }
+ }
+
+ // Put small pages back to page pool.
+ for _, p := range pages {
+ // Ignore page sizes over 1 page.
+ // These are allocated using make() instead of the page pool.
+ if int(p.overflow) != 0 {
+ continue
+ }
+
+ buf := (*[maxAllocSize]byte)(unsafe.Pointer(p))[:tx.db.pageSize]
+
+ // See https://go.googlesource.com/go/+/f03c9202c43e0abb130669852082117ca50aa9b1
+ for i := range buf {
+ buf[i] = 0
+ }
+ tx.db.pagePool.Put(buf)
+ }
+
+ return nil
+}
+
+// writeMeta writes the meta to the disk.
+func (tx *Tx) writeMeta() error {
+ // Create a temporary buffer for the meta page.
+ buf := make([]byte, tx.db.pageSize)
+ p := tx.db.pageInBuffer(buf, 0)
+ tx.meta.write(p)
+
+ // Write the meta page to file.
+ if _, err := tx.db.ops.writeAt(buf, int64(p.id)*int64(tx.db.pageSize)); err != nil {
+ return err
+ }
+ if !tx.db.NoSync || IgnoreNoSync {
+ if err := fdatasync(tx.db); err != nil {
+ return err
+ }
+ }
+
+ // Update statistics.
+ tx.stats.Write++
+
+ return nil
+}
+
+// page returns a reference to the page with a given id.
+// If page has been written to then a temporary buffered page is returned.
+func (tx *Tx) page(id pgid) *page {
+ // Check the dirty pages first.
+ if tx.pages != nil {
+ if p, ok := tx.pages[id]; ok {
+ return p
+ }
+ }
+
+ // Otherwise return directly from the mmap.
+ return tx.db.page(id)
+}
+
+// forEachPage iterates over every page within a given page and executes a function.
+func (tx *Tx) forEachPage(pgid pgid, depth int, fn func(*page, int)) {
+ p := tx.page(pgid)
+
+ // Execute function.
+ fn(p, depth)
+
+ // Recursively loop over children.
+ if (p.flags & branchPageFlag) != 0 {
+ for i := 0; i < int(p.count); i++ {
+ elem := p.branchPageElement(uint16(i))
+ tx.forEachPage(elem.pgid, depth+1, fn)
+ }
+ }
+}
+
+// Page returns page information for a given page number.
+// This is only safe for concurrent use when used by a writable transaction.
+func (tx *Tx) Page(id int) (*PageInfo, error) {
+ if tx.db == nil {
+ return nil, ErrTxClosed
+ } else if pgid(id) >= tx.meta.pgid {
+ return nil, nil
+ }
+
+ // Build the page info.
+ p := tx.db.page(pgid(id))
+ info := &PageInfo{
+ ID: id,
+ Count: int(p.count),
+ OverflowCount: int(p.overflow),
+ }
+
+ // Determine the type (or if it's free).
+ if tx.db.freelist.freed(pgid(id)) {
+ info.Type = "free"
+ } else {
+ info.Type = p.typ()
+ }
+
+ return info, nil
+}
+
+// TxStats represents statistics about the actions performed by the transaction.
+type TxStats struct {
+ // Page statistics.
+ PageCount int // number of page allocations
+ PageAlloc int // total bytes allocated
+
+ // Cursor statistics.
+ CursorCount int // number of cursors created
+
+ // Node statistics
+ NodeCount int // number of node allocations
+ NodeDeref int // number of node dereferences
+
+ // Rebalance statistics.
+ Rebalance int // number of node rebalances
+ RebalanceTime time.Duration // total time spent rebalancing
+
+ // Split/Spill statistics.
+ Split int // number of nodes split
+ Spill int // number of nodes spilled
+ SpillTime time.Duration // total time spent spilling
+
+ // Write statistics.
+ Write int // number of writes performed
+ WriteTime time.Duration // total time spent writing to disk
+}
+
+func (s *TxStats) add(other *TxStats) {
+ s.PageCount += other.PageCount
+ s.PageAlloc += other.PageAlloc
+ s.CursorCount += other.CursorCount
+ s.NodeCount += other.NodeCount
+ s.NodeDeref += other.NodeDeref
+ s.Rebalance += other.Rebalance
+ s.RebalanceTime += other.RebalanceTime
+ s.Split += other.Split
+ s.Spill += other.Spill
+ s.SpillTime += other.SpillTime
+ s.Write += other.Write
+ s.WriteTime += other.WriteTime
+}
+
+// Sub calculates and returns the difference between two sets of transaction stats.
+// This is useful when obtaining stats at two different points and time and
+// you need the performance counters that occurred within that time span.
+func (s *TxStats) Sub(other *TxStats) TxStats {
+ var diff TxStats
+ diff.PageCount = s.PageCount - other.PageCount
+ diff.PageAlloc = s.PageAlloc - other.PageAlloc
+ diff.CursorCount = s.CursorCount - other.CursorCount
+ diff.NodeCount = s.NodeCount - other.NodeCount
+ diff.NodeDeref = s.NodeDeref - other.NodeDeref
+ diff.Rebalance = s.Rebalance - other.Rebalance
+ diff.RebalanceTime = s.RebalanceTime - other.RebalanceTime
+ diff.Split = s.Split - other.Split
+ diff.Spill = s.Spill - other.Spill
+ diff.SpillTime = s.SpillTime - other.SpillTime
+ diff.Write = s.Write - other.Write
+ diff.WriteTime = s.WriteTime - other.WriteTime
+ return diff
+}
diff -Naur --color b/vendor/github.com/hashicorp/go-hclog/colorize_unix.go a/vendor/github.com/hashicorp/go-hclog/colorize_unix.go
--- b/vendor/github.com/hashicorp/go-hclog/colorize_unix.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-hclog/colorize_unix.go 2022-11-15 23:06:31.548724207 +0100
@@ -0,0 +1,27 @@
+// +build !windows
+
+package hclog
+
+import (
+ "github.com/mattn/go-isatty"
+)
+
+// setColorization will mutate the values of this logger
+// to approperately configure colorization options. It provides
+// a wrapper to the output stream on Windows systems.
+func (l *intLogger) setColorization(opts *LoggerOptions) {
+ switch opts.Color {
+ case ColorOff:
+ fallthrough
+ case ForceColor:
+ return
+ case AutoColor:
+ fi := l.checkWriterIsFile()
+ isUnixTerm := isatty.IsTerminal(fi.Fd())
+ isCygwinTerm := isatty.IsCygwinTerminal(fi.Fd())
+ isTerm := isUnixTerm || isCygwinTerm
+ if !isTerm {
+ l.writer.color = ColorOff
+ }
+ }
+}
diff -Naur --color b/vendor/github.com/hashicorp/go-hclog/colorize_windows.go a/vendor/github.com/hashicorp/go-hclog/colorize_windows.go
--- b/vendor/github.com/hashicorp/go-hclog/colorize_windows.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-hclog/colorize_windows.go 2022-11-15 23:06:31.548724207 +0100
@@ -0,0 +1,33 @@
+// +build windows
+
+package hclog
+
+import (
+ "os"
+
+ colorable "github.com/mattn/go-colorable"
+ "github.com/mattn/go-isatty"
+)
+
+// setColorization will mutate the values of this logger
+// to approperately configure colorization options. It provides
+// a wrapper to the output stream on Windows systems.
+func (l *intLogger) setColorization(opts *LoggerOptions) {
+ switch opts.Color {
+ case ColorOff:
+ return
+ case ForceColor:
+ fi := l.checkWriterIsFile()
+ l.writer.w = colorable.NewColorable(fi)
+ case AutoColor:
+ fi := l.checkWriterIsFile()
+ isUnixTerm := isatty.IsTerminal(os.Stdout.Fd())
+ isCygwinTerm := isatty.IsCygwinTerminal(os.Stdout.Fd())
+ isTerm := isUnixTerm || isCygwinTerm
+ if !isTerm {
+ l.writer.color = ColorOff
+ return
+ }
+ l.writer.w = colorable.NewColorable(fi)
+ }
+}
diff -Naur --color b/vendor/github.com/hashicorp/go-hclog/context.go a/vendor/github.com/hashicorp/go-hclog/context.go
--- b/vendor/github.com/hashicorp/go-hclog/context.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-hclog/context.go 2022-11-15 23:06:31.548724207 +0100
@@ -0,0 +1,38 @@
+package hclog
+
+import (
+ "context"
+)
+
+// WithContext inserts a logger into the context and is retrievable
+// with FromContext. The optional args can be set with the same syntax as
+// Logger.With to set fields on the inserted logger. This will not modify
+// the logger argument in-place.
+func WithContext(ctx context.Context, logger Logger, args ...interface{}) context.Context {
+ // While we could call logger.With even with zero args, we have this
+ // check to avoid unnecessary allocations around creating a copy of a
+ // logger.
+ if len(args) > 0 {
+ logger = logger.With(args...)
+ }
+
+ return context.WithValue(ctx, contextKey, logger)
+}
+
+// FromContext returns a logger from the context. This will return L()
+// (the default logger) if no logger is found in the context. Therefore,
+// this will never return a nil value.
+func FromContext(ctx context.Context) Logger {
+ logger, _ := ctx.Value(contextKey).(Logger)
+ if logger == nil {
+ return L()
+ }
+
+ return logger
+}
+
+// Unexported new type so that our context key never collides with another.
+type contextKeyType struct{}
+
+// contextKey is the key used for the context to store the logger.
+var contextKey = contextKeyType{}
diff -Naur --color b/vendor/github.com/hashicorp/go-hclog/exclude.go a/vendor/github.com/hashicorp/go-hclog/exclude.go
--- b/vendor/github.com/hashicorp/go-hclog/exclude.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-hclog/exclude.go 2022-11-15 23:06:31.548724207 +0100
@@ -0,0 +1,71 @@
+package hclog
+
+import (
+ "regexp"
+ "strings"
+)
+
+// ExcludeByMessage provides a simple way to build a list of log messages that
+// can be queried and matched. This is meant to be used with the Exclude
+// option on Options to suppress log messages. This does not hold any mutexs
+// within itself, so normal usage would be to Add entries at setup and none after
+// Exclude is going to be called. Exclude is called with a mutex held within
+// the Logger, so that doesn't need to use a mutex. Example usage:
+//
+// f := new(ExcludeByMessage)
+// f.Add("Noisy log message text")
+// appLogger.Exclude = f.Exclude
+type ExcludeByMessage struct {
+ messages map[string]struct{}
+}
+
+// Add a message to be filtered. Do not call this after Exclude is to be called
+// due to concurrency issues.
+func (f *ExcludeByMessage) Add(msg string) {
+ if f.messages == nil {
+ f.messages = make(map[string]struct{})
+ }
+
+ f.messages[msg] = struct{}{}
+}
+
+// Return true if the given message should be included
+func (f *ExcludeByMessage) Exclude(level Level, msg string, args ...interface{}) bool {
+ _, ok := f.messages[msg]
+ return ok
+}
+
+// ExcludeByPrefix is a simple type to match a message string that has a common prefix.
+type ExcludeByPrefix string
+
+// Matches an message that starts with the prefix.
+func (p ExcludeByPrefix) Exclude(level Level, msg string, args ...interface{}) bool {
+ return strings.HasPrefix(msg, string(p))
+}
+
+// ExcludeByRegexp takes a regexp and uses it to match a log message string. If it matches
+// the log entry is excluded.
+type ExcludeByRegexp struct {
+ Regexp *regexp.Regexp
+}
+
+// Exclude the log message if the message string matches the regexp
+func (e ExcludeByRegexp) Exclude(level Level, msg string, args ...interface{}) bool {
+ return e.Regexp.MatchString(msg)
+}
+
+// ExcludeFuncs is a slice of functions that will called to see if a log entry
+// should be filtered or not. It stops calling functions once at least one returns
+// true.
+type ExcludeFuncs []func(level Level, msg string, args ...interface{}) bool
+
+// Calls each function until one of them returns true
+func (ff ExcludeFuncs) Exclude(level Level, msg string, args ...interface{}) bool {
+ for _, f := range ff {
+ if f(level, msg, args...) {
+ return true
+ }
+ }
+
+ return false
+}
diff -Naur --color b/vendor/github.com/hashicorp/go-hclog/.gitignore a/vendor/github.com/hashicorp/go-hclog/.gitignore
--- b/vendor/github.com/hashicorp/go-hclog/.gitignore 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-hclog/.gitignore 2022-11-15 23:06:31.545390809 +0100
@@ -0,0 +1 @@
+.idea*
\ No newline at end of file
diff -Naur --color b/vendor/github.com/hashicorp/go-hclog/global.go a/vendor/github.com/hashicorp/go-hclog/global.go
--- b/vendor/github.com/hashicorp/go-hclog/global.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-hclog/global.go 2022-11-15 23:06:31.548724207 +0100
@@ -0,0 +1,62 @@
+package hclog
+
+import (
+ "sync"
+)
+
+var (
+ protect sync.Once
+ def Logger
+
+ // DefaultOptions is used to create the Default logger. These are read
+ // only when the Default logger is created, so set them as soon as the
+ // process starts.
+ DefaultOptions = &LoggerOptions{
+ Level: DefaultLevel,
+ Output: DefaultOutput,
+ }
+)
+
+// Default returns a globally held logger. This can be a good starting
+// place, and then you can use .With() and .Name() to create sub-loggers
+// to be used in more specific contexts.
+// The value of the Default logger can be set via SetDefault() or by
+// changing the options in DefaultOptions.
+//
+// This method is goroutine safe, returning a global from memory, but
+// cause should be used if SetDefault() is called it random times
+// in the program as that may result in race conditions and an unexpected
+// Logger being returned.
+func Default() Logger {
+ protect.Do(func() {
+ // If SetDefault was used before Default() was called, we need to
+ // detect that here.
+ if def == nil {
+ def = New(DefaultOptions)
+ }
+ })
+
+ return def
+}
+
+// L is a short alias for Default().
+func L() Logger {
+ return Default()
+}
+
+// SetDefault changes the logger to be returned by Default()and L()
+// to the one given. This allows packages to use the default logger
+// and have higher level packages change it to match the execution
+// environment. It returns any old default if there is one.
+//
+// NOTE: This is expected to be called early in the program to setup
+// a default logger. As such, it does not attempt to make itself
+// not racy with regard to the value of the default logger. Ergo
+// if it is called in goroutines, you may experience race conditions
+// with other goroutines retrieving the default logger. Basically,
+// don't do that.
+func SetDefault(log Logger) Logger {
+ old := def
+ def = log
+ return old
+}
diff -Naur --color b/vendor/github.com/hashicorp/go-hclog/interceptlogger.go a/vendor/github.com/hashicorp/go-hclog/interceptlogger.go
--- b/vendor/github.com/hashicorp/go-hclog/interceptlogger.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-hclog/interceptlogger.go 2022-11-15 23:06:31.548724207 +0100
@@ -0,0 +1,203 @@
+package hclog
+
+import (
+ "io"
+ "log"
+ "sync"
+ "sync/atomic"
+)
+
+var _ Logger = &interceptLogger{}
+
+type interceptLogger struct {
+ Logger
+
+ mu *sync.Mutex
+ sinkCount *int32
+ Sinks map[SinkAdapter]struct{}
+}
+
+func NewInterceptLogger(opts *LoggerOptions) InterceptLogger {
+ l := newLogger(opts)
+ if l.callerOffset > 0 {
+ // extra frames for interceptLogger.{Warn,Info,Log,etc...}, and interceptLogger.log
+ l.callerOffset += 2
+ }
+ intercept := &interceptLogger{
+ Logger: l,
+ mu: new(sync.Mutex),
+ sinkCount: new(int32),
+ Sinks: make(map[SinkAdapter]struct{}),
+ }
+
+ atomic.StoreInt32(intercept.sinkCount, 0)
+
+ return intercept
+}
+
+func (i *interceptLogger) Log(level Level, msg string, args ...interface{}) {
+ i.log(level, msg, args...)
+}
+
+// log is used to make the caller stack frame lookup consistent. If Warn,Info,etc
+// all called Log then direct calls to Log would have a different stack frame
+// depth. By having all the methods call the same helper we ensure the stack
+// frame depth is the same.
+func (i *interceptLogger) log(level Level, msg string, args ...interface{}) {
+ i.Logger.Log(level, msg, args...)
+ if atomic.LoadInt32(i.sinkCount) == 0 {
+ return
+ }
+
+ i.mu.Lock()
+ defer i.mu.Unlock()
+ for s := range i.Sinks {
+ s.Accept(i.Name(), level, msg, i.retrieveImplied(args...)...)
+ }
+}
+
+// Emit the message and args at TRACE level to log and sinks
+func (i *interceptLogger) Trace(msg string, args ...interface{}) {
+ i.log(Trace, msg, args...)
+}
+
+// Emit the message and args at DEBUG level to log and sinks
+func (i *interceptLogger) Debug(msg string, args ...interface{}) {
+ i.log(Debug, msg, args...)
+}
+
+// Emit the message and args at INFO level to log and sinks
+func (i *interceptLogger) Info(msg string, args ...interface{}) {
+ i.log(Info, msg, args...)
+}
+
+// Emit the message and args at WARN level to log and sinks
+func (i *interceptLogger) Warn(msg string, args ...interface{}) {
+ i.log(Warn, msg, args...)
+}
+
+// Emit the message and args at ERROR level to log and sinks
+func (i *interceptLogger) Error(msg string, args ...interface{}) {
+ i.log(Error, msg, args...)
+}
+
+func (i *interceptLogger) retrieveImplied(args ...interface{}) []interface{} {
+ top := i.Logger.ImpliedArgs()
+
+ cp := make([]interface{}, len(top)+len(args))
+ copy(cp, top)
+ copy(cp[len(top):], args)
+
+ return cp
+}
+
+// Create a new sub-Logger that a name descending from the current name.
+// This is used to create a subsystem specific Logger.
+// Registered sinks will subscribe to these messages as well.
+func (i *interceptLogger) Named(name string) Logger {
+ return i.NamedIntercept(name)
+}
+
+// Create a new sub-Logger with an explicit name. This ignores the current
+// name. This is used to create a standalone logger that doesn't fall
+// within the normal hierarchy. Registered sinks will subscribe
+// to these messages as well.
+func (i *interceptLogger) ResetNamed(name string) Logger {
+ return i.ResetNamedIntercept(name)
+}
+
+// Create a new sub-Logger that a name decending from the current name.
+// This is used to create a subsystem specific Logger.
+// Registered sinks will subscribe to these messages as well.
+func (i *interceptLogger) NamedIntercept(name string) InterceptLogger {
+ var sub interceptLogger
+
+ sub = *i
+ sub.Logger = i.Logger.Named(name)
+ return &sub
+}
+
+// Create a new sub-Logger with an explicit name. This ignores the current
+// name. This is used to create a standalone logger that doesn't fall
+// within the normal hierarchy. Registered sinks will subscribe
+// to these messages as well.
+func (i *interceptLogger) ResetNamedIntercept(name string) InterceptLogger {
+ var sub interceptLogger
+
+ sub = *i
+ sub.Logger = i.Logger.ResetNamed(name)
+ return &sub
+}
+
+// Return a sub-Logger for which every emitted log message will contain
+// the given key/value pairs. This is used to create a context specific
+// Logger.
+func (i *interceptLogger) With(args ...interface{}) Logger {
+ var sub interceptLogger
+
+ sub = *i
+
+ sub.Logger = i.Logger.With(args...)
+
+ return &sub
+}
+
+// RegisterSink attaches a SinkAdapter to interceptLoggers sinks.
+func (i *interceptLogger) RegisterSink(sink SinkAdapter) {
+ i.mu.Lock()
+ defer i.mu.Unlock()
+
+ i.Sinks[sink] = struct{}{}
+
+ atomic.AddInt32(i.sinkCount, 1)
+}
+
+// DeregisterSink removes a SinkAdapter from interceptLoggers sinks.
+func (i *interceptLogger) DeregisterSink(sink SinkAdapter) {
+ i.mu.Lock()
+ defer i.mu.Unlock()
+
+ delete(i.Sinks, sink)
+
+ atomic.AddInt32(i.sinkCount, -1)
+}
+
+func (i *interceptLogger) StandardLoggerIntercept(opts *StandardLoggerOptions) *log.Logger {
+ return i.StandardLogger(opts)
+}
+
+func (i *interceptLogger) StandardLogger(opts *StandardLoggerOptions) *log.Logger {
+ if opts == nil {
+ opts = &StandardLoggerOptions{}
+ }
+
+ return log.New(i.StandardWriter(opts), "", 0)
+}
+
+func (i *interceptLogger) StandardWriterIntercept(opts *StandardLoggerOptions) io.Writer {
+ return i.StandardWriter(opts)
+}
+
+func (i *interceptLogger) StandardWriter(opts *StandardLoggerOptions) io.Writer {
+ return &stdlogAdapter{
+ log: i,
+ inferLevels: opts.InferLevels,
+ forceLevel: opts.ForceLevel,
+ }
+}
+
+func (i *interceptLogger) ResetOutput(opts *LoggerOptions) error {
+ if or, ok := i.Logger.(OutputResettable); ok {
+ return or.ResetOutput(opts)
+ } else {
+ return nil
+ }
+}
+
+func (i *interceptLogger) ResetOutputWithFlush(opts *LoggerOptions, flushable Flushable) error {
+ if or, ok := i.Logger.(OutputResettable); ok {
+ return or.ResetOutputWithFlush(opts, flushable)
+ } else {
+ return nil
+ }
+}
diff -Naur --color b/vendor/github.com/hashicorp/go-hclog/intlogger.go a/vendor/github.com/hashicorp/go-hclog/intlogger.go
--- b/vendor/github.com/hashicorp/go-hclog/intlogger.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-hclog/intlogger.go 2022-11-15 23:06:31.548724207 +0100
@@ -0,0 +1,732 @@
+package hclog
+
+import (
+ "bytes"
+ "encoding"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+ "os"
+ "reflect"
+ "runtime"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/fatih/color"
+)
+
+// TimeFormat is the time format to use for plain (non-JSON) output.
+// This is a version of RFC3339 that contains millisecond precision.
+const TimeFormat = "2006-01-02T15:04:05.000Z0700"
+
+// TimeFormatJSON is the time format to use for JSON output.
+// This is a version of RFC3339 that contains microsecond precision.
+const TimeFormatJSON = "2006-01-02T15:04:05.000000Z07:00"
+
+// errJsonUnsupportedTypeMsg is included in log json entries, if an arg cannot be serialized to json
+const errJsonUnsupportedTypeMsg = "logging contained values that don't serialize to json"
+
+var (
+ _levelToBracket = map[Level]string{
+ Debug: "[DEBUG]",
+ Trace: "[TRACE]",
+ Info: "[INFO] ",
+ Warn: "[WARN] ",
+ Error: "[ERROR]",
+ }
+
+ _levelToColor = map[Level]*color.Color{
+ Debug: color.New(color.FgHiWhite),
+ Trace: color.New(color.FgHiGreen),
+ Info: color.New(color.FgHiBlue),
+ Warn: color.New(color.FgHiYellow),
+ Error: color.New(color.FgHiRed),
+ }
+)
+
+// Make sure that intLogger is a Logger
+var _ Logger = &intLogger{}
+
+// intLogger is an internal logger implementation. Internal in that it is
+// defined entirely by this package.
+type intLogger struct {
+ json bool
+ callerOffset int
+ name string
+ timeFormat string
+ disableTime bool
+
+ // This is an interface so that it's shared by any derived loggers, since
+ // those derived loggers share the bufio.Writer as well.
+ mutex Locker
+ writer *writer
+ level *int32
+
+ implied []interface{}
+
+ exclude func(level Level, msg string, args ...interface{}) bool
+
+ // create subloggers with their own level setting
+ independentLevels bool
+}
+
+// New returns a configured logger.
+func New(opts *LoggerOptions) Logger {
+ return newLogger(opts)
+}
+
+// NewSinkAdapter returns a SinkAdapter with configured settings
+// defined by LoggerOptions
+func NewSinkAdapter(opts *LoggerOptions) SinkAdapter {
+ l := newLogger(opts)
+ if l.callerOffset > 0 {
+ // extra frames for interceptLogger.{Warn,Info,Log,etc...}, and SinkAdapter.Accept
+ l.callerOffset += 2
+ }
+ return l
+}
+
+func newLogger(opts *LoggerOptions) *intLogger {
+ if opts == nil {
+ opts = &LoggerOptions{}
+ }
+
+ output := opts.Output
+ if output == nil {
+ output = DefaultOutput
+ }
+
+ level := opts.Level
+ if level == NoLevel {
+ level = DefaultLevel
+ }
+
+ mutex := opts.Mutex
+ if mutex == nil {
+ mutex = new(sync.Mutex)
+ }
+
+ l := &intLogger{
+ json: opts.JSONFormat,
+ name: opts.Name,
+ timeFormat: TimeFormat,
+ disableTime: opts.DisableTime,
+ mutex: mutex,
+ writer: newWriter(output, opts.Color),
+ level: new(int32),
+ exclude: opts.Exclude,
+ independentLevels: opts.IndependentLevels,
+ }
+ if opts.IncludeLocation {
+ l.callerOffset = offsetIntLogger + opts.AdditionalLocationOffset
+ }
+
+ if l.json {
+ l.timeFormat = TimeFormatJSON
+ }
+ if opts.TimeFormat != "" {
+ l.timeFormat = opts.TimeFormat
+ }
+
+ l.setColorization(opts)
+
+ atomic.StoreInt32(l.level, int32(level))
+
+ return l
+}
+
+// offsetIntLogger is the stack frame offset in the call stack for the caller to
+// one of the Warn,Info,Log,etc methods.
+const offsetIntLogger = 3
+
+// Log a message and a set of key/value pairs if the given level is at
+// or more severe that the threshold configured in the Logger.
+func (l *intLogger) log(name string, level Level, msg string, args ...interface{}) {
+ if level < Level(atomic.LoadInt32(l.level)) {
+ return
+ }
+
+ t := time.Now()
+
+ l.mutex.Lock()
+ defer l.mutex.Unlock()
+
+ if l.exclude != nil && l.exclude(level, msg, args...) {
+ return
+ }
+
+ if l.json {
+ l.logJSON(t, name, level, msg, args...)
+ } else {
+ l.logPlain(t, name, level, msg, args...)
+ }
+
+ l.writer.Flush(level)
+}
+
+// Cleanup a path by returning the last 2 segments of the path only.
+func trimCallerPath(path string) string {
+ // lovely borrowed from zap
+ // nb. To make sure we trim the path correctly on Windows too, we
+ // counter-intuitively need to use '/' and *not* os.PathSeparator here,
+ // because the path given originates from Go stdlib, specifically
+ // runtime.Caller() which (as of Mar/17) returns forward slashes even on
+ // Windows.
+ //
+ // See https://github.com/golang/go/issues/3335
+ // and https://github.com/golang/go/issues/18151
+ //
+ // for discussion on the issue on Go side.
+
+ // Find the last separator.
+ idx := strings.LastIndexByte(path, '/')
+ if idx == -1 {
+ return path
+ }
+
+ // Find the penultimate separator.
+ idx = strings.LastIndexByte(path[:idx], '/')
+ if idx == -1 {
+ return path
+ }
+
+ return path[idx+1:]
+}
+
+// Non-JSON logging format function
+func (l *intLogger) logPlain(t time.Time, name string, level Level, msg string, args ...interface{}) {
+
+ if !l.disableTime {
+ l.writer.WriteString(t.Format(l.timeFormat))
+ l.writer.WriteByte(' ')
+ }
+
+ s, ok := _levelToBracket[level]
+ if ok {
+ l.writer.WriteString(s)
+ } else {
+ l.writer.WriteString("[?????]")
+ }
+
+ if l.callerOffset > 0 {
+ if _, file, line, ok := runtime.Caller(l.callerOffset); ok {
+ l.writer.WriteByte(' ')
+ l.writer.WriteString(trimCallerPath(file))
+ l.writer.WriteByte(':')
+ l.writer.WriteString(strconv.Itoa(line))
+ l.writer.WriteByte(':')
+ }
+ }
+
+ l.writer.WriteByte(' ')
+
+ if name != "" {
+ l.writer.WriteString(name)
+ l.writer.WriteString(": ")
+ }
+
+ l.writer.WriteString(msg)
+
+ args = append(l.implied, args...)
+
+ var stacktrace CapturedStacktrace
+
+ if args != nil && len(args) > 0 {
+ if len(args)%2 != 0 {
+ cs, ok := args[len(args)-1].(CapturedStacktrace)
+ if ok {
+ args = args[:len(args)-1]
+ stacktrace = cs
+ } else {
+ extra := args[len(args)-1]
+ args = append(args[:len(args)-1], MissingKey, extra)
+ }
+ }
+
+ l.writer.WriteByte(':')
+
+ FOR:
+ for i := 0; i < len(args); i = i + 2 {
+ var (
+ val string
+ raw bool
+ )
+
+ switch st := args[i+1].(type) {
+ case string:
+ val = st
+ if st == "" {
+ val = `""`
+ }
+ case int:
+ val = strconv.FormatInt(int64(st), 10)
+ case int64:
+ val = strconv.FormatInt(int64(st), 10)
+ case int32:
+ val = strconv.FormatInt(int64(st), 10)
+ case int16:
+ val = strconv.FormatInt(int64(st), 10)
+ case int8:
+ val = strconv.FormatInt(int64(st), 10)
+ case uint:
+ val = strconv.FormatUint(uint64(st), 10)
+ case uint64:
+ val = strconv.FormatUint(uint64(st), 10)
+ case uint32:
+ val = strconv.FormatUint(uint64(st), 10)
+ case uint16:
+ val = strconv.FormatUint(uint64(st), 10)
+ case uint8:
+ val = strconv.FormatUint(uint64(st), 10)
+ case Hex:
+ val = "0x" + strconv.FormatUint(uint64(st), 16)
+ case Octal:
+ val = "0" + strconv.FormatUint(uint64(st), 8)
+ case Binary:
+ val = "0b" + strconv.FormatUint(uint64(st), 2)
+ case CapturedStacktrace:
+ stacktrace = st
+ continue FOR
+ case Format:
+ val = fmt.Sprintf(st[0].(string), st[1:]...)
+ case Quote:
+ raw = true
+ val = strconv.Quote(string(st))
+ default:
+ v := reflect.ValueOf(st)
+ if v.Kind() == reflect.Slice {
+ val = l.renderSlice(v)
+ raw = true
+ } else {
+ val = fmt.Sprintf("%v", st)
+ }
+ }
+
+ var key string
+
+ switch st := args[i].(type) {
+ case string:
+ key = st
+ default:
+ key = fmt.Sprintf("%s", st)
+ }
+
+ if strings.Contains(val, "\n") {
+ l.writer.WriteString("\n ")
+ l.writer.WriteString(key)
+ l.writer.WriteString("=\n")
+ writeIndent(l.writer, val, " | ")
+ l.writer.WriteString(" ")
+ } else if !raw && strings.ContainsAny(val, " \t") {
+ l.writer.WriteByte(' ')
+ l.writer.WriteString(key)
+ l.writer.WriteByte('=')
+ l.writer.WriteByte('"')
+ l.writer.WriteString(val)
+ l.writer.WriteByte('"')
+ } else {
+ l.writer.WriteByte(' ')
+ l.writer.WriteString(key)
+ l.writer.WriteByte('=')
+ l.writer.WriteString(val)
+ }
+ }
+ }
+
+ l.writer.WriteString("\n")
+
+ if stacktrace != "" {
+ l.writer.WriteString(string(stacktrace))
+ l.writer.WriteString("\n")
+ }
+}
+
+func writeIndent(w *writer, str string, indent string) {
+ for {
+ nl := strings.IndexByte(str, "\n"[0])
+ if nl == -1 {
+ if str != "" {
+ w.WriteString(indent)
+ w.WriteString(str)
+ w.WriteString("\n")
+ }
+ return
+ }
+
+ w.WriteString(indent)
+ w.WriteString(str[:nl])
+ w.WriteString("\n")
+ str = str[nl+1:]
+ }
+}
+
+func (l *intLogger) renderSlice(v reflect.Value) string {
+ var buf bytes.Buffer
+
+ buf.WriteRune('[')
+
+ for i := 0; i < v.Len(); i++ {
+ if i > 0 {
+ buf.WriteString(", ")
+ }
+
+ sv := v.Index(i)
+
+ var val string
+
+ switch sv.Kind() {
+ case reflect.String:
+ val = strconv.Quote(sv.String())
+ case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64:
+ val = strconv.FormatInt(sv.Int(), 10)
+ case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
+ val = strconv.FormatUint(sv.Uint(), 10)
+ default:
+ val = fmt.Sprintf("%v", sv.Interface())
+ if strings.ContainsAny(val, " \t\n\r") {
+ val = strconv.Quote(val)
+ }
+ }
+
+ buf.WriteString(val)
+ }
+
+ buf.WriteRune(']')
+
+ return buf.String()
+}
+
+// JSON logging function
+func (l *intLogger) logJSON(t time.Time, name string, level Level, msg string, args ...interface{}) {
+ vals := l.jsonMapEntry(t, name, level, msg)
+ args = append(l.implied, args...)
+
+ if args != nil && len(args) > 0 {
+ if len(args)%2 != 0 {
+ cs, ok := args[len(args)-1].(CapturedStacktrace)
+ if ok {
+ args = args[:len(args)-1]
+ vals["stacktrace"] = cs
+ } else {
+ extra := args[len(args)-1]
+ args = append(args[:len(args)-1], MissingKey, extra)
+ }
+ }
+
+ for i := 0; i < len(args); i = i + 2 {
+ val := args[i+1]
+ switch sv := val.(type) {
+ case error:
+ // Check if val is of type error. If error type doesn't
+ // implement json.Marshaler or encoding.TextMarshaler
+ // then set val to err.Error() so that it gets marshaled
+ switch sv.(type) {
+ case json.Marshaler, encoding.TextMarshaler:
+ default:
+ val = sv.Error()
+ }
+ case Format:
+ val = fmt.Sprintf(sv[0].(string), sv[1:]...)
+ }
+
+ var key string
+
+ switch st := args[i].(type) {
+ case string:
+ key = st
+ default:
+ key = fmt.Sprintf("%s", st)
+ }
+ vals[key] = val
+ }
+ }
+
+ err := json.NewEncoder(l.writer).Encode(vals)
+ if err != nil {
+ if _, ok := err.(*json.UnsupportedTypeError); ok {
+ plainVal := l.jsonMapEntry(t, name, level, msg)
+ plainVal["@warn"] = errJsonUnsupportedTypeMsg
+
+ json.NewEncoder(l.writer).Encode(plainVal)
+ }
+ }
+}
+
+func (l intLogger) jsonMapEntry(t time.Time, name string, level Level, msg string) map[string]interface{} {
+ vals := map[string]interface{}{
+ "@message": msg,
+ }
+ if !l.disableTime {
+ vals["@timestamp"] = t.Format(l.timeFormat)
+ }
+
+ var levelStr string
+ switch level {
+ case Error:
+ levelStr = "error"
+ case Warn:
+ levelStr = "warn"
+ case Info:
+ levelStr = "info"
+ case Debug:
+ levelStr = "debug"
+ case Trace:
+ levelStr = "trace"
+ default:
+ levelStr = "all"
+ }
+
+ vals["@level"] = levelStr
+
+ if name != "" {
+ vals["@module"] = name
+ }
+
+ if l.callerOffset > 0 {
+ if _, file, line, ok := runtime.Caller(l.callerOffset + 1); ok {
+ vals["@caller"] = fmt.Sprintf("%s:%d", file, line)
+ }
+ }
+ return vals
+}
+
+// Emit the message and args at the provided level
+func (l *intLogger) Log(level Level, msg string, args ...interface{}) {
+ l.log(l.Name(), level, msg, args...)
+}
+
+// Emit the message and args at DEBUG level
+func (l *intLogger) Debug(msg string, args ...interface{}) {
+ l.log(l.Name(), Debug, msg, args...)
+}
+
+// Emit the message and args at TRACE level
+func (l *intLogger) Trace(msg string, args ...interface{}) {
+ l.log(l.Name(), Trace, msg, args...)
+}
+
+// Emit the message and args at INFO level
+func (l *intLogger) Info(msg string, args ...interface{}) {
+ l.log(l.Name(), Info, msg, args...)
+}
+
+// Emit the message and args at WARN level
+func (l *intLogger) Warn(msg string, args ...interface{}) {
+ l.log(l.Name(), Warn, msg, args...)
+}
+
+// Emit the message and args at ERROR level
+func (l *intLogger) Error(msg string, args ...interface{}) {
+ l.log(l.Name(), Error, msg, args...)
+}
+
+// Indicate that the logger would emit TRACE level logs
+func (l *intLogger) IsTrace() bool {
+ return Level(atomic.LoadInt32(l.level)) == Trace
+}
+
+// Indicate that the logger would emit DEBUG level logs
+func (l *intLogger) IsDebug() bool {
+ return Level(atomic.LoadInt32(l.level)) <= Debug
+}
+
+// Indicate that the logger would emit INFO level logs
+func (l *intLogger) IsInfo() bool {
+ return Level(atomic.LoadInt32(l.level)) <= Info
+}
+
+// Indicate that the logger would emit WARN level logs
+func (l *intLogger) IsWarn() bool {
+ return Level(atomic.LoadInt32(l.level)) <= Warn
+}
+
+// Indicate that the logger would emit ERROR level logs
+func (l *intLogger) IsError() bool {
+ return Level(atomic.LoadInt32(l.level)) <= Error
+}
+
+const MissingKey = "EXTRA_VALUE_AT_END"
+
+// Return a sub-Logger for which every emitted log message will contain
+// the given key/value pairs. This is used to create a context specific
+// Logger.
+func (l *intLogger) With(args ...interface{}) Logger {
+ var extra interface{}
+
+ if len(args)%2 != 0 {
+ extra = args[len(args)-1]
+ args = args[:len(args)-1]
+ }
+
+ sl := l.copy()
+
+ result := make(map[string]interface{}, len(l.implied)+len(args))
+ keys := make([]string, 0, len(l.implied)+len(args))
+
+ // Read existing args, store map and key for consistent sorting
+ for i := 0; i < len(l.implied); i += 2 {
+ key := l.implied[i].(string)
+ keys = append(keys, key)
+ result[key] = l.implied[i+1]
+ }
+ // Read new args, store map and key for consistent sorting
+ for i := 0; i < len(args); i += 2 {
+ key := args[i].(string)
+ _, exists := result[key]
+ if !exists {
+ keys = append(keys, key)
+ }
+ result[key] = args[i+1]
+ }
+
+ // Sort keys to be consistent
+ sort.Strings(keys)
+
+ sl.implied = make([]interface{}, 0, len(l.implied)+len(args))
+ for _, k := range keys {
+ sl.implied = append(sl.implied, k)
+ sl.implied = append(sl.implied, result[k])
+ }
+
+ if extra != nil {
+ sl.implied = append(sl.implied, MissingKey, extra)
+ }
+
+ return sl
+}
+
+// Create a new sub-Logger that a name decending from the current name.
+// This is used to create a subsystem specific Logger.
+func (l *intLogger) Named(name string) Logger {
+ sl := l.copy()
+
+ if sl.name != "" {
+ sl.name = sl.name + "." + name
+ } else {
+ sl.name = name
+ }
+
+ return sl
+}
+
+// Create a new sub-Logger with an explicit name. This ignores the current
+// name. This is used to create a standalone logger that doesn't fall
+// within the normal hierarchy.
+func (l *intLogger) ResetNamed(name string) Logger {
+ sl := l.copy()
+
+ sl.name = name
+
+ return sl
+}
+
+func (l *intLogger) ResetOutput(opts *LoggerOptions) error {
+ if opts.Output == nil {
+ return errors.New("given output is nil")
+ }
+
+ l.mutex.Lock()
+ defer l.mutex.Unlock()
+
+ return l.resetOutput(opts)
+}
+
+func (l *intLogger) ResetOutputWithFlush(opts *LoggerOptions, flushable Flushable) error {
+ if opts.Output == nil {
+ return errors.New("given output is nil")
+ }
+ if flushable == nil {
+ return errors.New("flushable is nil")
+ }
+
+ l.mutex.Lock()
+ defer l.mutex.Unlock()
+
+ if err := flushable.Flush(); err != nil {
+ return err
+ }
+
+ return l.resetOutput(opts)
+}
+
+func (l *intLogger) resetOutput(opts *LoggerOptions) error {
+ l.writer = newWriter(opts.Output, opts.Color)
+ l.setColorization(opts)
+ return nil
+}
+
+// Update the logging level on-the-fly. This will affect all subloggers as
+// well.
+func (l *intLogger) SetLevel(level Level) {
+ atomic.StoreInt32(l.level, int32(level))
+}
+
+// Create a *log.Logger that will send it's data through this Logger. This
+// allows packages that expect to be using the standard library log to actually
+// use this logger.
+func (l *intLogger) StandardLogger(opts *StandardLoggerOptions) *log.Logger {
+ if opts == nil {
+ opts = &StandardLoggerOptions{}
+ }
+
+ return log.New(l.StandardWriter(opts), "", 0)
+}
+
+func (l *intLogger) StandardWriter(opts *StandardLoggerOptions) io.Writer {
+ newLog := *l
+ if l.callerOffset > 0 {
+ // the stack is
+ // logger.printf() -> l.Output() ->l.out.writer(hclog:stdlogAdaptor.write) -> hclog:stdlogAdaptor.dispatch()
+ // So plus 4.
+ newLog.callerOffset = l.callerOffset + 4
+ }
+ return &stdlogAdapter{
+ log: &newLog,
+ inferLevels: opts.InferLevels,
+ forceLevel: opts.ForceLevel,
+ }
+}
+
+// checks if the underlying io.Writer is a file, and
+// panics if not. For use by colorization.
+func (l *intLogger) checkWriterIsFile() *os.File {
+ fi, ok := l.writer.w.(*os.File)
+ if !ok {
+ panic("Cannot enable coloring of non-file Writers")
+ }
+ return fi
+}
+
+// Accept implements the SinkAdapter interface
+func (i *intLogger) Accept(name string, level Level, msg string, args ...interface{}) {
+ i.log(name, level, msg, args...)
+}
+
+// ImpliedArgs returns the loggers implied args
+func (i *intLogger) ImpliedArgs() []interface{} {
+ return i.implied
+}
+
+// Name returns the loggers name
+func (i *intLogger) Name() string {
+ return i.name
+}
+
+// copy returns a shallow copy of the intLogger, replacing the level pointer
+// when necessary
+func (l *intLogger) copy() *intLogger {
+ sl := *l
+
+ if l.independentLevels {
+ sl.level = new(int32)
+ *sl.level = *l.level
+ }
+
+ return &sl
+}
diff -Naur --color b/vendor/github.com/hashicorp/go-hclog/LICENSE a/vendor/github.com/hashicorp/go-hclog/LICENSE
--- b/vendor/github.com/hashicorp/go-hclog/LICENSE 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-hclog/LICENSE 2022-11-15 23:06:31.545390809 +0100
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2017 HashiCorp
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff -Naur --color b/vendor/github.com/hashicorp/go-hclog/logger.go a/vendor/github.com/hashicorp/go-hclog/logger.go
--- b/vendor/github.com/hashicorp/go-hclog/logger.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-hclog/logger.go 2022-11-15 23:06:31.548724207 +0100
@@ -0,0 +1,351 @@
+package hclog
+
+import (
+ "io"
+ "log"
+ "os"
+ "strings"
+)
+
+var (
+ //DefaultOutput is used as the default log output.
+ DefaultOutput io.Writer = os.Stderr
+
+ // DefaultLevel is used as the default log level.
+ DefaultLevel = Info
+)
+
+// Level represents a log level.
+type Level int32
+
+const (
+ // NoLevel is a special level used to indicate that no level has been
+ // set and allow for a default to be used.
+ NoLevel Level = 0
+
+ // Trace is the most verbose level. Intended to be used for the tracing
+ // of actions in code, such as function enters/exits, etc.
+ Trace Level = 1
+
+ // Debug information for programmer lowlevel analysis.
+ Debug Level = 2
+
+ // Info information about steady state operations.
+ Info Level = 3
+
+ // Warn information about rare but handled events.
+ Warn Level = 4
+
+ // Error information about unrecoverable events.
+ Error Level = 5
+
+ // Off disables all logging output.
+ Off Level = 6
+)
+
+// Format is a simple convience type for when formatting is required. When
+// processing a value of this type, the logger automatically treats the first
+// argument as a Printf formatting string and passes the rest as the values
+// to be formatted. For example: L.Info(Fmt{"%d beans/day", beans}).
+type Format []interface{}
+
+// Fmt returns a Format type. This is a convience function for creating a Format
+// type.
+func Fmt(str string, args ...interface{}) Format {
+ return append(Format{str}, args...)
+}
+
+// A simple shortcut to format numbers in hex when displayed with the normal
+// text output. For example: L.Info("header value", Hex(17))
+type Hex int
+
+// A simple shortcut to format numbers in octal when displayed with the normal
+// text output. For example: L.Info("perms", Octal(17))
+type Octal int
+
+// A simple shortcut to format numbers in binary when displayed with the normal
+// text output. For example: L.Info("bits", Binary(17))
+type Binary int
+
+// A simple shortcut to format strings with Go quoting. Control and
+// non-printable characters will be escaped with their backslash equivalents in
+// output. Intended for untrusted or multiline strings which should be logged
+// as concisely as possible.
+type Quote string
+
+// ColorOption expresses how the output should be colored, if at all.
+type ColorOption uint8
+
+const (
+ // ColorOff is the default coloration, and does not
+ // inject color codes into the io.Writer.
+ ColorOff ColorOption = iota
+ // AutoColor checks if the io.Writer is a tty,
+ // and if so enables coloring.
+ AutoColor
+ // ForceColor will enable coloring, regardless of whether
+ // the io.Writer is a tty or not.
+ ForceColor
+)
+
+// LevelFromString returns a Level type for the named log level, or "NoLevel" if
+// the level string is invalid. This facilitates setting the log level via
+// config or environment variable by name in a predictable way.
+func LevelFromString(levelStr string) Level {
+ // We don't care about case. Accept both "INFO" and "info".
+ levelStr = strings.ToLower(strings.TrimSpace(levelStr))
+ switch levelStr {
+ case "trace":
+ return Trace
+ case "debug":
+ return Debug
+ case "info":
+ return Info
+ case "warn":
+ return Warn
+ case "error":
+ return Error
+ case "off":
+ return Off
+ default:
+ return NoLevel
+ }
+}
+
+func (l Level) String() string {
+ switch l {
+ case Trace:
+ return "trace"
+ case Debug:
+ return "debug"
+ case Info:
+ return "info"
+ case Warn:
+ return "warn"
+ case Error:
+ return "error"
+ case NoLevel:
+ return "none"
+ case Off:
+ return "off"
+ default:
+ return "unknown"
+ }
+}
+
+// Logger describes the interface that must be implemeted by all loggers.
+type Logger interface {
+ // Args are alternating key, val pairs
+ // keys must be strings
+ // vals can be any type, but display is implementation specific
+ // Emit a message and key/value pairs at a provided log level
+ Log(level Level, msg string, args ...interface{})
+
+ // Emit a message and key/value pairs at the TRACE level
+ Trace(msg string, args ...interface{})
+
+ // Emit a message and key/value pairs at the DEBUG level
+ Debug(msg string, args ...interface{})
+
+ // Emit a message and key/value pairs at the INFO level
+ Info(msg string, args ...interface{})
+
+ // Emit a message and key/value pairs at the WARN level
+ Warn(msg string, args ...interface{})
+
+ // Emit a message and key/value pairs at the ERROR level
+ Error(msg string, args ...interface{})
+
+ // Indicate if TRACE logs would be emitted. This and the other Is* guards
+ // are used to elide expensive logging code based on the current level.
+ IsTrace() bool
+
+ // Indicate if DEBUG logs would be emitted. This and the other Is* guards
+ IsDebug() bool
+
+ // Indicate if INFO logs would be emitted. This and the other Is* guards
+ IsInfo() bool
+
+ // Indicate if WARN logs would be emitted. This and the other Is* guards
+ IsWarn() bool
+
+ // Indicate if ERROR logs would be emitted. This and the other Is* guards
+ IsError() bool
+
+ // ImpliedArgs returns With key/value pairs
+ ImpliedArgs() []interface{}
+
+ // Creates a sublogger that will always have the given key/value pairs
+ With(args ...interface{}) Logger
+
+ // Returns the Name of the logger
+ Name() string
+
+ // Create a logger that will prepend the name string on the front of all messages.
+ // If the logger already has a name, the new value will be appended to the current
+ // name. That way, a major subsystem can use this to decorate all it's own logs
+ // without losing context.
+ Named(name string) Logger
+
+ // Create a logger that will prepend the name string on the front of all messages.
+ // This sets the name of the logger to the value directly, unlike Named which honor
+ // the current name as well.
+ ResetNamed(name string) Logger
+
+ // Updates the level. This should affect all related loggers as well,
+ // unless they were created with IndependentLevels. If an
+ // implementation cannot update the level on the fly, it should no-op.
+ SetLevel(level Level)
+
+ // Return a value that conforms to the stdlib log.Logger interface
+ StandardLogger(opts *StandardLoggerOptions) *log.Logger
+
+ // Return a value that conforms to io.Writer, which can be passed into log.SetOutput()
+ StandardWriter(opts *StandardLoggerOptions) io.Writer
+}
+
+// StandardLoggerOptions can be used to configure a new standard logger.
+type StandardLoggerOptions struct {
+ // Indicate that some minimal parsing should be done on strings to try
+ // and detect their level and re-emit them.
+ // This supports the strings like [ERROR], [ERR] [TRACE], [WARN], [INFO],
+ // [DEBUG] and strip it off before reapplying it.
+ InferLevels bool
+
+ // ForceLevel is used to force all output from the standard logger to be at
+ // the specified level. Similar to InferLevels, this will strip any level
+ // prefix contained in the logged string before applying the forced level.
+ // If set, this override InferLevels.
+ ForceLevel Level
+}
+
+// LoggerOptions can be used to configure a new logger.
+type LoggerOptions struct {
+ // Name of the subsystem to prefix logs with
+ Name string
+
+ // The threshold for the logger. Anything less severe is supressed
+ Level Level
+
+ // Where to write the logs to. Defaults to os.Stderr if nil
+ Output io.Writer
+
+ // An optional Locker in case Output is shared. This can be a sync.Mutex or
+ // a NoopLocker if the caller wants control over output, e.g. for batching
+ // log lines.
+ Mutex Locker
+
+ // Control if the output should be in JSON.
+ JSONFormat bool
+
+ // Include file and line information in each log line
+ IncludeLocation bool
+
+ // AdditionalLocationOffset is the number of additional stack levels to skip
+ // when finding the file and line information for the log line
+ AdditionalLocationOffset int
+
+ // The time format to use instead of the default
+ TimeFormat string
+
+ // Control whether or not to display the time at all. This is required
+ // because setting TimeFormat to empty assumes the default format.
+ DisableTime bool
+
+ // Color the output. On Windows, colored logs are only avaiable for io.Writers that
+ // are concretely instances of *os.File.
+ Color ColorOption
+
+ // A function which is called with the log information and if it returns true the value
+ // should not be logged.
+ // This is useful when interacting with a system that you wish to suppress the log
+ // message for (because it's too noisy, etc)
+ Exclude func(level Level, msg string, args ...interface{}) bool
+
+ // IndependentLevels causes subloggers to be created with an independent
+ // copy of this logger's level. This means that using SetLevel on this
+ // logger will not effect any subloggers, and SetLevel on any subloggers
+ // will not effect the parent or sibling loggers.
+ IndependentLevels bool
+}
+
+// InterceptLogger describes the interface for using a logger
+// that can register different output sinks.
+// This is useful for sending lower level log messages
+// to a different output while keeping the root logger
+// at a higher one.
+type InterceptLogger interface {
+ // Logger is the root logger for an InterceptLogger
+ Logger
+
+ // RegisterSink adds a SinkAdapter to the InterceptLogger
+ RegisterSink(sink SinkAdapter)
+
+ // DeregisterSink removes a SinkAdapter from the InterceptLogger
+ DeregisterSink(sink SinkAdapter)
+
+ // Create a interceptlogger that will prepend the name string on the front of all messages.
+ // If the logger already has a name, the new value will be appended to the current
+ // name. That way, a major subsystem can use this to decorate all it's own logs
+ // without losing context.
+ NamedIntercept(name string) InterceptLogger
+
+ // Create a interceptlogger that will prepend the name string on the front of all messages.
+ // This sets the name of the logger to the value directly, unlike Named which honor
+ // the current name as well.
+ ResetNamedIntercept(name string) InterceptLogger
+
+ // Deprecated: use StandardLogger
+ StandardLoggerIntercept(opts *StandardLoggerOptions) *log.Logger
+
+ // Deprecated: use StandardWriter
+ StandardWriterIntercept(opts *StandardLoggerOptions) io.Writer
+}
+
+// SinkAdapter describes the interface that must be implemented
+// in order to Register a new sink to an InterceptLogger
+type SinkAdapter interface {
+ Accept(name string, level Level, msg string, args ...interface{})
+}
+
+// Flushable represents a method for flushing an output buffer. It can be used
+// if Resetting the log to use a new output, in order to flush the writes to
+// the existing output beforehand.
+type Flushable interface {
+ Flush() error
+}
+
+// OutputResettable provides ways to swap the output in use at runtime
+type OutputResettable interface {
+ // ResetOutput swaps the current output writer with the one given in the
+ // opts. Color options given in opts will be used for the new output.
+ ResetOutput(opts *LoggerOptions) error
+
+ // ResetOutputWithFlush swaps the current output writer with the one given
+ // in the opts, first calling Flush on the given Flushable. Color options
+ // given in opts will be used for the new output.
+ ResetOutputWithFlush(opts *LoggerOptions, flushable Flushable) error
+}
+
+// Locker is used for locking output. If not set when creating a logger, a
+// sync.Mutex will be used internally.
+type Locker interface {
+ // Lock is called when the output is going to be changed or written to
+ Lock()
+
+ // Unlock is called when the operation that called Lock() completes
+ Unlock()
+}
+
+// NoopLocker implements locker but does nothing. This is useful if the client
+// wants tight control over locking, in order to provide grouping of log
+// entries or other functionality.
+type NoopLocker struct{}
+
+// Lock does nothing
+func (n NoopLocker) Lock() {}
+
+// Unlock does nothing
+func (n NoopLocker) Unlock() {}
+
+var _ Locker = (*NoopLocker)(nil)
diff -Naur --color b/vendor/github.com/hashicorp/go-hclog/nulllogger.go a/vendor/github.com/hashicorp/go-hclog/nulllogger.go
--- b/vendor/github.com/hashicorp/go-hclog/nulllogger.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-hclog/nulllogger.go 2022-11-15 23:06:31.548724207 +0100
@@ -0,0 +1,58 @@
+package hclog
+
+import (
+ "io"
+ "io/ioutil"
+ "log"
+)
+
+// NewNullLogger instantiates a Logger for which all calls
+// will succeed without doing anything.
+// Useful for testing purposes.
+func NewNullLogger() Logger {
+ return &nullLogger{}
+}
+
+type nullLogger struct{}
+
+func (l *nullLogger) Log(level Level, msg string, args ...interface{}) {}
+
+func (l *nullLogger) Trace(msg string, args ...interface{}) {}
+
+func (l *nullLogger) Debug(msg string, args ...interface{}) {}
+
+func (l *nullLogger) Info(msg string, args ...interface{}) {}
+
+func (l *nullLogger) Warn(msg string, args ...interface{}) {}
+
+func (l *nullLogger) Error(msg string, args ...interface{}) {}
+
+func (l *nullLogger) IsTrace() bool { return false }
+
+func (l *nullLogger) IsDebug() bool { return false }
+
+func (l *nullLogger) IsInfo() bool { return false }
+
+func (l *nullLogger) IsWarn() bool { return false }
+
+func (l *nullLogger) IsError() bool { return false }
+
+func (l *nullLogger) ImpliedArgs() []interface{} { return []interface{}{} }
+
+func (l *nullLogger) With(args ...interface{}) Logger { return l }
+
+func (l *nullLogger) Name() string { return "" }
+
+func (l *nullLogger) Named(name string) Logger { return l }
+
+func (l *nullLogger) ResetNamed(name string) Logger { return l }
+
+func (l *nullLogger) SetLevel(level Level) {}
+
+func (l *nullLogger) StandardLogger(opts *StandardLoggerOptions) *log.Logger {
+ return log.New(l.StandardWriter(opts), "", log.LstdFlags)
+}
+
+func (l *nullLogger) StandardWriter(opts *StandardLoggerOptions) io.Writer {
+ return ioutil.Discard
+}
diff -Naur --color b/vendor/github.com/hashicorp/go-hclog/README.md a/vendor/github.com/hashicorp/go-hclog/README.md
--- b/vendor/github.com/hashicorp/go-hclog/README.md 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-hclog/README.md 2022-11-15 23:06:31.545390809 +0100
@@ -0,0 +1,148 @@
+# go-hclog
+
+[![Go Documentation](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)][godocs]
+
+[godocs]: https://godoc.org/github.com/hashicorp/go-hclog
+
+`go-hclog` is a package for Go that provides a simple key/value logging
+interface for use in development and production environments.
+
+It provides logging levels that provide decreased output based upon the
+desired amount of output, unlike the standard library `log` package.
+
+It provides `Printf` style logging of values via `hclog.Fmt()`.
+
+It provides a human readable output mode for use in development as well as
+JSON output mode for production.
+
+## Stability Note
+
+While this library is fully open source and HashiCorp will be maintaining it
+(since we are and will be making extensive use of it), the API and output
+format is subject to minor changes as we fully bake and vet it in our projects.
+This notice will be removed once it's fully integrated into our major projects
+and no further changes are anticipated.
+
+## Installation and Docs
+
+Install using `go get github.com/hashicorp/go-hclog`.
+
+Full documentation is available at
+http://godoc.org/github.com/hashicorp/go-hclog
+
+## Usage
+
+### Use the global logger
+
+```go
+hclog.Default().Info("hello world")
+```
+
+```text
+2017-07-05T16:15:55.167-0700 [INFO ] hello world
+```
+
+(Note timestamps are removed in future examples for brevity.)
+
+### Create a new logger
+
+```go
+appLogger := hclog.New(&hclog.LoggerOptions{
+ Name: "my-app",
+ Level: hclog.LevelFromString("DEBUG"),
+})
+```
+
+### Emit an Info level message with 2 key/value pairs
+
+```go
+input := "5.5"
+_, err := strconv.ParseInt(input, 10, 32)
+if err != nil {
+ appLogger.Info("Invalid input for ParseInt", "input", input, "error", err)
+}
+```
+
+```text
+... [INFO ] my-app: Invalid input for ParseInt: input=5.5 error="strconv.ParseInt: parsing "5.5": invalid syntax"
+```
+
+### Create a new Logger for a major subsystem
+
+```go
+subsystemLogger := appLogger.Named("transport")
+subsystemLogger.Info("we are transporting something")
+```
+
+```text
+... [INFO ] my-app.transport: we are transporting something
+```
+
+Notice that logs emitted by `subsystemLogger` contain `my-app.transport`,
+reflecting both the application and subsystem names.
+
+### Create a new Logger with fixed key/value pairs
+
+Using `With()` will include a specific key-value pair in all messages emitted
+by that logger.
+
+```go
+requestID := "5fb446b6-6eba-821d-df1b-cd7501b6a363"
+requestLogger := subsystemLogger.With("request", requestID)
+requestLogger.Info("we are transporting a request")
+```
+
+```text
+... [INFO ] my-app.transport: we are transporting a request: request=5fb446b6-6eba-821d-df1b-cd7501b6a363
+```
+
+This allows sub Loggers to be context specific without having to thread that
+into all the callers.
+
+### Using `hclog.Fmt()`
+
+```go
+var int totalBandwidth = 200
+appLogger.Info("total bandwidth exceeded", "bandwidth", hclog.Fmt("%d GB/s", totalBandwidth))
+```
+
+```text
+... [INFO ] my-app: total bandwidth exceeded: bandwidth="200 GB/s"
+```
+
+### Use this with code that uses the standard library logger
+
+If you want to use the standard library's `log.Logger` interface you can wrap
+`hclog.Logger` by calling the `StandardLogger()` method. This allows you to use
+it with the familiar `Println()`, `Printf()`, etc. For example:
+
+```go
+stdLogger := appLogger.StandardLogger(&hclog.StandardLoggerOptions{
+ InferLevels: true,
+})
+// Printf() is provided by stdlib log.Logger interface, not hclog.Logger
+stdLogger.Printf("[DEBUG] %+v", stdLogger)
+```
+
+```text
+... [DEBUG] my-app: &{mu:{state:0 sema:0} prefix: flag:0 out:0xc42000a0a0 buf:[]}
+```
+
+Alternatively, you may configure the system-wide logger:
+
+```go
+// log the standard logger from 'import "log"'
+log.SetOutput(appLogger.StandardWriter(&hclog.StandardLoggerOptions{InferLevels: true}))
+log.SetPrefix("")
+log.SetFlags(0)
+
+log.Printf("[DEBUG] %d", 42)
+```
+
+```text
+... [DEBUG] my-app: 42
+```
+
+Notice that if `appLogger` is initialized with the `INFO` log level _and_ you
+specify `InferLevels: true`, you will not see any output here. You must change
+`appLogger` to `DEBUG` to see output. See the docs for more information.
diff -Naur --color b/vendor/github.com/hashicorp/go-hclog/stacktrace.go a/vendor/github.com/hashicorp/go-hclog/stacktrace.go
--- b/vendor/github.com/hashicorp/go-hclog/stacktrace.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-hclog/stacktrace.go 2022-11-15 23:06:31.548724207 +0100
@@ -0,0 +1,109 @@
+// Copyright (c) 2016 Uber Technologies, Inc.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+package hclog
+
+import (
+ "bytes"
+ "runtime"
+ "strconv"
+ "strings"
+ "sync"
+)
+
+var (
+ _stacktraceIgnorePrefixes = []string{
+ "runtime.goexit",
+ "runtime.main",
+ }
+ _stacktracePool = sync.Pool{
+ New: func() interface{} {
+ return newProgramCounters(64)
+ },
+ }
+)
+
+// CapturedStacktrace represents a stacktrace captured by a previous call
+// to log.Stacktrace. If passed to a logging function, the stacktrace
+// will be appended.
+type CapturedStacktrace string
+
+// Stacktrace captures a stacktrace of the current goroutine and returns
+// it to be passed to a logging function.
+func Stacktrace() CapturedStacktrace {
+ return CapturedStacktrace(takeStacktrace())
+}
+
+func takeStacktrace() string {
+ programCounters := _stacktracePool.Get().(*programCounters)
+ defer _stacktracePool.Put(programCounters)
+
+ var buffer bytes.Buffer
+
+ for {
+ // Skip the call to runtime.Counters and takeStacktrace so that the
+ // program counters start at the caller of takeStacktrace.
+ n := runtime.Callers(2, programCounters.pcs)
+ if n < cap(programCounters.pcs) {
+ programCounters.pcs = programCounters.pcs[:n]
+ break
+ }
+ // Don't put the too-short counter slice back into the pool; this lets
+ // the pool adjust if we consistently take deep stacktraces.
+ programCounters = newProgramCounters(len(programCounters.pcs) * 2)
+ }
+
+ i := 0
+ frames := runtime.CallersFrames(programCounters.pcs)
+ for frame, more := frames.Next(); more; frame, more = frames.Next() {
+ if shouldIgnoreStacktraceFunction(frame.Function) {
+ continue
+ }
+ if i != 0 {
+ buffer.WriteByte('\n')
+ }
+ i++
+ buffer.WriteString(frame.Function)
+ buffer.WriteByte('\n')
+ buffer.WriteByte('\t')
+ buffer.WriteString(frame.File)
+ buffer.WriteByte(':')
+ buffer.WriteString(strconv.Itoa(int(frame.Line)))
+ }
+
+ return buffer.String()
+}
+
+func shouldIgnoreStacktraceFunction(function string) bool {
+ for _, prefix := range _stacktraceIgnorePrefixes {
+ if strings.HasPrefix(function, prefix) {
+ return true
+ }
+ }
+ return false
+}
+
+type programCounters struct {
+ pcs []uintptr
+}
+
+func newProgramCounters(size int) *programCounters {
+ return &programCounters{make([]uintptr, size)}
+}
diff -Naur --color b/vendor/github.com/hashicorp/go-hclog/stdlog.go a/vendor/github.com/hashicorp/go-hclog/stdlog.go
--- b/vendor/github.com/hashicorp/go-hclog/stdlog.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-hclog/stdlog.go 2022-11-15 23:06:31.548724207 +0100
@@ -0,0 +1,95 @@
+package hclog
+
+import (
+ "bytes"
+ "log"
+ "strings"
+)
+
+// Provides a io.Writer to shim the data out of *log.Logger
+// and back into our Logger. This is basically the only way to
+// build upon *log.Logger.
+type stdlogAdapter struct {
+ log Logger
+ inferLevels bool
+ forceLevel Level
+}
+
+// Take the data, infer the levels if configured, and send it through
+// a regular Logger.
+func (s *stdlogAdapter) Write(data []byte) (int, error) {
+ str := string(bytes.TrimRight(data, " \t\n"))
+
+ if s.forceLevel != NoLevel {
+ // Use pickLevel to strip log levels included in the line since we are
+ // forcing the level
+ _, str := s.pickLevel(str)
+
+ // Log at the forced level
+ s.dispatch(str, s.forceLevel)
+ } else if s.inferLevels {
+ level, str := s.pickLevel(str)
+ s.dispatch(str, level)
+ } else {
+ s.log.Info(str)
+ }
+
+ return len(data), nil
+}
+
+func (s *stdlogAdapter) dispatch(str string, level Level) {
+ switch level {
+ case Trace:
+ s.log.Trace(str)
+ case Debug:
+ s.log.Debug(str)
+ case Info:
+ s.log.Info(str)
+ case Warn:
+ s.log.Warn(str)
+ case Error:
+ s.log.Error(str)
+ default:
+ s.log.Info(str)
+ }
+}
+
+// Detect, based on conventions, what log level this is.
+func (s *stdlogAdapter) pickLevel(str string) (Level, string) {
+ switch {
+ case strings.HasPrefix(str, "[DEBUG]"):
+ return Debug, strings.TrimSpace(str[7:])
+ case strings.HasPrefix(str, "[TRACE]"):
+ return Trace, strings.TrimSpace(str[7:])
+ case strings.HasPrefix(str, "[INFO]"):
+ return Info, strings.TrimSpace(str[6:])
+ case strings.HasPrefix(str, "[WARN]"):
+ return Warn, strings.TrimSpace(str[6:])
+ case strings.HasPrefix(str, "[ERROR]"):
+ return Error, strings.TrimSpace(str[7:])
+ case strings.HasPrefix(str, "[ERR]"):
+ return Error, strings.TrimSpace(str[5:])
+ default:
+ return Info, str
+ }
+}
+
+type logWriter struct {
+ l *log.Logger
+}
+
+func (l *logWriter) Write(b []byte) (int, error) {
+ l.l.Println(string(bytes.TrimRight(b, " \n\t")))
+ return len(b), nil
+}
+
+// Takes a standard library logger and returns a Logger that will write to it
+func FromStandardLogger(l *log.Logger, opts *LoggerOptions) Logger {
+ var dl LoggerOptions = *opts
+
+ // Use the time format that log.Logger uses
+ dl.DisableTime = true
+ dl.Output = &logWriter{l}
+
+ return New(&dl)
+}
diff -Naur --color b/vendor/github.com/hashicorp/go-hclog/writer.go a/vendor/github.com/hashicorp/go-hclog/writer.go
--- b/vendor/github.com/hashicorp/go-hclog/writer.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-hclog/writer.go 2022-11-15 23:06:31.548724207 +0100
@@ -0,0 +1,82 @@
+package hclog
+
+import (
+ "bytes"
+ "io"
+)
+
+type writer struct {
+ b bytes.Buffer
+ w io.Writer
+ color ColorOption
+}
+
+func newWriter(w io.Writer, color ColorOption) *writer {
+ return &writer{w: w, color: color}
+}
+
+func (w *writer) Flush(level Level) (err error) {
+ var unwritten = w.b.Bytes()
+
+ if w.color != ColorOff {
+ color := _levelToColor[level]
+ unwritten = []byte(color.Sprintf("%s", unwritten))
+ }
+
+ if lw, ok := w.w.(LevelWriter); ok {
+ _, err = lw.LevelWrite(level, unwritten)
+ } else {
+ _, err = w.w.Write(unwritten)
+ }
+ w.b.Reset()
+ return err
+}
+
+func (w *writer) Write(p []byte) (int, error) {
+ return w.b.Write(p)
+}
+
+func (w *writer) WriteByte(c byte) error {
+ return w.b.WriteByte(c)
+}
+
+func (w *writer) WriteString(s string) (int, error) {
+ return w.b.WriteString(s)
+}
+
+// LevelWriter is the interface that wraps the LevelWrite method.
+type LevelWriter interface {
+ LevelWrite(level Level, p []byte) (n int, err error)
+}
+
+// LeveledWriter writes all log messages to the standard writer,
+// except for log levels that are defined in the overrides map.
+type LeveledWriter struct {
+ standard io.Writer
+ overrides map[Level]io.Writer
+}
+
+// NewLeveledWriter returns an initialized LeveledWriter.
+//
+// standard will be used as the default writer for all log levels,
+// except for log levels that are defined in the overrides map.
+func NewLeveledWriter(standard io.Writer, overrides map[Level]io.Writer) *LeveledWriter {
+ return &LeveledWriter{
+ standard: standard,
+ overrides: overrides,
+ }
+}
+
+// Write implements io.Writer.
+func (lw *LeveledWriter) Write(p []byte) (int, error) {
+ return lw.standard.Write(p)
+}
+
+// LevelWrite implements LevelWriter.
+func (lw *LeveledWriter) LevelWrite(level Level, p []byte) (int, error) {
+ w, ok := lw.overrides[level]
+ if !ok {
+ w = lw.standard
+ }
+ return w.Write(p)
+}
diff -Naur --color b/vendor/github.com/hashicorp/go-immutable-radix/CHANGELOG.md a/vendor/github.com/hashicorp/go-immutable-radix/CHANGELOG.md
--- b/vendor/github.com/hashicorp/go-immutable-radix/CHANGELOG.md 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-immutable-radix/CHANGELOG.md 2022-11-15 23:06:31.552057604 +0100
@@ -0,0 +1,23 @@
+# UNRELEASED
+
+# 1.3.0 (September 17th, 2020)
+
+FEATURES
+
+* Add reverse tree traversal [[GH-30](https://github.com/hashicorp/go-immutable-radix/pull/30)]
+
+# 1.2.0 (March 18th, 2020)
+
+FEATURES
+
+* Adds a `Clone` method to `Txn` allowing transactions to be split either into two independently mutable trees. [[GH-26](https://github.com/hashicorp/go-immutable-radix/pull/26)]
+
+# 1.1.0 (May 22nd, 2019)
+
+FEATURES
+
+* Add `SeekLowerBound` to allow for range scans. [[GH-24](https://github.com/hashicorp/go-immutable-radix/pull/24)]
+
+# 1.0.0 (August 30th, 2018)
+
+* go mod adopted
diff -Naur --color b/vendor/github.com/hashicorp/go-immutable-radix/edges.go a/vendor/github.com/hashicorp/go-immutable-radix/edges.go
--- b/vendor/github.com/hashicorp/go-immutable-radix/edges.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-immutable-radix/edges.go 2022-11-15 23:06:31.552057604 +0100
@@ -0,0 +1,21 @@
+package iradix
+
+import "sort"
+
+type edges []edge
+
+func (e edges) Len() int {
+ return len(e)
+}
+
+func (e edges) Less(i, j int) bool {
+ return e[i].label < e[j].label
+}
+
+func (e edges) Swap(i, j int) {
+ e[i], e[j] = e[j], e[i]
+}
+
+func (e edges) Sort() {
+ sort.Sort(e)
+}
diff -Naur --color b/vendor/github.com/hashicorp/go-immutable-radix/.gitignore a/vendor/github.com/hashicorp/go-immutable-radix/.gitignore
--- b/vendor/github.com/hashicorp/go-immutable-radix/.gitignore 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-immutable-radix/.gitignore 2022-11-15 23:06:31.552057604 +0100
@@ -0,0 +1,24 @@
+# Compiled Object files, Static and Dynamic libs (Shared Objects)
+*.o
+*.a
+*.so
+
+# Folders
+_obj
+_test
+
+# Architecture specific extensions/prefixes
+*.[568vq]
+[568vq].out
+
+*.cgo1.go
+*.cgo2.c
+_cgo_defun.c
+_cgo_gotypes.go
+_cgo_export.*
+
+_testmain.go
+
+*.exe
+*.test
+*.prof
diff -Naur --color b/vendor/github.com/hashicorp/go-immutable-radix/iradix.go a/vendor/github.com/hashicorp/go-immutable-radix/iradix.go
--- b/vendor/github.com/hashicorp/go-immutable-radix/iradix.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-immutable-radix/iradix.go 2022-11-15 23:06:31.552057604 +0100
@@ -0,0 +1,676 @@
+package iradix
+
+import (
+ "bytes"
+ "strings"
+
+ "github.com/hashicorp/golang-lru/simplelru"
+)
+
+const (
+ // defaultModifiedCache is the default size of the modified node
+ // cache used per transaction. This is used to cache the updates
+ // to the nodes near the root, while the leaves do not need to be
+ // cached. This is important for very large transactions to prevent
+ // the modified cache from growing to be enormous. This is also used
+ // to set the max size of the mutation notify maps since those should
+ // also be bounded in a similar way.
+ defaultModifiedCache = 8192
+)
+
+// Tree implements an immutable radix tree. This can be treated as a
+// Dictionary abstract data type. The main advantage over a standard
+// hash map is prefix-based lookups and ordered iteration. The immutability
+// means that it is safe to concurrently read from a Tree without any
+// coordination.
+type Tree struct {
+ root *Node
+ size int
+}
+
+// New returns an empty Tree
+func New() *Tree {
+ t := &Tree{
+ root: &Node{
+ mutateCh: make(chan struct{}),
+ },
+ }
+ return t
+}
+
+// Len is used to return the number of elements in the tree
+func (t *Tree) Len() int {
+ return t.size
+}
+
+// Txn is a transaction on the tree. This transaction is applied
+// atomically and returns a new tree when committed. A transaction
+// is not thread safe, and should only be used by a single goroutine.
+type Txn struct {
+ // root is the modified root for the transaction.
+ root *Node
+
+ // snap is a snapshot of the root node for use if we have to run the
+ // slow notify algorithm.
+ snap *Node
+
+ // size tracks the size of the tree as it is modified during the
+ // transaction.
+ size int
+
+ // writable is a cache of writable nodes that have been created during
+ // the course of the transaction. This allows us to re-use the same
+ // nodes for further writes and avoid unnecessary copies of nodes that
+ // have never been exposed outside the transaction. This will only hold
+ // up to defaultModifiedCache number of entries.
+ writable *simplelru.LRU
+
+ // trackChannels is used to hold channels that need to be notified to
+ // signal mutation of the tree. This will only hold up to
+ // defaultModifiedCache number of entries, after which we will set the
+ // trackOverflow flag, which will cause us to use a more expensive
+ // algorithm to perform the notifications. Mutation tracking is only
+ // performed if trackMutate is true.
+ trackChannels map[chan struct{}]struct{}
+ trackOverflow bool
+ trackMutate bool
+}
+
+// Txn starts a new transaction that can be used to mutate the tree
+func (t *Tree) Txn() *Txn {
+ txn := &Txn{
+ root: t.root,
+ snap: t.root,
+ size: t.size,
+ }
+ return txn
+}
+
+// Clone makes an independent copy of the transaction. The new transaction
+// does not track any nodes and has TrackMutate turned off. The cloned transaction will contain any uncommitted writes in the original transaction but further mutations to either will be independent and result in different radix trees on Commit. A cloned transaction may be passed to another goroutine and mutated there independently however each transaction may only be mutated in a single thread.
+func (t *Txn) Clone() *Txn {
+ // reset the writable node cache to avoid leaking future writes into the clone
+ t.writable = nil
+
+ txn := &Txn{
+ root: t.root,
+ snap: t.snap,
+ size: t.size,
+ }
+ return txn
+}
+
+// TrackMutate can be used to toggle if mutations are tracked. If this is enabled
+// then notifications will be issued for affected internal nodes and leaves when
+// the transaction is committed.
+func (t *Txn) TrackMutate(track bool) {
+ t.trackMutate = track
+}
+
+// trackChannel safely attempts to track the given mutation channel, setting the
+// overflow flag if we can no longer track any more. This limits the amount of
+// state that will accumulate during a transaction and we have a slower algorithm
+// to switch to if we overflow.
+func (t *Txn) trackChannel(ch chan struct{}) {
+ // In overflow, make sure we don't store any more objects.
+ if t.trackOverflow {
+ return
+ }
+
+ // If this would overflow the state we reject it and set the flag (since
+ // we aren't tracking everything that's required any longer).
+ if len(t.trackChannels) >= defaultModifiedCache {
+ // Mark that we are in the overflow state
+ t.trackOverflow = true
+
+ // Clear the map so that the channels can be garbage collected. It is
+ // safe to do this since we have already overflowed and will be using
+ // the slow notify algorithm.
+ t.trackChannels = nil
+ return
+ }
+
+ // Create the map on the fly when we need it.
+ if t.trackChannels == nil {
+ t.trackChannels = make(map[chan struct{}]struct{})
+ }
+
+ // Otherwise we are good to track it.
+ t.trackChannels[ch] = struct{}{}
+}
+
+// writeNode returns a node to be modified, if the current node has already been
+// modified during the course of the transaction, it is used in-place. Set
+// forLeafUpdate to true if you are getting a write node to update the leaf,
+// which will set leaf mutation tracking appropriately as well.
+func (t *Txn) writeNode(n *Node, forLeafUpdate bool) *Node {
+ // Ensure the writable set exists.
+ if t.writable == nil {
+ lru, err := simplelru.NewLRU(defaultModifiedCache, nil)
+ if err != nil {
+ panic(err)
+ }
+ t.writable = lru
+ }
+
+ // If this node has already been modified, we can continue to use it
+ // during this transaction. We know that we don't need to track it for
+ // a node update since the node is writable, but if this is for a leaf
+ // update we track it, in case the initial write to this node didn't
+ // update the leaf.
+ if _, ok := t.writable.Get(n); ok {
+ if t.trackMutate && forLeafUpdate && n.leaf != nil {
+ t.trackChannel(n.leaf.mutateCh)
+ }
+ return n
+ }
+
+ // Mark this node as being mutated.
+ if t.trackMutate {
+ t.trackChannel(n.mutateCh)
+ }
+
+ // Mark its leaf as being mutated, if appropriate.
+ if t.trackMutate && forLeafUpdate && n.leaf != nil {
+ t.trackChannel(n.leaf.mutateCh)
+ }
+
+ // Copy the existing node. If you have set forLeafUpdate it will be
+ // safe to replace this leaf with another after you get your node for
+ // writing. You MUST replace it, because the channel associated with
+ // this leaf will be closed when this transaction is committed.
+ nc := &Node{
+ mutateCh: make(chan struct{}),
+ leaf: n.leaf,
+ }
+ if n.prefix != nil {
+ nc.prefix = make([]byte, len(n.prefix))
+ copy(nc.prefix, n.prefix)
+ }
+ if len(n.edges) != 0 {
+ nc.edges = make([]edge, len(n.edges))
+ copy(nc.edges, n.edges)
+ }
+
+ // Mark this node as writable.
+ t.writable.Add(nc, nil)
+ return nc
+}
+
+// Visit all the nodes in the tree under n, and add their mutateChannels to the transaction
+// Returns the size of the subtree visited
+func (t *Txn) trackChannelsAndCount(n *Node) int {
+ // Count only leaf nodes
+ leaves := 0
+ if n.leaf != nil {
+ leaves = 1
+ }
+ // Mark this node as being mutated.
+ if t.trackMutate {
+ t.trackChannel(n.mutateCh)
+ }
+
+ // Mark its leaf as being mutated, if appropriate.
+ if t.trackMutate && n.leaf != nil {
+ t.trackChannel(n.leaf.mutateCh)
+ }
+
+ // Recurse on the children
+ for _, e := range n.edges {
+ leaves += t.trackChannelsAndCount(e.node)
+ }
+ return leaves
+}
+
+// mergeChild is called to collapse the given node with its child. This is only
+// called when the given node is not a leaf and has a single edge.
+func (t *Txn) mergeChild(n *Node) {
+ // Mark the child node as being mutated since we are about to abandon
+ // it. We don't need to mark the leaf since we are retaining it if it
+ // is there.
+ e := n.edges[0]
+ child := e.node
+ if t.trackMutate {
+ t.trackChannel(child.mutateCh)
+ }
+
+ // Merge the nodes.
+ n.prefix = concat(n.prefix, child.prefix)
+ n.leaf = child.leaf
+ if len(child.edges) != 0 {
+ n.edges = make([]edge, len(child.edges))
+ copy(n.edges, child.edges)
+ } else {
+ n.edges = nil
+ }
+}
+
+// insert does a recursive insertion
+func (t *Txn) insert(n *Node, k, search []byte, v interface{}) (*Node, interface{}, bool) {
+ // Handle key exhaustion
+ if len(search) == 0 {
+ var oldVal interface{}
+ didUpdate := false
+ if n.isLeaf() {
+ oldVal = n.leaf.val
+ didUpdate = true
+ }
+
+ nc := t.writeNode(n, true)
+ nc.leaf = &leafNode{
+ mutateCh: make(chan struct{}),
+ key: k,
+ val: v,
+ }
+ return nc, oldVal, didUpdate
+ }
+
+ // Look for the edge
+ idx, child := n.getEdge(search[0])
+
+ // No edge, create one
+ if child == nil {
+ e := edge{
+ label: search[0],
+ node: &Node{
+ mutateCh: make(chan struct{}),
+ leaf: &leafNode{
+ mutateCh: make(chan struct{}),
+ key: k,
+ val: v,
+ },
+ prefix: search,
+ },
+ }
+ nc := t.writeNode(n, false)
+ nc.addEdge(e)
+ return nc, nil, false
+ }
+
+ // Determine longest prefix of the search key on match
+ commonPrefix := longestPrefix(search, child.prefix)
+ if commonPrefix == len(child.prefix) {
+ search = search[commonPrefix:]
+ newChild, oldVal, didUpdate := t.insert(child, k, search, v)
+ if newChild != nil {
+ nc := t.writeNode(n, false)
+ nc.edges[idx].node = newChild
+ return nc, oldVal, didUpdate
+ }
+ return nil, oldVal, didUpdate
+ }
+
+ // Split the node
+ nc := t.writeNode(n, false)
+ splitNode := &Node{
+ mutateCh: make(chan struct{}),
+ prefix: search[:commonPrefix],
+ }
+ nc.replaceEdge(edge{
+ label: search[0],
+ node: splitNode,
+ })
+
+ // Restore the existing child node
+ modChild := t.writeNode(child, false)
+ splitNode.addEdge(edge{
+ label: modChild.prefix[commonPrefix],
+ node: modChild,
+ })
+ modChild.prefix = modChild.prefix[commonPrefix:]
+
+ // Create a new leaf node
+ leaf := &leafNode{
+ mutateCh: make(chan struct{}),
+ key: k,
+ val: v,
+ }
+
+ // If the new key is a subset, add to to this node
+ search = search[commonPrefix:]
+ if len(search) == 0 {
+ splitNode.leaf = leaf
+ return nc, nil, false
+ }
+
+ // Create a new edge for the node
+ splitNode.addEdge(edge{
+ label: search[0],
+ node: &Node{
+ mutateCh: make(chan struct{}),
+ leaf: leaf,
+ prefix: search,
+ },
+ })
+ return nc, nil, false
+}
+
+// delete does a recursive deletion
+func (t *Txn) delete(parent, n *Node, search []byte) (*Node, *leafNode) {
+ // Check for key exhaustion
+ if len(search) == 0 {
+ if !n.isLeaf() {
+ return nil, nil
+ }
+ // Copy the pointer in case we are in a transaction that already
+ // modified this node since the node will be reused. Any changes
+ // made to the node will not affect returning the original leaf
+ // value.
+ oldLeaf := n.leaf
+
+ // Remove the leaf node
+ nc := t.writeNode(n, true)
+ nc.leaf = nil
+
+ // Check if this node should be merged
+ if n != t.root && len(nc.edges) == 1 {
+ t.mergeChild(nc)
+ }
+ return nc, oldLeaf
+ }
+
+ // Look for an edge
+ label := search[0]
+ idx, child := n.getEdge(label)
+ if child == nil || !bytes.HasPrefix(search, child.prefix) {
+ return nil, nil
+ }
+
+ // Consume the search prefix
+ search = search[len(child.prefix):]
+ newChild, leaf := t.delete(n, child, search)
+ if newChild == nil {
+ return nil, nil
+ }
+
+ // Copy this node. WATCH OUT - it's safe to pass "false" here because we
+ // will only ADD a leaf via nc.mergeChild() if there isn't one due to
+ // the !nc.isLeaf() check in the logic just below. This is pretty subtle,
+ // so be careful if you change any of the logic here.
+ nc := t.writeNode(n, false)
+
+ // Delete the edge if the node has no edges
+ if newChild.leaf == nil && len(newChild.edges) == 0 {
+ nc.delEdge(label)
+ if n != t.root && len(nc.edges) == 1 && !nc.isLeaf() {
+ t.mergeChild(nc)
+ }
+ } else {
+ nc.edges[idx].node = newChild
+ }
+ return nc, leaf
+}
+
+// delete does a recursive deletion
+func (t *Txn) deletePrefix(parent, n *Node, search []byte) (*Node, int) {
+ // Check for key exhaustion
+ if len(search) == 0 {
+ nc := t.writeNode(n, true)
+ if n.isLeaf() {
+ nc.leaf = nil
+ }
+ nc.edges = nil
+ return nc, t.trackChannelsAndCount(n)
+ }
+
+ // Look for an edge
+ label := search[0]
+ idx, child := n.getEdge(label)
+ // We make sure that either the child node's prefix starts with the search term, or the search term starts with the child node's prefix
+ // Need to do both so that we can delete prefixes that don't correspond to any node in the tree
+ if child == nil || (!bytes.HasPrefix(child.prefix, search) && !bytes.HasPrefix(search, child.prefix)) {
+ return nil, 0
+ }
+
+ // Consume the search prefix
+ if len(child.prefix) > len(search) {
+ search = []byte("")
+ } else {
+ search = search[len(child.prefix):]
+ }
+ newChild, numDeletions := t.deletePrefix(n, child, search)
+ if newChild == nil {
+ return nil, 0
+ }
+ // Copy this node. WATCH OUT - it's safe to pass "false" here because we
+ // will only ADD a leaf via nc.mergeChild() if there isn't one due to
+ // the !nc.isLeaf() check in the logic just below. This is pretty subtle,
+ // so be careful if you change any of the logic here.
+
+ nc := t.writeNode(n, false)
+
+ // Delete the edge if the node has no edges
+ if newChild.leaf == nil && len(newChild.edges) == 0 {
+ nc.delEdge(label)
+ if n != t.root && len(nc.edges) == 1 && !nc.isLeaf() {
+ t.mergeChild(nc)
+ }
+ } else {
+ nc.edges[idx].node = newChild
+ }
+ return nc, numDeletions
+}
+
+// Insert is used to add or update a given key. The return provides
+// the previous value and a bool indicating if any was set.
+func (t *Txn) Insert(k []byte, v interface{}) (interface{}, bool) {
+ newRoot, oldVal, didUpdate := t.insert(t.root, k, k, v)
+ if newRoot != nil {
+ t.root = newRoot
+ }
+ if !didUpdate {
+ t.size++
+ }
+ return oldVal, didUpdate
+}
+
+// Delete is used to delete a given key. Returns the old value if any,
+// and a bool indicating if the key was set.
+func (t *Txn) Delete(k []byte) (interface{}, bool) {
+ newRoot, leaf := t.delete(nil, t.root, k)
+ if newRoot != nil {
+ t.root = newRoot
+ }
+ if leaf != nil {
+ t.size--
+ return leaf.val, true
+ }
+ return nil, false
+}
+
+// DeletePrefix is used to delete an entire subtree that matches the prefix
+// This will delete all nodes under that prefix
+func (t *Txn) DeletePrefix(prefix []byte) bool {
+ newRoot, numDeletions := t.deletePrefix(nil, t.root, prefix)
+ if newRoot != nil {
+ t.root = newRoot
+ t.size = t.size - numDeletions
+ return true
+ }
+ return false
+
+}
+
+// Root returns the current root of the radix tree within this
+// transaction. The root is not safe across insert and delete operations,
+// but can be used to read the current state during a transaction.
+func (t *Txn) Root() *Node {
+ return t.root
+}
+
+// Get is used to lookup a specific key, returning
+// the value and if it was found
+func (t *Txn) Get(k []byte) (interface{}, bool) {
+ return t.root.Get(k)
+}
+
+// GetWatch is used to lookup a specific key, returning
+// the watch channel, value and if it was found
+func (t *Txn) GetWatch(k []byte) (<-chan struct{}, interface{}, bool) {
+ return t.root.GetWatch(k)
+}
+
+// Commit is used to finalize the transaction and return a new tree. If mutation
+// tracking is turned on then notifications will also be issued.
+func (t *Txn) Commit() *Tree {
+ nt := t.CommitOnly()
+ if t.trackMutate {
+ t.Notify()
+ }
+ return nt
+}
+
+// CommitOnly is used to finalize the transaction and return a new tree, but
+// does not issue any notifications until Notify is called.
+func (t *Txn) CommitOnly() *Tree {
+ nt := &Tree{t.root, t.size}
+ t.writable = nil
+ return nt
+}
+
+// slowNotify does a complete comparison of the before and after trees in order
+// to trigger notifications. This doesn't require any additional state but it
+// is very expensive to compute.
+func (t *Txn) slowNotify() {
+ snapIter := t.snap.rawIterator()
+ rootIter := t.root.rawIterator()
+ for snapIter.Front() != nil || rootIter.Front() != nil {
+ // If we've exhausted the nodes in the old snapshot, we know
+ // there's nothing remaining to notify.
+ if snapIter.Front() == nil {
+ return
+ }
+ snapElem := snapIter.Front()
+
+ // If we've exhausted the nodes in the new root, we know we need
+ // to invalidate everything that remains in the old snapshot. We
+ // know from the loop condition there's something in the old
+ // snapshot.
+ if rootIter.Front() == nil {
+ close(snapElem.mutateCh)
+ if snapElem.isLeaf() {
+ close(snapElem.leaf.mutateCh)
+ }
+ snapIter.Next()
+ continue
+ }
+
+ // Do one string compare so we can check the various conditions
+ // below without repeating the compare.
+ cmp := strings.Compare(snapIter.Path(), rootIter.Path())
+
+ // If the snapshot is behind the root, then we must have deleted
+ // this node during the transaction.
+ if cmp < 0 {
+ close(snapElem.mutateCh)
+ if snapElem.isLeaf() {
+ close(snapElem.leaf.mutateCh)
+ }
+ snapIter.Next()
+ continue
+ }
+
+ // If the snapshot is ahead of the root, then we must have added
+ // this node during the transaction.
+ if cmp > 0 {
+ rootIter.Next()
+ continue
+ }
+
+ // If we have the same path, then we need to see if we mutated a
+ // node and possibly the leaf.
+ rootElem := rootIter.Front()
+ if snapElem != rootElem {
+ close(snapElem.mutateCh)
+ if snapElem.leaf != nil && (snapElem.leaf != rootElem.leaf) {
+ close(snapElem.leaf.mutateCh)
+ }
+ }
+ snapIter.Next()
+ rootIter.Next()
+ }
+}
+
+// Notify is used along with TrackMutate to trigger notifications. This must
+// only be done once a transaction is committed via CommitOnly, and it is called
+// automatically by Commit.
+func (t *Txn) Notify() {
+ if !t.trackMutate {
+ return
+ }
+
+ // If we've overflowed the tracking state we can't use it in any way and
+ // need to do a full tree compare.
+ if t.trackOverflow {
+ t.slowNotify()
+ } else {
+ for ch := range t.trackChannels {
+ close(ch)
+ }
+ }
+
+ // Clean up the tracking state so that a re-notify is safe (will trigger
+ // the else clause above which will be a no-op).
+ t.trackChannels = nil
+ t.trackOverflow = false
+}
+
+// Insert is used to add or update a given key. The return provides
+// the new tree, previous value and a bool indicating if any was set.
+func (t *Tree) Insert(k []byte, v interface{}) (*Tree, interface{}, bool) {
+ txn := t.Txn()
+ old, ok := txn.Insert(k, v)
+ return txn.Commit(), old, ok
+}
+
+// Delete is used to delete a given key. Returns the new tree,
+// old value if any, and a bool indicating if the key was set.
+func (t *Tree) Delete(k []byte) (*Tree, interface{}, bool) {
+ txn := t.Txn()
+ old, ok := txn.Delete(k)
+ return txn.Commit(), old, ok
+}
+
+// DeletePrefix is used to delete all nodes starting with a given prefix. Returns the new tree,
+// and a bool indicating if the prefix matched any nodes
+func (t *Tree) DeletePrefix(k []byte) (*Tree, bool) {
+ txn := t.Txn()
+ ok := txn.DeletePrefix(k)
+ return txn.Commit(), ok
+}
+
+// Root returns the root node of the tree which can be used for richer
+// query operations.
+func (t *Tree) Root() *Node {
+ return t.root
+}
+
+// Get is used to lookup a specific key, returning
+// the value and if it was found
+func (t *Tree) Get(k []byte) (interface{}, bool) {
+ return t.root.Get(k)
+}
+
+// longestPrefix finds the length of the shared prefix
+// of two strings
+func longestPrefix(k1, k2 []byte) int {
+ max := len(k1)
+ if l := len(k2); l < max {
+ max = l
+ }
+ var i int
+ for i = 0; i < max; i++ {
+ if k1[i] != k2[i] {
+ break
+ }
+ }
+ return i
+}
+
+// concat two byte slices, returning a third new copy
+func concat(a, b []byte) []byte {
+ c := make([]byte, len(a)+len(b))
+ copy(c, a)
+ copy(c[len(a):], b)
+ return c
+}
diff -Naur --color b/vendor/github.com/hashicorp/go-immutable-radix/iter.go a/vendor/github.com/hashicorp/go-immutable-radix/iter.go
--- b/vendor/github.com/hashicorp/go-immutable-radix/iter.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-immutable-radix/iter.go 2022-11-15 23:06:31.552057604 +0100
@@ -0,0 +1,205 @@
+package iradix
+
+import (
+ "bytes"
+)
+
+// Iterator is used to iterate over a set of nodes
+// in pre-order
+type Iterator struct {
+ node *Node
+ stack []edges
+}
+
+// SeekPrefixWatch is used to seek the iterator to a given prefix
+// and returns the watch channel of the finest granularity
+func (i *Iterator) SeekPrefixWatch(prefix []byte) (watch <-chan struct{}) {
+ // Wipe the stack
+ i.stack = nil
+ n := i.node
+ watch = n.mutateCh
+ search := prefix
+ for {
+ // Check for key exhaustion
+ if len(search) == 0 {
+ i.node = n
+ return
+ }
+
+ // Look for an edge
+ _, n = n.getEdge(search[0])
+ if n == nil {
+ i.node = nil
+ return
+ }
+
+ // Update to the finest granularity as the search makes progress
+ watch = n.mutateCh
+
+ // Consume the search prefix
+ if bytes.HasPrefix(search, n.prefix) {
+ search = search[len(n.prefix):]
+
+ } else if bytes.HasPrefix(n.prefix, search) {
+ i.node = n
+ return
+ } else {
+ i.node = nil
+ return
+ }
+ }
+}
+
+// SeekPrefix is used to seek the iterator to a given prefix
+func (i *Iterator) SeekPrefix(prefix []byte) {
+ i.SeekPrefixWatch(prefix)
+}
+
+func (i *Iterator) recurseMin(n *Node) *Node {
+ // Traverse to the minimum child
+ if n.leaf != nil {
+ return n
+ }
+ nEdges := len(n.edges)
+ if nEdges > 1 {
+ // Add all the other edges to the stack (the min node will be added as
+ // we recurse)
+ i.stack = append(i.stack, n.edges[1:])
+ }
+ if nEdges > 0 {
+ return i.recurseMin(n.edges[0].node)
+ }
+ // Shouldn't be possible
+ return nil
+}
+
+// SeekLowerBound is used to seek the iterator to the smallest key that is
+// greater or equal to the given key. There is no watch variant as it's hard to
+// predict based on the radix structure which node(s) changes might affect the
+// result.
+func (i *Iterator) SeekLowerBound(key []byte) {
+ // Wipe the stack. Unlike Prefix iteration, we need to build the stack as we
+ // go because we need only a subset of edges of many nodes in the path to the
+ // leaf with the lower bound. Note that the iterator will still recurse into
+ // children that we don't traverse on the way to the reverse lower bound as it
+ // walks the stack.
+ i.stack = []edges{}
+ // i.node starts off in the common case as pointing to the root node of the
+ // tree. By the time we return we have either found a lower bound and setup
+ // the stack to traverse all larger keys, or we have not and the stack and
+ // node should both be nil to prevent the iterator from assuming it is just
+ // iterating the whole tree from the root node. Either way this needs to end
+ // up as nil so just set it here.
+ n := i.node
+ i.node = nil
+ search := key
+
+ found := func(n *Node) {
+ i.stack = append(i.stack, edges{edge{node: n}})
+ }
+
+ findMin := func(n *Node) {
+ n = i.recurseMin(n)
+ if n != nil {
+ found(n)
+ return
+ }
+ }
+
+ for {
+ // Compare current prefix with the search key's same-length prefix.
+ var prefixCmp int
+ if len(n.prefix) < len(search) {
+ prefixCmp = bytes.Compare(n.prefix, search[0:len(n.prefix)])
+ } else {
+ prefixCmp = bytes.Compare(n.prefix, search)
+ }
+
+ if prefixCmp > 0 {
+ // Prefix is larger, that means the lower bound is greater than the search
+ // and from now on we need to follow the minimum path to the smallest
+ // leaf under this subtree.
+ findMin(n)
+ return
+ }
+
+ if prefixCmp < 0 {
+ // Prefix is smaller than search prefix, that means there is no lower
+ // bound
+ i.node = nil
+ return
+ }
+
+ // Prefix is equal, we are still heading for an exact match. If this is a
+ // leaf and an exact match we're done.
+ if n.leaf != nil && bytes.Equal(n.leaf.key, key) {
+ found(n)
+ return
+ }
+
+ // Consume the search prefix if the current node has one. Note that this is
+ // safe because if n.prefix is longer than the search slice prefixCmp would
+ // have been > 0 above and the method would have already returned.
+ search = search[len(n.prefix):]
+
+ if len(search) == 0 {
+ // We've exhausted the search key, but the current node is not an exact
+ // match or not a leaf. That means that the leaf value if it exists, and
+ // all child nodes must be strictly greater, the smallest key in this
+ // subtree must be the lower bound.
+ findMin(n)
+ return
+ }
+
+ // Otherwise, take the lower bound next edge.
+ idx, lbNode := n.getLowerBoundEdge(search[0])
+ if lbNode == nil {
+ return
+ }
+
+ // Create stack edges for the all strictly higher edges in this node.
+ if idx+1 < len(n.edges) {
+ i.stack = append(i.stack, n.edges[idx+1:])
+ }
+
+ // Recurse
+ n = lbNode
+ }
+}
+
+// Next returns the next node in order
+func (i *Iterator) Next() ([]byte, interface{}, bool) {
+ // Initialize our stack if needed
+ if i.stack == nil && i.node != nil {
+ i.stack = []edges{
+ {
+ edge{node: i.node},
+ },
+ }
+ }
+
+ for len(i.stack) > 0 {
+ // Inspect the last element of the stack
+ n := len(i.stack)
+ last := i.stack[n-1]
+ elem := last[0].node
+
+ // Update the stack
+ if len(last) > 1 {
+ i.stack[n-1] = last[1:]
+ } else {
+ i.stack = i.stack[:n-1]
+ }
+
+ // Push the edges onto the frontier
+ if len(elem.edges) > 0 {
+ i.stack = append(i.stack, elem.edges)
+ }
+
+ // Return the leaf values if any
+ if elem.leaf != nil {
+ return elem.leaf.key, elem.leaf.val, true
+ }
+ }
+ return nil, nil, false
+}
diff -Naur --color b/vendor/github.com/hashicorp/go-immutable-radix/LICENSE a/vendor/github.com/hashicorp/go-immutable-radix/LICENSE
--- b/vendor/github.com/hashicorp/go-immutable-radix/LICENSE 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-immutable-radix/LICENSE 2022-11-15 23:06:31.552057604 +0100
@@ -0,0 +1,363 @@
+Mozilla Public License, version 2.0
+
+1. Definitions
+
+1.1. "Contributor"
+
+ means each individual or legal entity that creates, contributes to the
+ creation of, or owns Covered Software.
+
+1.2. "Contributor Version"
+
+ means the combination of the Contributions of others (if any) used by a
+ Contributor and that particular Contributor's Contribution.
+
+1.3. "Contribution"
+
+ means Covered Software of a particular Contributor.
+
+1.4. "Covered Software"
+
+ means Source Code Form to which the initial Contributor has attached the
+ notice in Exhibit A, the Executable Form of such Source Code Form, and
+ Modifications of such Source Code Form, in each case including portions
+ thereof.
+
+1.5. "Incompatible With Secondary Licenses"
+ means
+
+ a. that the initial Contributor has attached the notice described in
+ Exhibit B to the Covered Software; or
+
+ b. that the Covered Software was made available under the terms of
+ version 1.1 or earlier of the License, but not also under the terms of
+ a Secondary License.
+
+1.6. "Executable Form"
+
+ means any form of the work other than Source Code Form.
+
+1.7. "Larger Work"
+
+ means a work that combines Covered Software with other material, in a
+ separate file or files, that is not Covered Software.
+
+1.8. "License"
+
+ means this document.
+
+1.9. "Licensable"
+
+ means having the right to grant, to the maximum extent possible, whether
+ at the time of the initial grant or subsequently, any and all of the
+ rights conveyed by this License.
+
+1.10. "Modifications"
+
+ means any of the following:
+
+ a. any file in Source Code Form that results from an addition to,
+ deletion from, or modification of the contents of Covered Software; or
+
+ b. any new file in Source Code Form that contains any Covered Software.
+
+1.11. "Patent Claims" of a Contributor
+
+ means any patent claim(s), including without limitation, method,
+ process, and apparatus claims, in any patent Licensable by such
+ Contributor that would be infringed, but for the grant of the License,
+ by the making, using, selling, offering for sale, having made, import,
+ or transfer of either its Contributions or its Contributor Version.
+
+1.12. "Secondary License"
+
+ means either the GNU General Public License, Version 2.0, the GNU Lesser
+ General Public License, Version 2.1, the GNU Affero General Public
+ License, Version 3.0, or any later versions of those licenses.
+
+1.13. "Source Code Form"
+
+ means the form of the work preferred for making modifications.
+
+1.14. "You" (or "Your")
+
+ means an individual or a legal entity exercising rights under this
+ License. For legal entities, "You" includes any entity that controls, is
+ controlled by, or is under common control with You. For purposes of this
+ definition, "control" means (a) the power, direct or indirect, to cause
+ the direction or management of such entity, whether by contract or
+ otherwise, or (b) ownership of more than fifty percent (50%) of the
+ outstanding shares or beneficial ownership of such entity.
+
+
+2. License Grants and Conditions
+
+2.1. Grants
+
+ Each Contributor hereby grants You a world-wide, royalty-free,
+ non-exclusive license:
+
+ a. under intellectual property rights (other than patent or trademark)
+ Licensable by such Contributor to use, reproduce, make available,
+ modify, display, perform, distribute, and otherwise exploit its
+ Contributions, either on an unmodified basis, with Modifications, or
+ as part of a Larger Work; and
+
+ b. under Patent Claims of such Contributor to make, use, sell, offer for
+ sale, have made, import, and otherwise transfer either its
+ Contributions or its Contributor Version.
+
+2.2. Effective Date
+
+ The licenses granted in Section 2.1 with respect to any Contribution
+ become effective for each Contribution on the date the Contributor first
+ distributes such Contribution.
+
+2.3. Limitations on Grant Scope
+
+ The licenses granted in this Section 2 are the only rights granted under
+ this License. No additional rights or licenses will be implied from the
+ distribution or licensing of Covered Software under this License.
+ Notwithstanding Section 2.1(b) above, no patent license is granted by a
+ Contributor:
+
+ a. for any code that a Contributor has removed from Covered Software; or
+
+ b. for infringements caused by: (i) Your and any other third party's
+ modifications of Covered Software, or (ii) the combination of its
+ Contributions with other software (except as part of its Contributor
+ Version); or
+
+ c. under Patent Claims infringed by Covered Software in the absence of
+ its Contributions.
+
+ This License does not grant any rights in the trademarks, service marks,
+ or logos of any Contributor (except as may be necessary to comply with
+ the notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+ No Contributor makes additional grants as a result of Your choice to
+ distribute the Covered Software under a subsequent version of this
+ License (see Section 10.2) or under the terms of a Secondary License (if
+ permitted under the terms of Section 3.3).
+
+2.5. Representation
+
+ Each Contributor represents that the Contributor believes its
+ Contributions are its original creation(s) or it has sufficient rights to
+ grant the rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+ This License is not intended to limit any rights You have under
+ applicable copyright doctrines of fair use, fair dealing, or other
+ equivalents.
+
+2.7. Conditions
+
+ Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
+ Section 2.1.
+
+
+3. Responsibilities
+
+3.1. Distribution of Source Form
+
+ All distribution of Covered Software in Source Code Form, including any
+ Modifications that You create or to which You contribute, must be under
+ the terms of this License. You must inform recipients that the Source
+ Code Form of the Covered Software is governed by the terms of this
+ License, and how they can obtain a copy of this License. You may not
+ attempt to alter or restrict the recipients' rights in the Source Code
+ Form.
+
+3.2. Distribution of Executable Form
+
+ If You distribute Covered Software in Executable Form then:
+
+ a. such Covered Software must also be made available in Source Code Form,
+ as described in Section 3.1, and You must inform recipients of the
+ Executable Form how they can obtain a copy of such Source Code Form by
+ reasonable means in a timely manner, at a charge no more than the cost
+ of distribution to the recipient; and
+
+ b. You may distribute such Executable Form under the terms of this
+ License, or sublicense it under different terms, provided that the
+ license for the Executable Form does not attempt to limit or alter the
+ recipients' rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+ You may create and distribute a Larger Work under terms of Your choice,
+ provided that You also comply with the requirements of this License for
+ the Covered Software. If the Larger Work is a combination of Covered
+ Software with a work governed by one or more Secondary Licenses, and the
+ Covered Software is not Incompatible With Secondary Licenses, this
+ License permits You to additionally distribute such Covered Software
+ under the terms of such Secondary License(s), so that the recipient of
+ the Larger Work may, at their option, further distribute the Covered
+ Software under the terms of either this License or such Secondary
+ License(s).
+
+3.4. Notices
+
+ You may not remove or alter the substance of any license notices
+ (including copyright notices, patent notices, disclaimers of warranty, or
+ limitations of liability) contained within the Source Code Form of the
+ Covered Software, except that You may alter any license notices to the
+ extent required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+ You may choose to offer, and to charge a fee for, warranty, support,
+ indemnity or liability obligations to one or more recipients of Covered
+ Software. However, You may do so only on Your own behalf, and not on
+ behalf of any Contributor. You must make it absolutely clear that any
+ such warranty, support, indemnity, or liability obligation is offered by
+ You alone, and You hereby agree to indemnify every Contributor for any
+ liability incurred by such Contributor as a result of warranty, support,
+ indemnity or liability terms You offer. You may include additional
+ disclaimers of warranty and limitations of liability specific to any
+ jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+
+ If it is impossible for You to comply with any of the terms of this License
+ with respect to some or all of the Covered Software due to statute,
+ judicial order, or regulation then You must: (a) comply with the terms of
+ this License to the maximum extent possible; and (b) describe the
+ limitations and the code they affect. Such description must be placed in a
+ text file included with all distributions of the Covered Software under
+ this License. Except to the extent prohibited by statute or regulation,
+ such description must be sufficiently detailed for a recipient of ordinary
+ skill to be able to understand it.
+
+5. Termination
+
+5.1. The rights granted under this License will terminate automatically if You
+ fail to comply with any of its terms. However, if You become compliant,
+ then the rights granted under this License from a particular Contributor
+ are reinstated (a) provisionally, unless and until such Contributor
+ explicitly and finally terminates Your grants, and (b) on an ongoing
+ basis, if such Contributor fails to notify You of the non-compliance by
+ some reasonable means prior to 60 days after You have come back into
+ compliance. Moreover, Your grants from a particular Contributor are
+ reinstated on an ongoing basis if such Contributor notifies You of the
+ non-compliance by some reasonable means, this is the first time You have
+ received notice of non-compliance with this License from such
+ Contributor, and You become compliant prior to 30 days after Your receipt
+ of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+ infringement claim (excluding declaratory judgment actions,
+ counter-claims, and cross-claims) alleging that a Contributor Version
+ directly or indirectly infringes any patent, then the rights granted to
+ You by any and all Contributors for the Covered Software under Section
+ 2.1 of this License shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
+ license agreements (excluding distributors and resellers) which have been
+ validly granted by You or Your distributors under this License prior to
+ termination shall survive termination.
+
+6. Disclaimer of Warranty
+
+ Covered Software is provided under this License on an "as is" basis,
+ without warranty of any kind, either expressed, implied, or statutory,
+ including, without limitation, warranties that the Covered Software is free
+ of defects, merchantable, fit for a particular purpose or non-infringing.
+ The entire risk as to the quality and performance of the Covered Software
+ is with You. Should any Covered Software prove defective in any respect,
+ You (not any Contributor) assume the cost of any necessary servicing,
+ repair, or correction. This disclaimer of warranty constitutes an essential
+ part of this License. No use of any Covered Software is authorized under
+ this License except under this disclaimer.
+
+7. Limitation of Liability
+
+ Under no circumstances and under no legal theory, whether tort (including
+ negligence), contract, or otherwise, shall any Contributor, or anyone who
+ distributes Covered Software as permitted above, be liable to You for any
+ direct, indirect, special, incidental, or consequential damages of any
+ character including, without limitation, damages for lost profits, loss of
+ goodwill, work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses, even if such party shall have been
+ informed of the possibility of such damages. This limitation of liability
+ shall not apply to liability for death or personal injury resulting from
+ such party's negligence to the extent applicable law prohibits such
+ limitation. Some jurisdictions do not allow the exclusion or limitation of
+ incidental or consequential damages, so this exclusion and limitation may
+ not apply to You.
+
+8. Litigation
+
+ Any litigation relating to this License may be brought only in the courts
+ of a jurisdiction where the defendant maintains its principal place of
+ business and such litigation shall be governed by laws of that
+ jurisdiction, without reference to its conflict-of-law provisions. Nothing
+ in this Section shall prevent a party's ability to bring cross-claims or
+ counter-claims.
+
+9. Miscellaneous
+
+ This License represents the complete agreement concerning the subject
+ matter hereof. If any provision of this License is held to be
+ unenforceable, such provision shall be reformed only to the extent
+ necessary to make it enforceable. Any law or regulation which provides that
+ the language of a contract shall be construed against the drafter shall not
+ be used to construe this License against a Contributor.
+
+
+10. Versions of the License
+
+10.1. New Versions
+
+ Mozilla Foundation is the license steward. Except as provided in Section
+ 10.3, no one other than the license steward has the right to modify or
+ publish new versions of this License. Each version will be given a
+ distinguishing version number.
+
+10.2. Effect of New Versions
+
+ You may distribute the Covered Software under the terms of the version
+ of the License under which You originally received the Covered Software,
+ or under the terms of any subsequent version published by the license
+ steward.
+
+10.3. Modified Versions
+
+ If you create software not governed by this License, and you want to
+ create a new license for such software, you may create and use a
+ modified version of this License if you rename the license and remove
+ any references to the name of the license steward (except to note that
+ such modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary
+ Licenses If You choose to distribute Source Code Form that is
+ Incompatible With Secondary Licenses under the terms of this version of
+ the License, the notice described in Exhibit B of this License must be
+ attached.
+
+Exhibit A - Source Code Form License Notice
+
+ This Source Code Form is subject to the
+ terms of the Mozilla Public License, v.
+ 2.0. If a copy of the MPL was not
+ distributed with this file, You can
+ obtain one at
+ http://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular file,
+then You may include the notice in a location (such as a LICENSE file in a
+relevant directory) where a recipient would be likely to look for such a
+notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - "Incompatible With Secondary Licenses" Notice
+
+ This Source Code Form is "Incompatible
+ With Secondary Licenses", as defined by
+ the Mozilla Public License, v. 2.0.
+
diff -Naur --color b/vendor/github.com/hashicorp/go-immutable-radix/node.go a/vendor/github.com/hashicorp/go-immutable-radix/node.go
--- b/vendor/github.com/hashicorp/go-immutable-radix/node.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-immutable-radix/node.go 2022-11-15 23:06:31.552057604 +0100
@@ -0,0 +1,334 @@
+package iradix
+
+import (
+ "bytes"
+ "sort"
+)
+
+// WalkFn is used when walking the tree. Takes a
+// key and value, returning if iteration should
+// be terminated.
+type WalkFn func(k []byte, v interface{}) bool
+
+// leafNode is used to represent a value
+type leafNode struct {
+ mutateCh chan struct{}
+ key []byte
+ val interface{}
+}
+
+// edge is used to represent an edge node
+type edge struct {
+ label byte
+ node *Node
+}
+
+// Node is an immutable node in the radix tree
+type Node struct {
+ // mutateCh is closed if this node is modified
+ mutateCh chan struct{}
+
+ // leaf is used to store possible leaf
+ leaf *leafNode
+
+ // prefix is the common prefix we ignore
+ prefix []byte
+
+ // Edges should be stored in-order for iteration.
+ // We avoid a fully materialized slice to save memory,
+ // since in most cases we expect to be sparse
+ edges edges
+}
+
+func (n *Node) isLeaf() bool {
+ return n.leaf != nil
+}
+
+func (n *Node) addEdge(e edge) {
+ num := len(n.edges)
+ idx := sort.Search(num, func(i int) bool {
+ return n.edges[i].label >= e.label
+ })
+ n.edges = append(n.edges, e)
+ if idx != num {
+ copy(n.edges[idx+1:], n.edges[idx:num])
+ n.edges[idx] = e
+ }
+}
+
+func (n *Node) replaceEdge(e edge) {
+ num := len(n.edges)
+ idx := sort.Search(num, func(i int) bool {
+ return n.edges[i].label >= e.label
+ })
+ if idx < num && n.edges[idx].label == e.label {
+ n.edges[idx].node = e.node
+ return
+ }
+ panic("replacing missing edge")
+}
+
+func (n *Node) getEdge(label byte) (int, *Node) {
+ num := len(n.edges)
+ idx := sort.Search(num, func(i int) bool {
+ return n.edges[i].label >= label
+ })
+ if idx < num && n.edges[idx].label == label {
+ return idx, n.edges[idx].node
+ }
+ return -1, nil
+}
+
+func (n *Node) getLowerBoundEdge(label byte) (int, *Node) {
+ num := len(n.edges)
+ idx := sort.Search(num, func(i int) bool {
+ return n.edges[i].label >= label
+ })
+ // we want lower bound behavior so return even if it's not an exact match
+ if idx < num {
+ return idx, n.edges[idx].node
+ }
+ return -1, nil
+}
+
+func (n *Node) delEdge(label byte) {
+ num := len(n.edges)
+ idx := sort.Search(num, func(i int) bool {
+ return n.edges[i].label >= label
+ })
+ if idx < num && n.edges[idx].label == label {
+ copy(n.edges[idx:], n.edges[idx+1:])
+ n.edges[len(n.edges)-1] = edge{}
+ n.edges = n.edges[:len(n.edges)-1]
+ }
+}
+
+func (n *Node) GetWatch(k []byte) (<-chan struct{}, interface{}, bool) {
+ search := k
+ watch := n.mutateCh
+ for {
+ // Check for key exhaustion
+ if len(search) == 0 {
+ if n.isLeaf() {
+ return n.leaf.mutateCh, n.leaf.val, true
+ }
+ break
+ }
+
+ // Look for an edge
+ _, n = n.getEdge(search[0])
+ if n == nil {
+ break
+ }
+
+ // Update to the finest granularity as the search makes progress
+ watch = n.mutateCh
+
+ // Consume the search prefix
+ if bytes.HasPrefix(search, n.prefix) {
+ search = search[len(n.prefix):]
+ } else {
+ break
+ }
+ }
+ return watch, nil, false
+}
+
+func (n *Node) Get(k []byte) (interface{}, bool) {
+ _, val, ok := n.GetWatch(k)
+ return val, ok
+}
+
+// LongestPrefix is like Get, but instead of an
+// exact match, it will return the longest prefix match.
+func (n *Node) LongestPrefix(k []byte) ([]byte, interface{}, bool) {
+ var last *leafNode
+ search := k
+ for {
+ // Look for a leaf node
+ if n.isLeaf() {
+ last = n.leaf
+ }
+
+ // Check for key exhaution
+ if len(search) == 0 {
+ break
+ }
+
+ // Look for an edge
+ _, n = n.getEdge(search[0])
+ if n == nil {
+ break
+ }
+
+ // Consume the search prefix
+ if bytes.HasPrefix(search, n.prefix) {
+ search = search[len(n.prefix):]
+ } else {
+ break
+ }
+ }
+ if last != nil {
+ return last.key, last.val, true
+ }
+ return nil, nil, false
+}
+
+// Minimum is used to return the minimum value in the tree
+func (n *Node) Minimum() ([]byte, interface{}, bool) {
+ for {
+ if n.isLeaf() {
+ return n.leaf.key, n.leaf.val, true
+ }
+ if len(n.edges) > 0 {
+ n = n.edges[0].node
+ } else {
+ break
+ }
+ }
+ return nil, nil, false
+}
+
+// Maximum is used to return the maximum value in the tree
+func (n *Node) Maximum() ([]byte, interface{}, bool) {
+ for {
+ if num := len(n.edges); num > 0 {
+ n = n.edges[num-1].node
+ continue
+ }
+ if n.isLeaf() {
+ return n.leaf.key, n.leaf.val, true
+ } else {
+ break
+ }
+ }
+ return nil, nil, false
+}
+
+// Iterator is used to return an iterator at
+// the given node to walk the tree
+func (n *Node) Iterator() *Iterator {
+ return &Iterator{node: n}
+}
+
+// ReverseIterator is used to return an iterator at
+// the given node to walk the tree backwards
+func (n *Node) ReverseIterator() *ReverseIterator {
+ return NewReverseIterator(n)
+}
+
+// rawIterator is used to return a raw iterator at the given node to walk the
+// tree.
+func (n *Node) rawIterator() *rawIterator {
+ iter := &rawIterator{node: n}
+ iter.Next()
+ return iter
+}
+
+// Walk is used to walk the tree
+func (n *Node) Walk(fn WalkFn) {
+ recursiveWalk(n, fn)
+}
+
+// WalkBackwards is used to walk the tree in reverse order
+func (n *Node) WalkBackwards(fn WalkFn) {
+ reverseRecursiveWalk(n, fn)
+}
+
+// WalkPrefix is used to walk the tree under a prefix
+func (n *Node) WalkPrefix(prefix []byte, fn WalkFn) {
+ search := prefix
+ for {
+ // Check for key exhaution
+ if len(search) == 0 {
+ recursiveWalk(n, fn)
+ return
+ }
+
+ // Look for an edge
+ _, n = n.getEdge(search[0])
+ if n == nil {
+ break
+ }
+
+ // Consume the search prefix
+ if bytes.HasPrefix(search, n.prefix) {
+ search = search[len(n.prefix):]
+
+ } else if bytes.HasPrefix(n.prefix, search) {
+ // Child may be under our search prefix
+ recursiveWalk(n, fn)
+ return
+ } else {
+ break
+ }
+ }
+}
+
+// WalkPath is used to walk the tree, but only visiting nodes
+// from the root down to a given leaf. Where WalkPrefix walks
+// all the entries *under* the given prefix, this walks the
+// entries *above* the given prefix.
+func (n *Node) WalkPath(path []byte, fn WalkFn) {
+ search := path
+ for {
+ // Visit the leaf values if any
+ if n.leaf != nil && fn(n.leaf.key, n.leaf.val) {
+ return
+ }
+
+ // Check for key exhaution
+ if len(search) == 0 {
+ return
+ }
+
+ // Look for an edge
+ _, n = n.getEdge(search[0])
+ if n == nil {
+ return
+ }
+
+ // Consume the search prefix
+ if bytes.HasPrefix(search, n.prefix) {
+ search = search[len(n.prefix):]
+ } else {
+ break
+ }
+ }
+}
+
+// recursiveWalk is used to do a pre-order walk of a node
+// recursively. Returns true if the walk should be aborted
+func recursiveWalk(n *Node, fn WalkFn) bool {
+ // Visit the leaf values if any
+ if n.leaf != nil && fn(n.leaf.key, n.leaf.val) {
+ return true
+ }
+
+ // Recurse on the children
+ for _, e := range n.edges {
+ if recursiveWalk(e.node, fn) {
+ return true
+ }
+ }
+ return false
+}
+
+// reverseRecursiveWalk is used to do a reverse pre-order
+// walk of a node recursively. Returns true if the walk
+// should be aborted
+func reverseRecursiveWalk(n *Node, fn WalkFn) bool {
+ // Visit the leaf values if any
+ if n.leaf != nil && fn(n.leaf.key, n.leaf.val) {
+ return true
+ }
+
+ // Recurse on the children in reverse order
+ for i := len(n.edges) - 1; i >= 0; i-- {
+ e := n.edges[i]
+ if reverseRecursiveWalk(e.node, fn) {
+ return true
+ }
+ }
+ return false
+}
diff -Naur --color b/vendor/github.com/hashicorp/go-immutable-radix/raw_iter.go a/vendor/github.com/hashicorp/go-immutable-radix/raw_iter.go
--- b/vendor/github.com/hashicorp/go-immutable-radix/raw_iter.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-immutable-radix/raw_iter.go 2022-11-15 23:06:31.552057604 +0100
@@ -0,0 +1,78 @@
+package iradix
+
+// rawIterator visits each of the nodes in the tree, even the ones that are not
+// leaves. It keeps track of the effective path (what a leaf at a given node
+// would be called), which is useful for comparing trees.
+type rawIterator struct {
+ // node is the starting node in the tree for the iterator.
+ node *Node
+
+ // stack keeps track of edges in the frontier.
+ stack []rawStackEntry
+
+ // pos is the current position of the iterator.
+ pos *Node
+
+ // path is the effective path of the current iterator position,
+ // regardless of whether the current node is a leaf.
+ path string
+}
+
+// rawStackEntry is used to keep track of the cumulative common path as well as
+// its associated edges in the frontier.
+type rawStackEntry struct {
+ path string
+ edges edges
+}
+
+// Front returns the current node that has been iterated to.
+func (i *rawIterator) Front() *Node {
+ return i.pos
+}
+
+// Path returns the effective path of the current node, even if it's not actually
+// a leaf.
+func (i *rawIterator) Path() string {
+ return i.path
+}
+
+// Next advances the iterator to the next node.
+func (i *rawIterator) Next() {
+ // Initialize our stack if needed.
+ if i.stack == nil && i.node != nil {
+ i.stack = []rawStackEntry{
+ {
+ edges: edges{
+ edge{node: i.node},
+ },
+ },
+ }
+ }
+
+ for len(i.stack) > 0 {
+ // Inspect the last element of the stack.
+ n := len(i.stack)
+ last := i.stack[n-1]
+ elem := last.edges[0].node
+
+ // Update the stack.
+ if len(last.edges) > 1 {
+ i.stack[n-1].edges = last.edges[1:]
+ } else {
+ i.stack = i.stack[:n-1]
+ }
+
+ // Push the edges onto the frontier.
+ if len(elem.edges) > 0 {
+ path := last.path + string(elem.prefix)
+ i.stack = append(i.stack, rawStackEntry{path, elem.edges})
+ }
+
+ i.pos = elem
+ i.path = last.path + string(elem.prefix)
+ return
+ }
+
+ i.pos = nil
+ i.path = ""
+}
diff -Naur --color b/vendor/github.com/hashicorp/go-immutable-radix/README.md a/vendor/github.com/hashicorp/go-immutable-radix/README.md
--- b/vendor/github.com/hashicorp/go-immutable-radix/README.md 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-immutable-radix/README.md 2022-11-15 23:06:31.552057604 +0100
@@ -0,0 +1,66 @@
+go-immutable-radix [![CircleCI](https://circleci.com/gh/hashicorp/go-immutable-radix/tree/master.svg?style=svg)](https://circleci.com/gh/hashicorp/go-immutable-radix/tree/master)
+=========
+
+Provides the `iradix` package that implements an immutable [radix tree](http://en.wikipedia.org/wiki/Radix_tree).
+The package only provides a single `Tree` implementation, optimized for sparse nodes.
+
+As a radix tree, it provides the following:
+ * O(k) operations. In many cases, this can be faster than a hash table since
+ the hash function is an O(k) operation, and hash tables have very poor cache locality.
+ * Minimum / Maximum value lookups
+ * Ordered iteration
+
+A tree supports using a transaction to batch multiple updates (insert, delete)
+in a more efficient manner than performing each operation one at a time.
+
+For a mutable variant, see [go-radix](https://github.com/armon/go-radix).
+
+Documentation
+=============
+
+The full documentation is available on [Godoc](http://godoc.org/github.com/hashicorp/go-immutable-radix).
+
+Example
+=======
+
+Below is a simple example of usage
+
+```go
+// Create a tree
+r := iradix.New()
+r, _, _ = r.Insert([]byte("foo"), 1)
+r, _, _ = r.Insert([]byte("bar"), 2)
+r, _, _ = r.Insert([]byte("foobar"), 2)
+
+// Find the longest prefix match
+m, _, _ := r.Root().LongestPrefix([]byte("foozip"))
+if string(m) != "foo" {
+ panic("should be foo")
+}
+```
+
+Here is an example of performing a range scan of the keys.
+
+```go
+// Create a tree
+r := iradix.New()
+r, _, _ = r.Insert([]byte("001"), 1)
+r, _, _ = r.Insert([]byte("002"), 2)
+r, _, _ = r.Insert([]byte("005"), 5)
+r, _, _ = r.Insert([]byte("010"), 10)
+r, _, _ = r.Insert([]byte("100"), 10)
+
+// Range scan over the keys that sort lexicographically between [003, 050)
+it := r.Root().Iterator()
+it.SeekLowerBound([]byte("003"))
+for key, _, ok := it.Next(); ok; key, _, ok = it.Next() {
+ if key >= "050" {
+ break
+ }
+ fmt.Println(key)
+}
+// Output:
+// 005
+// 010
+```
+
diff -Naur --color b/vendor/github.com/hashicorp/go-immutable-radix/reverse_iter.go a/vendor/github.com/hashicorp/go-immutable-radix/reverse_iter.go
--- b/vendor/github.com/hashicorp/go-immutable-radix/reverse_iter.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-immutable-radix/reverse_iter.go 2022-11-15 23:06:31.552057604 +0100
@@ -0,0 +1,239 @@
+package iradix
+
+import (
+ "bytes"
+)
+
+// ReverseIterator is used to iterate over a set of nodes
+// in reverse in-order
+type ReverseIterator struct {
+ i *Iterator
+
+ // expandedParents stores the set of parent nodes whose relevant children have
+ // already been pushed into the stack. This can happen during seek or during
+ // iteration.
+ //
+ // Unlike forward iteration we need to recurse into children before we can
+ // output the value stored in an internal leaf since all children are greater.
+ // We use this to track whether we have already ensured all the children are
+ // in the stack.
+ expandedParents map[*Node]struct{}
+}
+
+// NewReverseIterator returns a new ReverseIterator at a node
+func NewReverseIterator(n *Node) *ReverseIterator {
+ return &ReverseIterator{
+ i: &Iterator{node: n},
+ }
+}
+
+// SeekPrefixWatch is used to seek the iterator to a given prefix
+// and returns the watch channel of the finest granularity
+func (ri *ReverseIterator) SeekPrefixWatch(prefix []byte) (watch <-chan struct{}) {
+ return ri.i.SeekPrefixWatch(prefix)
+}
+
+// SeekPrefix is used to seek the iterator to a given prefix
+func (ri *ReverseIterator) SeekPrefix(prefix []byte) {
+ ri.i.SeekPrefixWatch(prefix)
+}
+
+// SeekReverseLowerBound is used to seek the iterator to the largest key that is
+// lower or equal to the given key. There is no watch variant as it's hard to
+// predict based on the radix structure which node(s) changes might affect the
+// result.
+func (ri *ReverseIterator) SeekReverseLowerBound(key []byte) {
+ // Wipe the stack. Unlike Prefix iteration, we need to build the stack as we
+ // go because we need only a subset of edges of many nodes in the path to the
+ // leaf with the lower bound. Note that the iterator will still recurse into
+ // children that we don't traverse on the way to the reverse lower bound as it
+ // walks the stack.
+ ri.i.stack = []edges{}
+ // ri.i.node starts off in the common case as pointing to the root node of the
+ // tree. By the time we return we have either found a lower bound and setup
+ // the stack to traverse all larger keys, or we have not and the stack and
+ // node should both be nil to prevent the iterator from assuming it is just
+ // iterating the whole tree from the root node. Either way this needs to end
+ // up as nil so just set it here.
+ n := ri.i.node
+ ri.i.node = nil
+ search := key
+
+ if ri.expandedParents == nil {
+ ri.expandedParents = make(map[*Node]struct{})
+ }
+
+ found := func(n *Node) {
+ ri.i.stack = append(ri.i.stack, edges{edge{node: n}})
+ // We need to mark this node as expanded in advance too otherwise the
+ // iterator will attempt to walk all of its children even though they are
+ // greater than the lower bound we have found. We've expanded it in the
+ // sense that all of its children that we want to walk are already in the
+ // stack (i.e. none of them).
+ ri.expandedParents[n] = struct{}{}
+ }
+
+ for {
+ // Compare current prefix with the search key's same-length prefix.
+ var prefixCmp int
+ if len(n.prefix) < len(search) {
+ prefixCmp = bytes.Compare(n.prefix, search[0:len(n.prefix)])
+ } else {
+ prefixCmp = bytes.Compare(n.prefix, search)
+ }
+
+ if prefixCmp < 0 {
+ // Prefix is smaller than search prefix, that means there is no exact
+ // match for the search key. But we are looking in reverse, so the reverse
+ // lower bound will be the largest leaf under this subtree, since it is
+ // the value that would come right before the current search key if it
+ // were in the tree. So we need to follow the maximum path in this subtree
+ // to find it. Note that this is exactly what the iterator will already do
+ // if it finds a node in the stack that has _not_ been marked as expanded
+ // so in this one case we don't call `found` and instead let the iterator
+ // do the expansion and recursion through all the children.
+ ri.i.stack = append(ri.i.stack, edges{edge{node: n}})
+ return
+ }
+
+ if prefixCmp > 0 {
+ // Prefix is larger than search prefix, or there is no prefix but we've
+ // also exhausted the search key. Either way, that means there is no
+ // reverse lower bound since nothing comes before our current search
+ // prefix.
+ return
+ }
+
+ // If this is a leaf, something needs to happen! Note that if it's a leaf
+ // and prefixCmp was zero (which it must be to get here) then the leaf value
+ // is either an exact match for the search, or it's lower. It can't be
+ // greater.
+ if n.isLeaf() {
+
+ // Firstly, if it's an exact match, we're done!
+ if bytes.Equal(n.leaf.key, key) {
+ found(n)
+ return
+ }
+
+ // It's not so this node's leaf value must be lower and could still be a
+ // valid contender for reverse lower bound.
+
+ // If it has no children then we are also done.
+ if len(n.edges) == 0 {
+ // This leaf is the lower bound.
+ found(n)
+ return
+ }
+
+ // Finally, this leaf is internal (has children) so we'll keep searching,
+ // but we need to add it to the iterator's stack since it has a leaf value
+ // that needs to be iterated over. It needs to be added to the stack
+ // before its children below as it comes first.
+ ri.i.stack = append(ri.i.stack, edges{edge{node: n}})
+ // We also need to mark it as expanded since we'll be adding any of its
+ // relevant children below and so don't want the iterator to re-add them
+ // on its way back up the stack.
+ ri.expandedParents[n] = struct{}{}
+ }
+
+ // Consume the search prefix. Note that this is safe because if n.prefix is
+ // longer than the search slice prefixCmp would have been > 0 above and the
+ // method would have already returned.
+ search = search[len(n.prefix):]
+
+ if len(search) == 0 {
+ // We've exhausted the search key but we are not at a leaf. That means all
+ // children are greater than the search key so a reverse lower bound
+ // doesn't exist in this subtree. Note that there might still be one in
+ // the whole radix tree by following a different path somewhere further
+ // up. If that's the case then the iterator's stack will contain all the
+ // smaller nodes already and Previous will walk through them correctly.
+ return
+ }
+
+ // Otherwise, take the lower bound next edge.
+ idx, lbNode := n.getLowerBoundEdge(search[0])
+
+ // From here, we need to update the stack with all values lower than
+ // the lower bound edge. Since getLowerBoundEdge() returns -1 when the
+ // search prefix is larger than all edges, we need to place idx at the
+ // last edge index so they can all be place in the stack, since they
+ // come before our search prefix.
+ if idx == -1 {
+ idx = len(n.edges)
+ }
+
+ // Create stack edges for the all strictly lower edges in this node.
+ if len(n.edges[:idx]) > 0 {
+ ri.i.stack = append(ri.i.stack, n.edges[:idx])
+ }
+
+ // Exit if there's no lower bound edge. The stack will have the previous
+ // nodes already.
+ if lbNode == nil {
+ return
+ }
+
+ // Recurse
+ n = lbNode
+ }
+}
+
+// Previous returns the previous node in reverse order
+func (ri *ReverseIterator) Previous() ([]byte, interface{}, bool) {
+ // Initialize our stack if needed
+ if ri.i.stack == nil && ri.i.node != nil {
+ ri.i.stack = []edges{
+ {
+ edge{node: ri.i.node},
+ },
+ }
+ }
+
+ if ri.expandedParents == nil {
+ ri.expandedParents = make(map[*Node]struct{})
+ }
+
+ for len(ri.i.stack) > 0 {
+ // Inspect the last element of the stack
+ n := len(ri.i.stack)
+ last := ri.i.stack[n-1]
+ m := len(last)
+ elem := last[m-1].node
+
+ _, alreadyExpanded := ri.expandedParents[elem]
+
+ // If this is an internal node and we've not seen it already, we need to
+ // leave it in the stack so we can return its possible leaf value _after_
+ // we've recursed through all its children.
+ if len(elem.edges) > 0 && !alreadyExpanded {
+ // record that we've seen this node!
+ ri.expandedParents[elem] = struct{}{}
+ // push child edges onto stack and skip the rest of the loop to recurse
+ // into the largest one.
+ ri.i.stack = append(ri.i.stack, elem.edges)
+ continue
+ }
+
+ // Remove the node from the stack
+ if m > 1 {
+ ri.i.stack[n-1] = last[:m-1]
+ } else {
+ ri.i.stack = ri.i.stack[:n-1]
+ }
+ // We don't need this state any more as it's no longer in the stack so we
+ // won't visit it again
+ if alreadyExpanded {
+ delete(ri.expandedParents, elem)
+ }
+
+ // If this is a leaf, return it
+ if elem.leaf != nil {
+ return elem.leaf.key, elem.leaf.val, true
+ }
+
+ // it's not a leaf so keep walking the stack to find the previous leaf
+ }
+ return nil, nil, false
+}
diff -Naur --color b/vendor/github.com/hashicorp/go-msgpack/codec/0doc.go a/vendor/github.com/hashicorp/go-msgpack/codec/0doc.go
--- b/vendor/github.com/hashicorp/go-msgpack/codec/0doc.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-msgpack/codec/0doc.go 2022-11-15 23:06:31.555391002 +0100
@@ -0,0 +1,143 @@
+// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved.
+// Use of this source code is governed by a BSD-style license found in the LICENSE file.
+
+/*
+High Performance, Feature-Rich Idiomatic Go encoding library for msgpack and binc .
+
+Supported Serialization formats are:
+
+ - msgpack: [https://github.com/msgpack/msgpack]
+ - binc: [http://github.com/ugorji/binc]
+
+To install:
+
+ go get github.com/ugorji/go/codec
+
+The idiomatic Go support is as seen in other encoding packages in
+the standard library (ie json, xml, gob, etc).
+
+Rich Feature Set includes:
+
+ - Simple but extremely powerful and feature-rich API
+ - Very High Performance.
+ Our extensive benchmarks show us outperforming Gob, Json and Bson by 2-4X.
+ This was achieved by taking extreme care on:
+ - managing allocation
+ - function frame size (important due to Go's use of split stacks),
+ - reflection use (and by-passing reflection for common types)
+ - recursion implications
+ - zero-copy mode (encoding/decoding to byte slice without using temp buffers)
+ - Correct.
+ Care was taken to precisely handle corner cases like:
+ overflows, nil maps and slices, nil value in stream, etc.
+ - Efficient zero-copying into temporary byte buffers
+ when encoding into or decoding from a byte slice.
+ - Standard field renaming via tags
+ - Encoding from any value
+ (struct, slice, map, primitives, pointers, interface{}, etc)
+ - Decoding into pointer to any non-nil typed value
+ (struct, slice, map, int, float32, bool, string, reflect.Value, etc)
+ - Supports extension functions to handle the encode/decode of custom types
+ - Support Go 1.2 encoding.BinaryMarshaler/BinaryUnmarshaler
+ - Schema-less decoding
+ (decode into a pointer to a nil interface{} as opposed to a typed non-nil value).
+ Includes Options to configure what specific map or slice type to use
+ when decoding an encoded list or map into a nil interface{}
+ - Provides a RPC Server and Client Codec for net/rpc communication protocol.
+ - Msgpack Specific:
+ - Provides extension functions to handle spec-defined extensions (binary, timestamp)
+ - Options to resolve ambiguities in handling raw bytes (as string or []byte)
+ during schema-less decoding (decoding into a nil interface{})
+ - RPC Server/Client Codec for msgpack-rpc protocol defined at:
+ https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md
+ - Fast Paths for some container types:
+ For some container types, we circumvent reflection and its associated overhead
+ and allocation costs, and encode/decode directly. These types are:
+ []interface{}
+ []int
+ []string
+ map[interface{}]interface{}
+ map[int]interface{}
+ map[string]interface{}
+
+Extension Support
+
+Users can register a function to handle the encoding or decoding of
+their custom types.
+
+There are no restrictions on what the custom type can be. Some examples:
+
+ type BisSet []int
+ type BitSet64 uint64
+ type UUID string
+ type MyStructWithUnexportedFields struct { a int; b bool; c []int; }
+ type GifImage struct { ... }
+
+As an illustration, MyStructWithUnexportedFields would normally be
+encoded as an empty map because it has no exported fields, while UUID
+would be encoded as a string. However, with extension support, you can
+encode any of these however you like.
+
+RPC
+
+RPC Client and Server Codecs are implemented, so the codecs can be used
+with the standard net/rpc package.
+
+Usage
+
+Typical usage model:
+
+ // create and configure Handle
+ var (
+ bh codec.BincHandle
+ mh codec.MsgpackHandle
+ )
+
+ mh.MapType = reflect.TypeOf(map[string]interface{}(nil))
+
+ // configure extensions
+ // e.g. for msgpack, define functions and enable Time support for tag 1
+ // mh.AddExt(reflect.TypeOf(time.Time{}), 1, myMsgpackTimeEncodeExtFn, myMsgpackTimeDecodeExtFn)
+
+ // create and use decoder/encoder
+ var (
+ r io.Reader
+ w io.Writer
+ b []byte
+ h = &bh // or mh to use msgpack
+ )
+
+ dec = codec.NewDecoder(r, h)
+ dec = codec.NewDecoderBytes(b, h)
+ err = dec.Decode(&v)
+
+ enc = codec.NewEncoder(w, h)
+ enc = codec.NewEncoderBytes(&b, h)
+ err = enc.Encode(v)
+
+ //RPC Server
+ go func() {
+ for {
+ conn, err := listener.Accept()
+ rpcCodec := codec.GoRpc.ServerCodec(conn, h)
+ //OR rpcCodec := codec.MsgpackSpecRpc.ServerCodec(conn, h)
+ rpc.ServeCodec(rpcCodec)
+ }
+ }()
+
+ //RPC Communication (client side)
+ conn, err = net.Dial("tcp", "localhost:5555")
+ rpcCodec := codec.GoRpc.ClientCodec(conn, h)
+ //OR rpcCodec := codec.MsgpackSpecRpc.ClientCodec(conn, h)
+ client := rpc.NewClientWithCodec(rpcCodec)
+
+Representative Benchmark Results
+
+Run the benchmark suite using:
+ go test -bi -bench=. -benchmem
+
+To run full benchmark suite (including against vmsgpack and bson),
+see notes in ext_dep_test.go
+
+*/
+package codec
diff -Naur --color b/vendor/github.com/hashicorp/go-msgpack/codec/binc.go a/vendor/github.com/hashicorp/go-msgpack/codec/binc.go
--- b/vendor/github.com/hashicorp/go-msgpack/codec/binc.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-msgpack/codec/binc.go 2022-11-15 23:06:31.555391002 +0100
@@ -0,0 +1,786 @@
+// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved.
+// Use of this source code is governed by a BSD-style license found in the LICENSE file.
+
+package codec
+
+import (
+ "math"
+ // "reflect"
+ // "sync/atomic"
+ "time"
+ //"fmt"
+)
+
+const bincDoPrune = true // No longer needed. Needed before as C lib did not support pruning.
+
+//var _ = fmt.Printf
+
+// vd as low 4 bits (there are 16 slots)
+const (
+ bincVdSpecial byte = iota
+ bincVdPosInt
+ bincVdNegInt
+ bincVdFloat
+
+ bincVdString
+ bincVdByteArray
+ bincVdArray
+ bincVdMap
+
+ bincVdTimestamp
+ bincVdSmallInt
+ bincVdUnicodeOther
+ bincVdSymbol
+
+ bincVdDecimal
+ _ // open slot
+ _ // open slot
+ bincVdCustomExt = 0x0f
+)
+
+const (
+ bincSpNil byte = iota
+ bincSpFalse
+ bincSpTrue
+ bincSpNan
+ bincSpPosInf
+ bincSpNegInf
+ bincSpZeroFloat
+ bincSpZero
+ bincSpNegOne
+)
+
+const (
+ bincFlBin16 byte = iota
+ bincFlBin32
+ _ // bincFlBin32e
+ bincFlBin64
+ _ // bincFlBin64e
+ // others not currently supported
+)
+
+type bincEncDriver struct {
+ w encWriter
+ m map[string]uint16 // symbols
+ s uint32 // symbols sequencer
+ b [8]byte
+}
+
+func (e *bincEncDriver) isBuiltinType(rt uintptr) bool {
+ return rt == timeTypId
+}
+
+func (e *bincEncDriver) encodeBuiltin(rt uintptr, v interface{}) {
+ switch rt {
+ case timeTypId:
+ bs := encodeTime(v.(time.Time))
+ e.w.writen1(bincVdTimestamp<<4 | uint8(len(bs)))
+ e.w.writeb(bs)
+ }
+}
+
+func (e *bincEncDriver) encodeNil() {
+ e.w.writen1(bincVdSpecial<<4 | bincSpNil)
+}
+
+func (e *bincEncDriver) encodeBool(b bool) {
+ if b {
+ e.w.writen1(bincVdSpecial<<4 | bincSpTrue)
+ } else {
+ e.w.writen1(bincVdSpecial<<4 | bincSpFalse)
+ }
+}
+
+func (e *bincEncDriver) encodeFloat32(f float32) {
+ if f == 0 {
+ e.w.writen1(bincVdSpecial<<4 | bincSpZeroFloat)
+ return
+ }
+ e.w.writen1(bincVdFloat<<4 | bincFlBin32)
+ e.w.writeUint32(math.Float32bits(f))
+}
+
+func (e *bincEncDriver) encodeFloat64(f float64) {
+ if f == 0 {
+ e.w.writen1(bincVdSpecial<<4 | bincSpZeroFloat)
+ return
+ }
+ bigen.PutUint64(e.b[:], math.Float64bits(f))
+ if bincDoPrune {
+ i := 7
+ for ; i >= 0 && (e.b[i] == 0); i-- {
+ }
+ i++
+ if i <= 6 {
+ e.w.writen1(bincVdFloat<<4 | 0x8 | bincFlBin64)
+ e.w.writen1(byte(i))
+ e.w.writeb(e.b[:i])
+ return
+ }
+ }
+ e.w.writen1(bincVdFloat<<4 | bincFlBin64)
+ e.w.writeb(e.b[:])
+}
+
+func (e *bincEncDriver) encIntegerPrune(bd byte, pos bool, v uint64, lim uint8) {
+ if lim == 4 {
+ bigen.PutUint32(e.b[:lim], uint32(v))
+ } else {
+ bigen.PutUint64(e.b[:lim], v)
+ }
+ if bincDoPrune {
+ i := pruneSignExt(e.b[:lim], pos)
+ e.w.writen1(bd | lim - 1 - byte(i))
+ e.w.writeb(e.b[i:lim])
+ } else {
+ e.w.writen1(bd | lim - 1)
+ e.w.writeb(e.b[:lim])
+ }
+}
+
+func (e *bincEncDriver) encodeInt(v int64) {
+ const nbd byte = bincVdNegInt << 4
+ switch {
+ case v >= 0:
+ e.encUint(bincVdPosInt<<4, true, uint64(v))
+ case v == -1:
+ e.w.writen1(bincVdSpecial<<4 | bincSpNegOne)
+ default:
+ e.encUint(bincVdNegInt<<4, false, uint64(-v))
+ }
+}
+
+func (e *bincEncDriver) encodeUint(v uint64) {
+ e.encUint(bincVdPosInt<<4, true, v)
+}
+
+func (e *bincEncDriver) encUint(bd byte, pos bool, v uint64) {
+ switch {
+ case v == 0:
+ e.w.writen1(bincVdSpecial<<4 | bincSpZero)
+ case pos && v >= 1 && v <= 16:
+ e.w.writen1(bincVdSmallInt<<4 | byte(v-1))
+ case v <= math.MaxUint8:
+ e.w.writen2(bd|0x0, byte(v))
+ case v <= math.MaxUint16:
+ e.w.writen1(bd | 0x01)
+ e.w.writeUint16(uint16(v))
+ case v <= math.MaxUint32:
+ e.encIntegerPrune(bd, pos, v, 4)
+ default:
+ e.encIntegerPrune(bd, pos, v, 8)
+ }
+}
+
+func (e *bincEncDriver) encodeExtPreamble(xtag byte, length int) {
+ e.encLen(bincVdCustomExt<<4, uint64(length))
+ e.w.writen1(xtag)
+}
+
+func (e *bincEncDriver) encodeArrayPreamble(length int) {
+ e.encLen(bincVdArray<<4, uint64(length))
+}
+
+func (e *bincEncDriver) encodeMapPreamble(length int) {
+ e.encLen(bincVdMap<<4, uint64(length))
+}
+
+func (e *bincEncDriver) encodeString(c charEncoding, v string) {
+ l := uint64(len(v))
+ e.encBytesLen(c, l)
+ if l > 0 {
+ e.w.writestr(v)
+ }
+}
+
+func (e *bincEncDriver) encodeSymbol(v string) {
+ // if WriteSymbolsNoRefs {
+ // e.encodeString(c_UTF8, v)
+ // return
+ // }
+
+ //symbols only offer benefit when string length > 1.
+ //This is because strings with length 1 take only 2 bytes to store
+ //(bd with embedded length, and single byte for string val).
+
+ l := len(v)
+ switch l {
+ case 0:
+ e.encBytesLen(c_UTF8, 0)
+ return
+ case 1:
+ e.encBytesLen(c_UTF8, 1)
+ e.w.writen1(v[0])
+ return
+ }
+ if e.m == nil {
+ e.m = make(map[string]uint16, 16)
+ }
+ ui, ok := e.m[v]
+ if ok {
+ if ui <= math.MaxUint8 {
+ e.w.writen2(bincVdSymbol<<4, byte(ui))
+ } else {
+ e.w.writen1(bincVdSymbol<<4 | 0x8)
+ e.w.writeUint16(ui)
+ }
+ } else {
+ e.s++
+ ui = uint16(e.s)
+ //ui = uint16(atomic.AddUint32(&e.s, 1))
+ e.m[v] = ui
+ var lenprec uint8
+ switch {
+ case l <= math.MaxUint8:
+ // lenprec = 0
+ case l <= math.MaxUint16:
+ lenprec = 1
+ case int64(l) <= math.MaxUint32:
+ lenprec = 2
+ default:
+ lenprec = 3
+ }
+ if ui <= math.MaxUint8 {
+ e.w.writen2(bincVdSymbol<<4|0x0|0x4|lenprec, byte(ui))
+ } else {
+ e.w.writen1(bincVdSymbol<<4 | 0x8 | 0x4 | lenprec)
+ e.w.writeUint16(ui)
+ }
+ switch lenprec {
+ case 0:
+ e.w.writen1(byte(l))
+ case 1:
+ e.w.writeUint16(uint16(l))
+ case 2:
+ e.w.writeUint32(uint32(l))
+ default:
+ e.w.writeUint64(uint64(l))
+ }
+ e.w.writestr(v)
+ }
+}
+
+func (e *bincEncDriver) encodeStringBytes(c charEncoding, v []byte) {
+ l := uint64(len(v))
+ e.encBytesLen(c, l)
+ if l > 0 {
+ e.w.writeb(v)
+ }
+}
+
+func (e *bincEncDriver) encBytesLen(c charEncoding, length uint64) {
+ //TODO: support bincUnicodeOther (for now, just use string or bytearray)
+ if c == c_RAW {
+ e.encLen(bincVdByteArray<<4, length)
+ } else {
+ e.encLen(bincVdString<<4, length)
+ }
+}
+
+func (e *bincEncDriver) encLen(bd byte, l uint64) {
+ if l < 12 {
+ e.w.writen1(bd | uint8(l+4))
+ } else {
+ e.encLenNumber(bd, l)
+ }
+}
+
+func (e *bincEncDriver) encLenNumber(bd byte, v uint64) {
+ switch {
+ case v <= math.MaxUint8:
+ e.w.writen2(bd, byte(v))
+ case v <= math.MaxUint16:
+ e.w.writen1(bd | 0x01)
+ e.w.writeUint16(uint16(v))
+ case v <= math.MaxUint32:
+ e.w.writen1(bd | 0x02)
+ e.w.writeUint32(uint32(v))
+ default:
+ e.w.writen1(bd | 0x03)
+ e.w.writeUint64(uint64(v))
+ }
+}
+
+//------------------------------------
+
+type bincDecDriver struct {
+ r decReader
+ bdRead bool
+ bdType valueType
+ bd byte
+ vd byte
+ vs byte
+ b [8]byte
+ m map[uint32]string // symbols (use uint32 as key, as map optimizes for it)
+}
+
+func (d *bincDecDriver) initReadNext() {
+ if d.bdRead {
+ return
+ }
+ d.bd = d.r.readn1()
+ d.vd = d.bd >> 4
+ d.vs = d.bd & 0x0f
+ d.bdRead = true
+ d.bdType = valueTypeUnset
+}
+
+func (d *bincDecDriver) currentEncodedType() valueType {
+ if d.bdType == valueTypeUnset {
+ switch d.vd {
+ case bincVdSpecial:
+ switch d.vs {
+ case bincSpNil:
+ d.bdType = valueTypeNil
+ case bincSpFalse, bincSpTrue:
+ d.bdType = valueTypeBool
+ case bincSpNan, bincSpNegInf, bincSpPosInf, bincSpZeroFloat:
+ d.bdType = valueTypeFloat
+ case bincSpZero:
+ d.bdType = valueTypeUint
+ case bincSpNegOne:
+ d.bdType = valueTypeInt
+ default:
+ decErr("currentEncodedType: Unrecognized special value 0x%x", d.vs)
+ }
+ case bincVdSmallInt:
+ d.bdType = valueTypeUint
+ case bincVdPosInt:
+ d.bdType = valueTypeUint
+ case bincVdNegInt:
+ d.bdType = valueTypeInt
+ case bincVdFloat:
+ d.bdType = valueTypeFloat
+ case bincVdString:
+ d.bdType = valueTypeString
+ case bincVdSymbol:
+ d.bdType = valueTypeSymbol
+ case bincVdByteArray:
+ d.bdType = valueTypeBytes
+ case bincVdTimestamp:
+ d.bdType = valueTypeTimestamp
+ case bincVdCustomExt:
+ d.bdType = valueTypeExt
+ case bincVdArray:
+ d.bdType = valueTypeArray
+ case bincVdMap:
+ d.bdType = valueTypeMap
+ default:
+ decErr("currentEncodedType: Unrecognized d.vd: 0x%x", d.vd)
+ }
+ }
+ return d.bdType
+}
+
+func (d *bincDecDriver) tryDecodeAsNil() bool {
+ if d.bd == bincVdSpecial<<4|bincSpNil {
+ d.bdRead = false
+ return true
+ }
+ return false
+}
+
+func (d *bincDecDriver) isBuiltinType(rt uintptr) bool {
+ return rt == timeTypId
+}
+
+func (d *bincDecDriver) decodeBuiltin(rt uintptr, v interface{}) {
+ switch rt {
+ case timeTypId:
+ if d.vd != bincVdTimestamp {
+ decErr("Invalid d.vd. Expecting 0x%x. Received: 0x%x", bincVdTimestamp, d.vd)
+ }
+ tt, err := decodeTime(d.r.readn(int(d.vs)))
+ if err != nil {
+ panic(err)
+ }
+ var vt *time.Time = v.(*time.Time)
+ *vt = tt
+ d.bdRead = false
+ }
+}
+
+func (d *bincDecDriver) decFloatPre(vs, defaultLen byte) {
+ if vs&0x8 == 0 {
+ d.r.readb(d.b[0:defaultLen])
+ } else {
+ l := d.r.readn1()
+ if l > 8 {
+ decErr("At most 8 bytes used to represent float. Received: %v bytes", l)
+ }
+ for i := l; i < 8; i++ {
+ d.b[i] = 0
+ }
+ d.r.readb(d.b[0:l])
+ }
+}
+
+func (d *bincDecDriver) decFloat() (f float64) {
+ //if true { f = math.Float64frombits(d.r.readUint64()); break; }
+ switch vs := d.vs; vs & 0x7 {
+ case bincFlBin32:
+ d.decFloatPre(vs, 4)
+ f = float64(math.Float32frombits(bigen.Uint32(d.b[0:4])))
+ case bincFlBin64:
+ d.decFloatPre(vs, 8)
+ f = math.Float64frombits(bigen.Uint64(d.b[0:8]))
+ default:
+ decErr("only float32 and float64 are supported. d.vd: 0x%x, d.vs: 0x%x", d.vd, d.vs)
+ }
+ return
+}
+
+func (d *bincDecDriver) decUint() (v uint64) {
+ // need to inline the code (interface conversion and type assertion expensive)
+ switch d.vs {
+ case 0:
+ v = uint64(d.r.readn1())
+ case 1:
+ d.r.readb(d.b[6:])
+ v = uint64(bigen.Uint16(d.b[6:]))
+ case 2:
+ d.b[4] = 0
+ d.r.readb(d.b[5:])
+ v = uint64(bigen.Uint32(d.b[4:]))
+ case 3:
+ d.r.readb(d.b[4:])
+ v = uint64(bigen.Uint32(d.b[4:]))
+ case 4, 5, 6:
+ lim := int(7 - d.vs)
+ d.r.readb(d.b[lim:])
+ for i := 0; i < lim; i++ {
+ d.b[i] = 0
+ }
+ v = uint64(bigen.Uint64(d.b[:]))
+ case 7:
+ d.r.readb(d.b[:])
+ v = uint64(bigen.Uint64(d.b[:]))
+ default:
+ decErr("unsigned integers with greater than 64 bits of precision not supported")
+ }
+ return
+}
+
+func (d *bincDecDriver) decIntAny() (ui uint64, i int64, neg bool) {
+ switch d.vd {
+ case bincVdPosInt:
+ ui = d.decUint()
+ i = int64(ui)
+ case bincVdNegInt:
+ ui = d.decUint()
+ i = -(int64(ui))
+ neg = true
+ case bincVdSmallInt:
+ i = int64(d.vs) + 1
+ ui = uint64(d.vs) + 1
+ case bincVdSpecial:
+ switch d.vs {
+ case bincSpZero:
+ //i = 0
+ case bincSpNegOne:
+ neg = true
+ ui = 1
+ i = -1
+ default:
+ decErr("numeric decode fails for special value: d.vs: 0x%x", d.vs)
+ }
+ default:
+ decErr("number can only be decoded from uint or int values. d.bd: 0x%x, d.vd: 0x%x", d.bd, d.vd)
+ }
+ return
+}
+
+func (d *bincDecDriver) decodeInt(bitsize uint8) (i int64) {
+ _, i, _ = d.decIntAny()
+ checkOverflow(0, i, bitsize)
+ d.bdRead = false
+ return
+}
+
+func (d *bincDecDriver) decodeUint(bitsize uint8) (ui uint64) {
+ ui, i, neg := d.decIntAny()
+ if neg {
+ decErr("Assigning negative signed value: %v, to unsigned type", i)
+ }
+ checkOverflow(ui, 0, bitsize)
+ d.bdRead = false
+ return
+}
+
+func (d *bincDecDriver) decodeFloat(chkOverflow32 bool) (f float64) {
+ switch d.vd {
+ case bincVdSpecial:
+ d.bdRead = false
+ switch d.vs {
+ case bincSpNan:
+ return math.NaN()
+ case bincSpPosInf:
+ return math.Inf(1)
+ case bincSpZeroFloat, bincSpZero:
+ return
+ case bincSpNegInf:
+ return math.Inf(-1)
+ default:
+ decErr("Invalid d.vs decoding float where d.vd=bincVdSpecial: %v", d.vs)
+ }
+ case bincVdFloat:
+ f = d.decFloat()
+ default:
+ _, i, _ := d.decIntAny()
+ f = float64(i)
+ }
+ checkOverflowFloat32(f, chkOverflow32)
+ d.bdRead = false
+ return
+}
+
+// bool can be decoded from bool only (single byte).
+func (d *bincDecDriver) decodeBool() (b bool) {
+ switch d.bd {
+ case (bincVdSpecial | bincSpFalse):
+ // b = false
+ case (bincVdSpecial | bincSpTrue):
+ b = true
+ default:
+ decErr("Invalid single-byte value for bool: %s: %x", msgBadDesc, d.bd)
+ }
+ d.bdRead = false
+ return
+}
+
+func (d *bincDecDriver) readMapLen() (length int) {
+ if d.vd != bincVdMap {
+ decErr("Invalid d.vd for map. Expecting 0x%x. Got: 0x%x", bincVdMap, d.vd)
+ }
+ length = d.decLen()
+ d.bdRead = false
+ return
+}
+
+func (d *bincDecDriver) readArrayLen() (length int) {
+ if d.vd != bincVdArray {
+ decErr("Invalid d.vd for array. Expecting 0x%x. Got: 0x%x", bincVdArray, d.vd)
+ }
+ length = d.decLen()
+ d.bdRead = false
+ return
+}
+
+func (d *bincDecDriver) decLen() int {
+ if d.vs <= 3 {
+ return int(d.decUint())
+ }
+ return int(d.vs - 4)
+}
+
+func (d *bincDecDriver) decodeString() (s string) {
+ switch d.vd {
+ case bincVdString, bincVdByteArray:
+ if length := d.decLen(); length > 0 {
+ s = string(d.r.readn(length))
+ }
+ case bincVdSymbol:
+ //from vs: extract numSymbolBytes, containsStringVal, strLenPrecision,
+ //extract symbol
+ //if containsStringVal, read it and put in map
+ //else look in map for string value
+ var symbol uint32
+ vs := d.vs
+ //fmt.Printf(">>>> d.vs: 0b%b, & 0x8: %v, & 0x4: %v\n", d.vs, vs & 0x8, vs & 0x4)
+ if vs&0x8 == 0 {
+ symbol = uint32(d.r.readn1())
+ } else {
+ symbol = uint32(d.r.readUint16())
+ }
+ if d.m == nil {
+ d.m = make(map[uint32]string, 16)
+ }
+
+ if vs&0x4 == 0 {
+ s = d.m[symbol]
+ } else {
+ var slen int
+ switch vs & 0x3 {
+ case 0:
+ slen = int(d.r.readn1())
+ case 1:
+ slen = int(d.r.readUint16())
+ case 2:
+ slen = int(d.r.readUint32())
+ case 3:
+ slen = int(d.r.readUint64())
+ }
+ s = string(d.r.readn(slen))
+ d.m[symbol] = s
+ }
+ default:
+ decErr("Invalid d.vd for string. Expecting string:0x%x, bytearray:0x%x or symbol: 0x%x. Got: 0x%x",
+ bincVdString, bincVdByteArray, bincVdSymbol, d.vd)
+ }
+ d.bdRead = false
+ return
+}
+
+func (d *bincDecDriver) decodeBytes(bs []byte) (bsOut []byte, changed bool) {
+ var clen int
+ switch d.vd {
+ case bincVdString, bincVdByteArray:
+ clen = d.decLen()
+ default:
+ decErr("Invalid d.vd for bytes. Expecting string:0x%x or bytearray:0x%x. Got: 0x%x",
+ bincVdString, bincVdByteArray, d.vd)
+ }
+ if clen > 0 {
+ // if no contents in stream, don't update the passed byteslice
+ if len(bs) != clen {
+ if len(bs) > clen {
+ bs = bs[:clen]
+ } else {
+ bs = make([]byte, clen)
+ }
+ bsOut = bs
+ changed = true
+ }
+ d.r.readb(bs)
+ }
+ d.bdRead = false
+ return
+}
+
+func (d *bincDecDriver) decodeExt(verifyTag bool, tag byte) (xtag byte, xbs []byte) {
+ switch d.vd {
+ case bincVdCustomExt:
+ l := d.decLen()
+ xtag = d.r.readn1()
+ if verifyTag && xtag != tag {
+ decErr("Wrong extension tag. Got %b. Expecting: %v", xtag, tag)
+ }
+ xbs = d.r.readn(l)
+ case bincVdByteArray:
+ xbs, _ = d.decodeBytes(nil)
+ default:
+ decErr("Invalid d.vd for extensions (Expecting extensions or byte array). Got: 0x%x", d.vd)
+ }
+ d.bdRead = false
+ return
+}
+
+func (d *bincDecDriver) decodeNaked() (v interface{}, vt valueType, decodeFurther bool) {
+ d.initReadNext()
+
+ switch d.vd {
+ case bincVdSpecial:
+ switch d.vs {
+ case bincSpNil:
+ vt = valueTypeNil
+ case bincSpFalse:
+ vt = valueTypeBool
+ v = false
+ case bincSpTrue:
+ vt = valueTypeBool
+ v = true
+ case bincSpNan:
+ vt = valueTypeFloat
+ v = math.NaN()
+ case bincSpPosInf:
+ vt = valueTypeFloat
+ v = math.Inf(1)
+ case bincSpNegInf:
+ vt = valueTypeFloat
+ v = math.Inf(-1)
+ case bincSpZeroFloat:
+ vt = valueTypeFloat
+ v = float64(0)
+ case bincSpZero:
+ vt = valueTypeUint
+ v = int64(0) // int8(0)
+ case bincSpNegOne:
+ vt = valueTypeInt
+ v = int64(-1) // int8(-1)
+ default:
+ decErr("decodeNaked: Unrecognized special value 0x%x", d.vs)
+ }
+ case bincVdSmallInt:
+ vt = valueTypeUint
+ v = uint64(int8(d.vs)) + 1 // int8(d.vs) + 1
+ case bincVdPosInt:
+ vt = valueTypeUint
+ v = d.decUint()
+ case bincVdNegInt:
+ vt = valueTypeInt
+ v = -(int64(d.decUint()))
+ case bincVdFloat:
+ vt = valueTypeFloat
+ v = d.decFloat()
+ case bincVdSymbol:
+ vt = valueTypeSymbol
+ v = d.decodeString()
+ case bincVdString:
+ vt = valueTypeString
+ v = d.decodeString()
+ case bincVdByteArray:
+ vt = valueTypeBytes
+ v, _ = d.decodeBytes(nil)
+ case bincVdTimestamp:
+ vt = valueTypeTimestamp
+ tt, err := decodeTime(d.r.readn(int(d.vs)))
+ if err != nil {
+ panic(err)
+ }
+ v = tt
+ case bincVdCustomExt:
+ vt = valueTypeExt
+ l := d.decLen()
+ var re RawExt
+ re.Tag = d.r.readn1()
+ re.Data = d.r.readn(l)
+ v = &re
+ vt = valueTypeExt
+ case bincVdArray:
+ vt = valueTypeArray
+ decodeFurther = true
+ case bincVdMap:
+ vt = valueTypeMap
+ decodeFurther = true
+ default:
+ decErr("decodeNaked: Unrecognized d.vd: 0x%x", d.vd)
+ }
+
+ if !decodeFurther {
+ d.bdRead = false
+ }
+ return
+}
+
+//------------------------------------
+
+//BincHandle is a Handle for the Binc Schema-Free Encoding Format
+//defined at https://github.com/ugorji/binc .
+//
+//BincHandle currently supports all Binc features with the following EXCEPTIONS:
+// - only integers up to 64 bits of precision are supported.
+// big integers are unsupported.
+// - Only IEEE 754 binary32 and binary64 floats are supported (ie Go float32 and float64 types).
+// extended precision and decimal IEEE 754 floats are unsupported.
+// - Only UTF-8 strings supported.
+// Unicode_Other Binc types (UTF16, UTF32) are currently unsupported.
+//Note that these EXCEPTIONS are temporary and full support is possible and may happen soon.
+type BincHandle struct {
+ BasicHandle
+}
+
+func (h *BincHandle) newEncDriver(w encWriter) encDriver {
+ return &bincEncDriver{w: w}
+}
+
+func (h *BincHandle) newDecDriver(r decReader) decDriver {
+ return &bincDecDriver{r: r}
+}
+
+func (_ *BincHandle) writeExt() bool {
+ return true
+}
+
+func (h *BincHandle) getBasicHandle() *BasicHandle {
+ return &h.BasicHandle
+}
diff -Naur --color b/vendor/github.com/hashicorp/go-msgpack/codec/decode.go a/vendor/github.com/hashicorp/go-msgpack/codec/decode.go
--- b/vendor/github.com/hashicorp/go-msgpack/codec/decode.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-msgpack/codec/decode.go 2022-11-15 23:06:31.555391002 +0100
@@ -0,0 +1,1048 @@
+// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved.
+// Use of this source code is governed by a BSD-style license found in the LICENSE file.
+
+package codec
+
+import (
+ "io"
+ "reflect"
+ // "runtime/debug"
+)
+
+// Some tagging information for error messages.
+const (
+ msgTagDec = "codec.decoder"
+ msgBadDesc = "Unrecognized descriptor byte"
+ msgDecCannotExpandArr = "cannot expand go array from %v to stream length: %v"
+)
+
+// decReader abstracts the reading source, allowing implementations that can
+// read from an io.Reader or directly off a byte slice with zero-copying.
+type decReader interface {
+ readn(n int) []byte
+ readb([]byte)
+ readn1() uint8
+ readUint16() uint16
+ readUint32() uint32
+ readUint64() uint64
+}
+
+type decDriver interface {
+ initReadNext()
+ tryDecodeAsNil() bool
+ currentEncodedType() valueType
+ isBuiltinType(rt uintptr) bool
+ decodeBuiltin(rt uintptr, v interface{})
+ //decodeNaked: Numbers are decoded as int64, uint64, float64 only (no smaller sized number types).
+ decodeNaked() (v interface{}, vt valueType, decodeFurther bool)
+ decodeInt(bitsize uint8) (i int64)
+ decodeUint(bitsize uint8) (ui uint64)
+ decodeFloat(chkOverflow32 bool) (f float64)
+ decodeBool() (b bool)
+ // decodeString can also decode symbols
+ decodeString() (s string)
+ decodeBytes(bs []byte) (bsOut []byte, changed bool)
+ decodeExt(verifyTag bool, tag byte) (xtag byte, xbs []byte)
+ readMapLen() int
+ readArrayLen() int
+}
+
+type DecodeOptions struct {
+ // An instance of MapType is used during schema-less decoding of a map in the stream.
+ // If nil, we use map[interface{}]interface{}
+ MapType reflect.Type
+ // An instance of SliceType is used during schema-less decoding of an array in the stream.
+ // If nil, we use []interface{}
+ SliceType reflect.Type
+ // ErrorIfNoField controls whether an error is returned when decoding a map
+ // from a codec stream into a struct, and no matching struct field is found.
+ ErrorIfNoField bool
+}
+
+// ------------------------------------
+
+// ioDecReader is a decReader that reads off an io.Reader
+type ioDecReader struct {
+ r io.Reader
+ br io.ByteReader
+ x [8]byte //temp byte array re-used internally for efficiency
+}
+
+func (z *ioDecReader) readn(n int) (bs []byte) {
+ if n <= 0 {
+ return
+ }
+ bs = make([]byte, n)
+ if _, err := io.ReadAtLeast(z.r, bs, n); err != nil {
+ panic(err)
+ }
+ return
+}
+
+func (z *ioDecReader) readb(bs []byte) {
+ if _, err := io.ReadAtLeast(z.r, bs, len(bs)); err != nil {
+ panic(err)
+ }
+}
+
+func (z *ioDecReader) readn1() uint8 {
+ if z.br != nil {
+ b, err := z.br.ReadByte()
+ if err != nil {
+ panic(err)
+ }
+ return b
+ }
+ z.readb(z.x[:1])
+ return z.x[0]
+}
+
+func (z *ioDecReader) readUint16() uint16 {
+ z.readb(z.x[:2])
+ return bigen.Uint16(z.x[:2])
+}
+
+func (z *ioDecReader) readUint32() uint32 {
+ z.readb(z.x[:4])
+ return bigen.Uint32(z.x[:4])
+}
+
+func (z *ioDecReader) readUint64() uint64 {
+ z.readb(z.x[:8])
+ return bigen.Uint64(z.x[:8])
+}
+
+// ------------------------------------
+
+// bytesDecReader is a decReader that reads off a byte slice with zero copying
+type bytesDecReader struct {
+ b []byte // data
+ c int // cursor
+ a int // available
+}
+
+func (z *bytesDecReader) consume(n int) (oldcursor int) {
+ if z.a == 0 {
+ panic(io.EOF)
+ }
+ if n > z.a {
+ decErr("Trying to read %v bytes. Only %v available", n, z.a)
+ }
+ // z.checkAvailable(n)
+ oldcursor = z.c
+ z.c = oldcursor + n
+ z.a = z.a - n
+ return
+}
+
+func (z *bytesDecReader) readn(n int) (bs []byte) {
+ if n <= 0 {
+ return
+ }
+ c0 := z.consume(n)
+ bs = z.b[c0:z.c]
+ return
+}
+
+func (z *bytesDecReader) readb(bs []byte) {
+ copy(bs, z.readn(len(bs)))
+}
+
+func (z *bytesDecReader) readn1() uint8 {
+ c0 := z.consume(1)
+ return z.b[c0]
+}
+
+// Use binaryEncoding helper for 4 and 8 bits, but inline it for 2 bits
+// creating temp slice variable and copying it to helper function is expensive
+// for just 2 bits.
+
+func (z *bytesDecReader) readUint16() uint16 {
+ c0 := z.consume(2)
+ return uint16(z.b[c0+1]) | uint16(z.b[c0])<<8
+}
+
+func (z *bytesDecReader) readUint32() uint32 {
+ c0 := z.consume(4)
+ return bigen.Uint32(z.b[c0:z.c])
+}
+
+func (z *bytesDecReader) readUint64() uint64 {
+ c0 := z.consume(8)
+ return bigen.Uint64(z.b[c0:z.c])
+}
+
+// ------------------------------------
+
+// decFnInfo has methods for registering handling decoding of a specific type
+// based on some characteristics (builtin, extension, reflect Kind, etc)
+type decFnInfo struct {
+ ti *typeInfo
+ d *Decoder
+ dd decDriver
+ xfFn func(reflect.Value, []byte) error
+ xfTag byte
+ array bool
+}
+
+func (f *decFnInfo) builtin(rv reflect.Value) {
+ f.dd.decodeBuiltin(f.ti.rtid, rv.Addr().Interface())
+}
+
+func (f *decFnInfo) rawExt(rv reflect.Value) {
+ xtag, xbs := f.dd.decodeExt(false, 0)
+ rv.Field(0).SetUint(uint64(xtag))
+ rv.Field(1).SetBytes(xbs)
+}
+
+func (f *decFnInfo) ext(rv reflect.Value) {
+ _, xbs := f.dd.decodeExt(true, f.xfTag)
+ if fnerr := f.xfFn(rv, xbs); fnerr != nil {
+ panic(fnerr)
+ }
+}
+
+func (f *decFnInfo) binaryMarshal(rv reflect.Value) {
+ var bm binaryUnmarshaler
+ if f.ti.unmIndir == -1 {
+ bm = rv.Addr().Interface().(binaryUnmarshaler)
+ } else if f.ti.unmIndir == 0 {
+ bm = rv.Interface().(binaryUnmarshaler)
+ } else {
+ for j, k := int8(0), f.ti.unmIndir; j < k; j++ {
+ if rv.IsNil() {
+ rv.Set(reflect.New(rv.Type().Elem()))
+ }
+ rv = rv.Elem()
+ }
+ bm = rv.Interface().(binaryUnmarshaler)
+ }
+ xbs, _ := f.dd.decodeBytes(nil)
+ if fnerr := bm.UnmarshalBinary(xbs); fnerr != nil {
+ panic(fnerr)
+ }
+}
+
+func (f *decFnInfo) kErr(rv reflect.Value) {
+ decErr("Unhandled value for kind: %v: %s", rv.Kind(), msgBadDesc)
+}
+
+func (f *decFnInfo) kString(rv reflect.Value) {
+ rv.SetString(f.dd.decodeString())
+}
+
+func (f *decFnInfo) kBool(rv reflect.Value) {
+ rv.SetBool(f.dd.decodeBool())
+}
+
+func (f *decFnInfo) kInt(rv reflect.Value) {
+ rv.SetInt(f.dd.decodeInt(intBitsize))
+}
+
+func (f *decFnInfo) kInt64(rv reflect.Value) {
+ rv.SetInt(f.dd.decodeInt(64))
+}
+
+func (f *decFnInfo) kInt32(rv reflect.Value) {
+ rv.SetInt(f.dd.decodeInt(32))
+}
+
+func (f *decFnInfo) kInt8(rv reflect.Value) {
+ rv.SetInt(f.dd.decodeInt(8))
+}
+
+func (f *decFnInfo) kInt16(rv reflect.Value) {
+ rv.SetInt(f.dd.decodeInt(16))
+}
+
+func (f *decFnInfo) kFloat32(rv reflect.Value) {
+ rv.SetFloat(f.dd.decodeFloat(true))
+}
+
+func (f *decFnInfo) kFloat64(rv reflect.Value) {
+ rv.SetFloat(f.dd.decodeFloat(false))
+}
+
+func (f *decFnInfo) kUint8(rv reflect.Value) {
+ rv.SetUint(f.dd.decodeUint(8))
+}
+
+func (f *decFnInfo) kUint64(rv reflect.Value) {
+ rv.SetUint(f.dd.decodeUint(64))
+}
+
+func (f *decFnInfo) kUint(rv reflect.Value) {
+ rv.SetUint(f.dd.decodeUint(uintBitsize))
+}
+
+func (f *decFnInfo) kUint32(rv reflect.Value) {
+ rv.SetUint(f.dd.decodeUint(32))
+}
+
+func (f *decFnInfo) kUint16(rv reflect.Value) {
+ rv.SetUint(f.dd.decodeUint(16))
+}
+
+// func (f *decFnInfo) kPtr(rv reflect.Value) {
+// debugf(">>>>>>> ??? decode kPtr called - shouldn't get called")
+// if rv.IsNil() {
+// rv.Set(reflect.New(rv.Type().Elem()))
+// }
+// f.d.decodeValue(rv.Elem())
+// }
+
+func (f *decFnInfo) kInterface(rv reflect.Value) {
+ // debugf("\t===> kInterface")
+ if !rv.IsNil() {
+ f.d.decodeValue(rv.Elem())
+ return
+ }
+ // nil interface:
+ // use some hieristics to set the nil interface to an
+ // appropriate value based on the first byte read (byte descriptor bd)
+ v, vt, decodeFurther := f.dd.decodeNaked()
+ if vt == valueTypeNil {
+ return
+ }
+ // Cannot decode into nil interface with methods (e.g. error, io.Reader, etc)
+ // if non-nil value in stream.
+ if num := f.ti.rt.NumMethod(); num > 0 {
+ decErr("decodeValue: Cannot decode non-nil codec value into nil %v (%v methods)",
+ f.ti.rt, num)
+ }
+ var rvn reflect.Value
+ var useRvn bool
+ switch vt {
+ case valueTypeMap:
+ if f.d.h.MapType == nil {
+ var m2 map[interface{}]interface{}
+ v = &m2
+ } else {
+ rvn = reflect.New(f.d.h.MapType).Elem()
+ useRvn = true
+ }
+ case valueTypeArray:
+ if f.d.h.SliceType == nil {
+ var m2 []interface{}
+ v = &m2
+ } else {
+ rvn = reflect.New(f.d.h.SliceType).Elem()
+ useRvn = true
+ }
+ case valueTypeExt:
+ re := v.(*RawExt)
+ var bfn func(reflect.Value, []byte) error
+ rvn, bfn = f.d.h.getDecodeExtForTag(re.Tag)
+ if bfn == nil {
+ rvn = reflect.ValueOf(*re)
+ } else if fnerr := bfn(rvn, re.Data); fnerr != nil {
+ panic(fnerr)
+ }
+ rv.Set(rvn)
+ return
+ }
+ if decodeFurther {
+ if useRvn {
+ f.d.decodeValue(rvn)
+ } else if v != nil {
+ // this v is a pointer, so we need to dereference it when done
+ f.d.decode(v)
+ rvn = reflect.ValueOf(v).Elem()
+ useRvn = true
+ }
+ }
+ if useRvn {
+ rv.Set(rvn)
+ } else if v != nil {
+ rv.Set(reflect.ValueOf(v))
+ }
+}
+
+func (f *decFnInfo) kStruct(rv reflect.Value) {
+ fti := f.ti
+ if currEncodedType := f.dd.currentEncodedType(); currEncodedType == valueTypeMap {
+ containerLen := f.dd.readMapLen()
+ if containerLen == 0 {
+ return
+ }
+ tisfi := fti.sfi
+ for j := 0; j < containerLen; j++ {
+ // var rvkencname string
+ // ddecode(&rvkencname)
+ f.dd.initReadNext()
+ rvkencname := f.dd.decodeString()
+ // rvksi := ti.getForEncName(rvkencname)
+ if k := fti.indexForEncName(rvkencname); k > -1 {
+ sfik := tisfi[k]
+ if sfik.i != -1 {
+ f.d.decodeValue(rv.Field(int(sfik.i)))
+ } else {
+ f.d.decEmbeddedField(rv, sfik.is)
+ }
+ // f.d.decodeValue(ti.field(k, rv))
+ } else {
+ if f.d.h.ErrorIfNoField {
+ decErr("No matching struct field found when decoding stream map with key: %v",
+ rvkencname)
+ } else {
+ var nilintf0 interface{}
+ f.d.decodeValue(reflect.ValueOf(&nilintf0).Elem())
+ }
+ }
+ }
+ } else if currEncodedType == valueTypeArray {
+ containerLen := f.dd.readArrayLen()
+ if containerLen == 0 {
+ return
+ }
+ for j, si := range fti.sfip {
+ if j == containerLen {
+ break
+ }
+ if si.i != -1 {
+ f.d.decodeValue(rv.Field(int(si.i)))
+ } else {
+ f.d.decEmbeddedField(rv, si.is)
+ }
+ }
+ if containerLen > len(fti.sfip) {
+ // read remaining values and throw away
+ for j := len(fti.sfip); j < containerLen; j++ {
+ var nilintf0 interface{}
+ f.d.decodeValue(reflect.ValueOf(&nilintf0).Elem())
+ }
+ }
+ } else {
+ decErr("Only encoded map or array can be decoded into a struct. (valueType: %x)",
+ currEncodedType)
+ }
+}
+
+func (f *decFnInfo) kSlice(rv reflect.Value) {
+ // A slice can be set from a map or array in stream.
+ currEncodedType := f.dd.currentEncodedType()
+
+ switch currEncodedType {
+ case valueTypeBytes, valueTypeString:
+ if f.ti.rtid == uint8SliceTypId || f.ti.rt.Elem().Kind() == reflect.Uint8 {
+ if bs2, changed2 := f.dd.decodeBytes(rv.Bytes()); changed2 {
+ rv.SetBytes(bs2)
+ }
+ return
+ }
+ }
+
+ if shortCircuitReflectToFastPath && rv.CanAddr() {
+ switch f.ti.rtid {
+ case intfSliceTypId:
+ f.d.decSliceIntf(rv.Addr().Interface().(*[]interface{}), currEncodedType, f.array)
+ return
+ case uint64SliceTypId:
+ f.d.decSliceUint64(rv.Addr().Interface().(*[]uint64), currEncodedType, f.array)
+ return
+ case int64SliceTypId:
+ f.d.decSliceInt64(rv.Addr().Interface().(*[]int64), currEncodedType, f.array)
+ return
+ case strSliceTypId:
+ f.d.decSliceStr(rv.Addr().Interface().(*[]string), currEncodedType, f.array)
+ return
+ }
+ }
+
+ containerLen, containerLenS := decContLens(f.dd, currEncodedType)
+
+ // an array can never return a nil slice. so no need to check f.array here.
+
+ if rv.IsNil() {
+ rv.Set(reflect.MakeSlice(f.ti.rt, containerLenS, containerLenS))
+ }
+
+ if containerLen == 0 {
+ return
+ }
+
+ if rvcap, rvlen := rv.Len(), rv.Cap(); containerLenS > rvcap {
+ if f.array { // !rv.CanSet()
+ decErr(msgDecCannotExpandArr, rvcap, containerLenS)
+ }
+ rvn := reflect.MakeSlice(f.ti.rt, containerLenS, containerLenS)
+ if rvlen > 0 {
+ reflect.Copy(rvn, rv)
+ }
+ rv.Set(rvn)
+ } else if containerLenS > rvlen {
+ rv.SetLen(containerLenS)
+ }
+
+ for j := 0; j < containerLenS; j++ {
+ f.d.decodeValue(rv.Index(j))
+ }
+}
+
+func (f *decFnInfo) kArray(rv reflect.Value) {
+ // f.d.decodeValue(rv.Slice(0, rv.Len()))
+ f.kSlice(rv.Slice(0, rv.Len()))
+}
+
+func (f *decFnInfo) kMap(rv reflect.Value) {
+ if shortCircuitReflectToFastPath && rv.CanAddr() {
+ switch f.ti.rtid {
+ case mapStrIntfTypId:
+ f.d.decMapStrIntf(rv.Addr().Interface().(*map[string]interface{}))
+ return
+ case mapIntfIntfTypId:
+ f.d.decMapIntfIntf(rv.Addr().Interface().(*map[interface{}]interface{}))
+ return
+ case mapInt64IntfTypId:
+ f.d.decMapInt64Intf(rv.Addr().Interface().(*map[int64]interface{}))
+ return
+ case mapUint64IntfTypId:
+ f.d.decMapUint64Intf(rv.Addr().Interface().(*map[uint64]interface{}))
+ return
+ }
+ }
+
+ containerLen := f.dd.readMapLen()
+
+ if rv.IsNil() {
+ rv.Set(reflect.MakeMap(f.ti.rt))
+ }
+
+ if containerLen == 0 {
+ return
+ }
+
+ ktype, vtype := f.ti.rt.Key(), f.ti.rt.Elem()
+ ktypeId := reflect.ValueOf(ktype).Pointer()
+ for j := 0; j < containerLen; j++ {
+ rvk := reflect.New(ktype).Elem()
+ f.d.decodeValue(rvk)
+
+ // special case if a byte array.
+ // if ktype == intfTyp {
+ if ktypeId == intfTypId {
+ rvk = rvk.Elem()
+ if rvk.Type() == uint8SliceTyp {
+ rvk = reflect.ValueOf(string(rvk.Bytes()))
+ }
+ }
+ rvv := rv.MapIndex(rvk)
+ if !rvv.IsValid() || !rvv.CanSet() {
+ rvv = reflect.New(vtype).Elem()
+ }
+
+ f.d.decodeValue(rvv)
+ rv.SetMapIndex(rvk, rvv)
+ }
+}
+
+// ----------------------------------------
+
+type decFn struct {
+ i *decFnInfo
+ f func(*decFnInfo, reflect.Value)
+}
+
+// A Decoder reads and decodes an object from an input stream in the codec format.
+type Decoder struct {
+ r decReader
+ d decDriver
+ h *BasicHandle
+ f map[uintptr]decFn
+ x []uintptr
+ s []decFn
+}
+
+// NewDecoder returns a Decoder for decoding a stream of bytes from an io.Reader.
+//
+// For efficiency, Users are encouraged to pass in a memory buffered writer
+// (eg bufio.Reader, bytes.Buffer).
+func NewDecoder(r io.Reader, h Handle) *Decoder {
+ z := ioDecReader{
+ r: r,
+ }
+ z.br, _ = r.(io.ByteReader)
+ return &Decoder{r: &z, d: h.newDecDriver(&z), h: h.getBasicHandle()}
+}
+
+// NewDecoderBytes returns a Decoder which efficiently decodes directly
+// from a byte slice with zero copying.
+func NewDecoderBytes(in []byte, h Handle) *Decoder {
+ z := bytesDecReader{
+ b: in,
+ a: len(in),
+ }
+ return &Decoder{r: &z, d: h.newDecDriver(&z), h: h.getBasicHandle()}
+}
+
+// Decode decodes the stream from reader and stores the result in the
+// value pointed to by v. v cannot be a nil pointer. v can also be
+// a reflect.Value of a pointer.
+//
+// Note that a pointer to a nil interface is not a nil pointer.
+// If you do not know what type of stream it is, pass in a pointer to a nil interface.
+// We will decode and store a value in that nil interface.
+//
+// Sample usages:
+// // Decoding into a non-nil typed value
+// var f float32
+// err = codec.NewDecoder(r, handle).Decode(&f)
+//
+// // Decoding into nil interface
+// var v interface{}
+// dec := codec.NewDecoder(r, handle)
+// err = dec.Decode(&v)
+//
+// When decoding into a nil interface{}, we will decode into an appropriate value based
+// on the contents of the stream:
+// - Numbers are decoded as float64, int64 or uint64.
+// - Other values are decoded appropriately depending on the type:
+// bool, string, []byte, time.Time, etc
+// - Extensions are decoded as RawExt (if no ext function registered for the tag)
+// Configurations exist on the Handle to override defaults
+// (e.g. for MapType, SliceType and how to decode raw bytes).
+//
+// When decoding into a non-nil interface{} value, the mode of encoding is based on the
+// type of the value. When a value is seen:
+// - If an extension is registered for it, call that extension function
+// - If it implements BinaryUnmarshaler, call its UnmarshalBinary(data []byte) error
+// - Else decode it based on its reflect.Kind
+//
+// There are some special rules when decoding into containers (slice/array/map/struct).
+// Decode will typically use the stream contents to UPDATE the container.
+// - A map can be decoded from a stream map, by updating matching keys.
+// - A slice can be decoded from a stream array,
+// by updating the first n elements, where n is length of the stream.
+// - A slice can be decoded from a stream map, by decoding as if
+// it contains a sequence of key-value pairs.
+// - A struct can be decoded from a stream map, by updating matching fields.
+// - A struct can be decoded from a stream array,
+// by updating fields as they occur in the struct (by index).
+//
+// When decoding a stream map or array with length of 0 into a nil map or slice,
+// we reset the destination map or slice to a zero-length value.
+//
+// However, when decoding a stream nil, we reset the destination container
+// to its "zero" value (e.g. nil for slice/map, etc).
+//
+func (d *Decoder) Decode(v interface{}) (err error) {
+ defer panicToErr(&err)
+ d.decode(v)
+ return
+}
+
+func (d *Decoder) decode(iv interface{}) {
+ d.d.initReadNext()
+
+ switch v := iv.(type) {
+ case nil:
+ decErr("Cannot decode into nil.")
+
+ case reflect.Value:
+ d.chkPtrValue(v)
+ d.decodeValue(v.Elem())
+
+ case *string:
+ *v = d.d.decodeString()
+ case *bool:
+ *v = d.d.decodeBool()
+ case *int:
+ *v = int(d.d.decodeInt(intBitsize))
+ case *int8:
+ *v = int8(d.d.decodeInt(8))
+ case *int16:
+ *v = int16(d.d.decodeInt(16))
+ case *int32:
+ *v = int32(d.d.decodeInt(32))
+ case *int64:
+ *v = d.d.decodeInt(64)
+ case *uint:
+ *v = uint(d.d.decodeUint(uintBitsize))
+ case *uint8:
+ *v = uint8(d.d.decodeUint(8))
+ case *uint16:
+ *v = uint16(d.d.decodeUint(16))
+ case *uint32:
+ *v = uint32(d.d.decodeUint(32))
+ case *uint64:
+ *v = d.d.decodeUint(64)
+ case *float32:
+ *v = float32(d.d.decodeFloat(true))
+ case *float64:
+ *v = d.d.decodeFloat(false)
+ case *[]byte:
+ *v, _ = d.d.decodeBytes(*v)
+
+ case *[]interface{}:
+ d.decSliceIntf(v, valueTypeInvalid, false)
+ case *[]uint64:
+ d.decSliceUint64(v, valueTypeInvalid, false)
+ case *[]int64:
+ d.decSliceInt64(v, valueTypeInvalid, false)
+ case *[]string:
+ d.decSliceStr(v, valueTypeInvalid, false)
+ case *map[string]interface{}:
+ d.decMapStrIntf(v)
+ case *map[interface{}]interface{}:
+ d.decMapIntfIntf(v)
+ case *map[uint64]interface{}:
+ d.decMapUint64Intf(v)
+ case *map[int64]interface{}:
+ d.decMapInt64Intf(v)
+
+ case *interface{}:
+ d.decodeValue(reflect.ValueOf(iv).Elem())
+
+ default:
+ rv := reflect.ValueOf(iv)
+ d.chkPtrValue(rv)
+ d.decodeValue(rv.Elem())
+ }
+}
+
+func (d *Decoder) decodeValue(rv reflect.Value) {
+ d.d.initReadNext()
+
+ if d.d.tryDecodeAsNil() {
+ // If value in stream is nil, set the dereferenced value to its "zero" value (if settable)
+ if rv.Kind() == reflect.Ptr {
+ if !rv.IsNil() {
+ rv.Set(reflect.Zero(rv.Type()))
+ }
+ return
+ }
+ // for rv.Kind() == reflect.Ptr {
+ // rv = rv.Elem()
+ // }
+ if rv.IsValid() { // rv.CanSet() // always settable, except it's invalid
+ rv.Set(reflect.Zero(rv.Type()))
+ }
+ return
+ }
+
+ // If stream is not containing a nil value, then we can deref to the base
+ // non-pointer value, and decode into that.
+ for rv.Kind() == reflect.Ptr {
+ if rv.IsNil() {
+ rv.Set(reflect.New(rv.Type().Elem()))
+ }
+ rv = rv.Elem()
+ }
+
+ rt := rv.Type()
+ rtid := reflect.ValueOf(rt).Pointer()
+
+ // retrieve or register a focus'ed function for this type
+ // to eliminate need to do the retrieval multiple times
+
+ // if d.f == nil && d.s == nil { debugf("---->Creating new dec f map for type: %v\n", rt) }
+ var fn decFn
+ var ok bool
+ if useMapForCodecCache {
+ fn, ok = d.f[rtid]
+ } else {
+ for i, v := range d.x {
+ if v == rtid {
+ fn, ok = d.s[i], true
+ break
+ }
+ }
+ }
+ if !ok {
+ // debugf("\tCreating new dec fn for type: %v\n", rt)
+ fi := decFnInfo{ti: getTypeInfo(rtid, rt), d: d, dd: d.d}
+ fn.i = &fi
+ // An extension can be registered for any type, regardless of the Kind
+ // (e.g. type BitSet int64, type MyStruct { / * unexported fields * / }, type X []int, etc.
+ //
+ // We can't check if it's an extension byte here first, because the user may have
+ // registered a pointer or non-pointer type, meaning we may have to recurse first
+ // before matching a mapped type, even though the extension byte is already detected.
+ //
+ // NOTE: if decoding into a nil interface{}, we return a non-nil
+ // value except even if the container registers a length of 0.
+ if rtid == rawExtTypId {
+ fn.f = (*decFnInfo).rawExt
+ } else if d.d.isBuiltinType(rtid) {
+ fn.f = (*decFnInfo).builtin
+ } else if xfTag, xfFn := d.h.getDecodeExt(rtid); xfFn != nil {
+ fi.xfTag, fi.xfFn = xfTag, xfFn
+ fn.f = (*decFnInfo).ext
+ } else if supportBinaryMarshal && fi.ti.unm {
+ fn.f = (*decFnInfo).binaryMarshal
+ } else {
+ switch rk := rt.Kind(); rk {
+ case reflect.String:
+ fn.f = (*decFnInfo).kString
+ case reflect.Bool:
+ fn.f = (*decFnInfo).kBool
+ case reflect.Int:
+ fn.f = (*decFnInfo).kInt
+ case reflect.Int64:
+ fn.f = (*decFnInfo).kInt64
+ case reflect.Int32:
+ fn.f = (*decFnInfo).kInt32
+ case reflect.Int8:
+ fn.f = (*decFnInfo).kInt8
+ case reflect.Int16:
+ fn.f = (*decFnInfo).kInt16
+ case reflect.Float32:
+ fn.f = (*decFnInfo).kFloat32
+ case reflect.Float64:
+ fn.f = (*decFnInfo).kFloat64
+ case reflect.Uint8:
+ fn.f = (*decFnInfo).kUint8
+ case reflect.Uint64:
+ fn.f = (*decFnInfo).kUint64
+ case reflect.Uint:
+ fn.f = (*decFnInfo).kUint
+ case reflect.Uint32:
+ fn.f = (*decFnInfo).kUint32
+ case reflect.Uint16:
+ fn.f = (*decFnInfo).kUint16
+ // case reflect.Ptr:
+ // fn.f = (*decFnInfo).kPtr
+ case reflect.Interface:
+ fn.f = (*decFnInfo).kInterface
+ case reflect.Struct:
+ fn.f = (*decFnInfo).kStruct
+ case reflect.Slice:
+ fn.f = (*decFnInfo).kSlice
+ case reflect.Array:
+ fi.array = true
+ fn.f = (*decFnInfo).kArray
+ case reflect.Map:
+ fn.f = (*decFnInfo).kMap
+ default:
+ fn.f = (*decFnInfo).kErr
+ }
+ }
+ if useMapForCodecCache {
+ if d.f == nil {
+ d.f = make(map[uintptr]decFn, 16)
+ }
+ d.f[rtid] = fn
+ } else {
+ d.s = append(d.s, fn)
+ d.x = append(d.x, rtid)
+ }
+ }
+
+ fn.f(fn.i, rv)
+
+ return
+}
+
+func (d *Decoder) chkPtrValue(rv reflect.Value) {
+ // We can only decode into a non-nil pointer
+ if rv.Kind() == reflect.Ptr && !rv.IsNil() {
+ return
+ }
+ if !rv.IsValid() {
+ decErr("Cannot decode into a zero (ie invalid) reflect.Value")
+ }
+ if !rv.CanInterface() {
+ decErr("Cannot decode into a value without an interface: %v", rv)
+ }
+ rvi := rv.Interface()
+ decErr("Cannot decode into non-pointer or nil pointer. Got: %v, %T, %v",
+ rv.Kind(), rvi, rvi)
+}
+
+func (d *Decoder) decEmbeddedField(rv reflect.Value, index []int) {
+ // d.decodeValue(rv.FieldByIndex(index))
+ // nil pointers may be here; so reproduce FieldByIndex logic + enhancements
+ for _, j := range index {
+ if rv.Kind() == reflect.Ptr {
+ if rv.IsNil() {
+ rv.Set(reflect.New(rv.Type().Elem()))
+ }
+ // If a pointer, it must be a pointer to struct (based on typeInfo contract)
+ rv = rv.Elem()
+ }
+ rv = rv.Field(j)
+ }
+ d.decodeValue(rv)
+}
+
+// --------------------------------------------------
+
+// short circuit functions for common maps and slices
+
+func (d *Decoder) decSliceIntf(v *[]interface{}, currEncodedType valueType, doNotReset bool) {
+ _, containerLenS := decContLens(d.d, currEncodedType)
+ s := *v
+ if s == nil {
+ s = make([]interface{}, containerLenS, containerLenS)
+ } else if containerLenS > cap(s) {
+ if doNotReset {
+ decErr(msgDecCannotExpandArr, cap(s), containerLenS)
+ }
+ s = make([]interface{}, containerLenS, containerLenS)
+ copy(s, *v)
+ } else if containerLenS > len(s) {
+ s = s[:containerLenS]
+ }
+ for j := 0; j < containerLenS; j++ {
+ d.decode(&s[j])
+ }
+ *v = s
+}
+
+func (d *Decoder) decSliceInt64(v *[]int64, currEncodedType valueType, doNotReset bool) {
+ _, containerLenS := decContLens(d.d, currEncodedType)
+ s := *v
+ if s == nil {
+ s = make([]int64, containerLenS, containerLenS)
+ } else if containerLenS > cap(s) {
+ if doNotReset {
+ decErr(msgDecCannotExpandArr, cap(s), containerLenS)
+ }
+ s = make([]int64, containerLenS, containerLenS)
+ copy(s, *v)
+ } else if containerLenS > len(s) {
+ s = s[:containerLenS]
+ }
+ for j := 0; j < containerLenS; j++ {
+ // d.decode(&s[j])
+ d.d.initReadNext()
+ s[j] = d.d.decodeInt(intBitsize)
+ }
+ *v = s
+}
+
+func (d *Decoder) decSliceUint64(v *[]uint64, currEncodedType valueType, doNotReset bool) {
+ _, containerLenS := decContLens(d.d, currEncodedType)
+ s := *v
+ if s == nil {
+ s = make([]uint64, containerLenS, containerLenS)
+ } else if containerLenS > cap(s) {
+ if doNotReset {
+ decErr(msgDecCannotExpandArr, cap(s), containerLenS)
+ }
+ s = make([]uint64, containerLenS, containerLenS)
+ copy(s, *v)
+ } else if containerLenS > len(s) {
+ s = s[:containerLenS]
+ }
+ for j := 0; j < containerLenS; j++ {
+ // d.decode(&s[j])
+ d.d.initReadNext()
+ s[j] = d.d.decodeUint(intBitsize)
+ }
+ *v = s
+}
+
+func (d *Decoder) decSliceStr(v *[]string, currEncodedType valueType, doNotReset bool) {
+ _, containerLenS := decContLens(d.d, currEncodedType)
+ s := *v
+ if s == nil {
+ s = make([]string, containerLenS, containerLenS)
+ } else if containerLenS > cap(s) {
+ if doNotReset {
+ decErr(msgDecCannotExpandArr, cap(s), containerLenS)
+ }
+ s = make([]string, containerLenS, containerLenS)
+ copy(s, *v)
+ } else if containerLenS > len(s) {
+ s = s[:containerLenS]
+ }
+ for j := 0; j < containerLenS; j++ {
+ // d.decode(&s[j])
+ d.d.initReadNext()
+ s[j] = d.d.decodeString()
+ }
+ *v = s
+}
+
+func (d *Decoder) decMapIntfIntf(v *map[interface{}]interface{}) {
+ containerLen := d.d.readMapLen()
+ m := *v
+ if m == nil {
+ m = make(map[interface{}]interface{}, containerLen)
+ *v = m
+ }
+ for j := 0; j < containerLen; j++ {
+ var mk interface{}
+ d.decode(&mk)
+ // special case if a byte array.
+ if bv, bok := mk.([]byte); bok {
+ mk = string(bv)
+ }
+ mv := m[mk]
+ d.decode(&mv)
+ m[mk] = mv
+ }
+}
+
+func (d *Decoder) decMapInt64Intf(v *map[int64]interface{}) {
+ containerLen := d.d.readMapLen()
+ m := *v
+ if m == nil {
+ m = make(map[int64]interface{}, containerLen)
+ *v = m
+ }
+ for j := 0; j < containerLen; j++ {
+ d.d.initReadNext()
+ mk := d.d.decodeInt(intBitsize)
+ mv := m[mk]
+ d.decode(&mv)
+ m[mk] = mv
+ }
+}
+
+func (d *Decoder) decMapUint64Intf(v *map[uint64]interface{}) {
+ containerLen := d.d.readMapLen()
+ m := *v
+ if m == nil {
+ m = make(map[uint64]interface{}, containerLen)
+ *v = m
+ }
+ for j := 0; j < containerLen; j++ {
+ d.d.initReadNext()
+ mk := d.d.decodeUint(intBitsize)
+ mv := m[mk]
+ d.decode(&mv)
+ m[mk] = mv
+ }
+}
+
+func (d *Decoder) decMapStrIntf(v *map[string]interface{}) {
+ containerLen := d.d.readMapLen()
+ m := *v
+ if m == nil {
+ m = make(map[string]interface{}, containerLen)
+ *v = m
+ }
+ for j := 0; j < containerLen; j++ {
+ d.d.initReadNext()
+ mk := d.d.decodeString()
+ mv := m[mk]
+ d.decode(&mv)
+ m[mk] = mv
+ }
+}
+
+// ----------------------------------------
+
+func decContLens(dd decDriver, currEncodedType valueType) (containerLen, containerLenS int) {
+ if currEncodedType == valueTypeInvalid {
+ currEncodedType = dd.currentEncodedType()
+ }
+ switch currEncodedType {
+ case valueTypeArray:
+ containerLen = dd.readArrayLen()
+ containerLenS = containerLen
+ case valueTypeMap:
+ containerLen = dd.readMapLen()
+ containerLenS = containerLen * 2
+ default:
+ decErr("Only encoded map or array can be decoded into a slice. (valueType: %0x)",
+ currEncodedType)
+ }
+ return
+}
+
+func decErr(format string, params ...interface{}) {
+ doPanic(msgTagDec, format, params...)
+}
diff -Naur --color b/vendor/github.com/hashicorp/go-msgpack/codec/encode.go a/vendor/github.com/hashicorp/go-msgpack/codec/encode.go
--- b/vendor/github.com/hashicorp/go-msgpack/codec/encode.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-msgpack/codec/encode.go 2022-11-15 23:06:31.555391002 +0100
@@ -0,0 +1,1001 @@
+// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved.
+// Use of this source code is governed by a BSD-style license found in the LICENSE file.
+
+package codec
+
+import (
+ "io"
+ "reflect"
+)
+
+const (
+ // Some tagging information for error messages.
+ msgTagEnc = "codec.encoder"
+ defEncByteBufSize = 1 << 6 // 4:16, 6:64, 8:256, 10:1024
+ // maxTimeSecs32 = math.MaxInt32 / 60 / 24 / 366
+)
+
+// AsSymbolFlag defines what should be encoded as symbols.
+type AsSymbolFlag uint8
+
+const (
+ // AsSymbolDefault is default.
+ // Currently, this means only encode struct field names as symbols.
+ // The default is subject to change.
+ AsSymbolDefault AsSymbolFlag = iota
+
+ // AsSymbolAll means encode anything which could be a symbol as a symbol.
+ AsSymbolAll = 0xfe
+
+ // AsSymbolNone means do not encode anything as a symbol.
+ AsSymbolNone = 1 << iota
+
+ // AsSymbolMapStringKeys means encode keys in map[string]XXX as symbols.
+ AsSymbolMapStringKeysFlag
+
+ // AsSymbolStructFieldName means encode struct field names as symbols.
+ AsSymbolStructFieldNameFlag
+)
+
+// encWriter abstracting writing to a byte array or to an io.Writer.
+type encWriter interface {
+ writeUint16(uint16)
+ writeUint32(uint32)
+ writeUint64(uint64)
+ writeb([]byte)
+ writestr(string)
+ writen1(byte)
+ writen2(byte, byte)
+ atEndOfEncode()
+}
+
+// encDriver abstracts the actual codec (binc vs msgpack, etc)
+type encDriver interface {
+ isBuiltinType(rt uintptr) bool
+ encodeBuiltin(rt uintptr, v interface{})
+ encodeNil()
+ encodeInt(i int64)
+ encodeUint(i uint64)
+ encodeBool(b bool)
+ encodeFloat32(f float32)
+ encodeFloat64(f float64)
+ encodeExtPreamble(xtag byte, length int)
+ encodeArrayPreamble(length int)
+ encodeMapPreamble(length int)
+ encodeString(c charEncoding, v string)
+ encodeSymbol(v string)
+ encodeStringBytes(c charEncoding, v []byte)
+ //TODO
+ //encBignum(f *big.Int)
+ //encStringRunes(c charEncoding, v []rune)
+}
+
+type ioEncWriterWriter interface {
+ WriteByte(c byte) error
+ WriteString(s string) (n int, err error)
+ Write(p []byte) (n int, err error)
+}
+
+type ioEncStringWriter interface {
+ WriteString(s string) (n int, err error)
+}
+
+type EncodeOptions struct {
+ // Encode a struct as an array, and not as a map.
+ StructToArray bool
+
+ // AsSymbols defines what should be encoded as symbols.
+ //
+ // Encoding as symbols can reduce the encoded size significantly.
+ //
+ // However, during decoding, each string to be encoded as a symbol must
+ // be checked to see if it has been seen before. Consequently, encoding time
+ // will increase if using symbols, because string comparisons has a clear cost.
+ //
+ // Sample values:
+ // AsSymbolNone
+ // AsSymbolAll
+ // AsSymbolMapStringKeys
+ // AsSymbolMapStringKeysFlag | AsSymbolStructFieldNameFlag
+ AsSymbols AsSymbolFlag
+}
+
+// ---------------------------------------------
+
+type simpleIoEncWriterWriter struct {
+ w io.Writer
+ bw io.ByteWriter
+ sw ioEncStringWriter
+}
+
+func (o *simpleIoEncWriterWriter) WriteByte(c byte) (err error) {
+ if o.bw != nil {
+ return o.bw.WriteByte(c)
+ }
+ _, err = o.w.Write([]byte{c})
+ return
+}
+
+func (o *simpleIoEncWriterWriter) WriteString(s string) (n int, err error) {
+ if o.sw != nil {
+ return o.sw.WriteString(s)
+ }
+ return o.w.Write([]byte(s))
+}
+
+func (o *simpleIoEncWriterWriter) Write(p []byte) (n int, err error) {
+ return o.w.Write(p)
+}
+
+// ----------------------------------------
+
+// ioEncWriter implements encWriter and can write to an io.Writer implementation
+type ioEncWriter struct {
+ w ioEncWriterWriter
+ x [8]byte // temp byte array re-used internally for efficiency
+}
+
+func (z *ioEncWriter) writeUint16(v uint16) {
+ bigen.PutUint16(z.x[:2], v)
+ z.writeb(z.x[:2])
+}
+
+func (z *ioEncWriter) writeUint32(v uint32) {
+ bigen.PutUint32(z.x[:4], v)
+ z.writeb(z.x[:4])
+}
+
+func (z *ioEncWriter) writeUint64(v uint64) {
+ bigen.PutUint64(z.x[:8], v)
+ z.writeb(z.x[:8])
+}
+
+func (z *ioEncWriter) writeb(bs []byte) {
+ if len(bs) == 0 {
+ return
+ }
+ n, err := z.w.Write(bs)
+ if err != nil {
+ panic(err)
+ }
+ if n != len(bs) {
+ encErr("write: Incorrect num bytes written. Expecting: %v, Wrote: %v", len(bs), n)
+ }
+}
+
+func (z *ioEncWriter) writestr(s string) {
+ n, err := z.w.WriteString(s)
+ if err != nil {
+ panic(err)
+ }
+ if n != len(s) {
+ encErr("write: Incorrect num bytes written. Expecting: %v, Wrote: %v", len(s), n)
+ }
+}
+
+func (z *ioEncWriter) writen1(b byte) {
+ if err := z.w.WriteByte(b); err != nil {
+ panic(err)
+ }
+}
+
+func (z *ioEncWriter) writen2(b1 byte, b2 byte) {
+ z.writen1(b1)
+ z.writen1(b2)
+}
+
+func (z *ioEncWriter) atEndOfEncode() {}
+
+// ----------------------------------------
+
+// bytesEncWriter implements encWriter and can write to an byte slice.
+// It is used by Marshal function.
+type bytesEncWriter struct {
+ b []byte
+ c int // cursor
+ out *[]byte // write out on atEndOfEncode
+}
+
+func (z *bytesEncWriter) writeUint16(v uint16) {
+ c := z.grow(2)
+ z.b[c] = byte(v >> 8)
+ z.b[c+1] = byte(v)
+}
+
+func (z *bytesEncWriter) writeUint32(v uint32) {
+ c := z.grow(4)
+ z.b[c] = byte(v >> 24)
+ z.b[c+1] = byte(v >> 16)
+ z.b[c+2] = byte(v >> 8)
+ z.b[c+3] = byte(v)
+}
+
+func (z *bytesEncWriter) writeUint64(v uint64) {
+ c := z.grow(8)
+ z.b[c] = byte(v >> 56)
+ z.b[c+1] = byte(v >> 48)
+ z.b[c+2] = byte(v >> 40)
+ z.b[c+3] = byte(v >> 32)
+ z.b[c+4] = byte(v >> 24)
+ z.b[c+5] = byte(v >> 16)
+ z.b[c+6] = byte(v >> 8)
+ z.b[c+7] = byte(v)
+}
+
+func (z *bytesEncWriter) writeb(s []byte) {
+ if len(s) == 0 {
+ return
+ }
+ c := z.grow(len(s))
+ copy(z.b[c:], s)
+}
+
+func (z *bytesEncWriter) writestr(s string) {
+ c := z.grow(len(s))
+ copy(z.b[c:], s)
+}
+
+func (z *bytesEncWriter) writen1(b1 byte) {
+ c := z.grow(1)
+ z.b[c] = b1
+}
+
+func (z *bytesEncWriter) writen2(b1 byte, b2 byte) {
+ c := z.grow(2)
+ z.b[c] = b1
+ z.b[c+1] = b2
+}
+
+func (z *bytesEncWriter) atEndOfEncode() {
+ *(z.out) = z.b[:z.c]
+}
+
+func (z *bytesEncWriter) grow(n int) (oldcursor int) {
+ oldcursor = z.c
+ z.c = oldcursor + n
+ if z.c > cap(z.b) {
+ // Tried using appendslice logic: (if cap < 1024, *2, else *1.25).
+ // However, it was too expensive, causing too many iterations of copy.
+ // Using bytes.Buffer model was much better (2*cap + n)
+ bs := make([]byte, 2*cap(z.b)+n)
+ copy(bs, z.b[:oldcursor])
+ z.b = bs
+ } else if z.c > len(z.b) {
+ z.b = z.b[:cap(z.b)]
+ }
+ return
+}
+
+// ---------------------------------------------
+
+type encFnInfo struct {
+ ti *typeInfo
+ e *Encoder
+ ee encDriver
+ xfFn func(reflect.Value) ([]byte, error)
+ xfTag byte
+}
+
+func (f *encFnInfo) builtin(rv reflect.Value) {
+ f.ee.encodeBuiltin(f.ti.rtid, rv.Interface())
+}
+
+func (f *encFnInfo) rawExt(rv reflect.Value) {
+ f.e.encRawExt(rv.Interface().(RawExt))
+}
+
+func (f *encFnInfo) ext(rv reflect.Value) {
+ bs, fnerr := f.xfFn(rv)
+ if fnerr != nil {
+ panic(fnerr)
+ }
+ if bs == nil {
+ f.ee.encodeNil()
+ return
+ }
+ if f.e.hh.writeExt() {
+ f.ee.encodeExtPreamble(f.xfTag, len(bs))
+ f.e.w.writeb(bs)
+ } else {
+ f.ee.encodeStringBytes(c_RAW, bs)
+ }
+
+}
+
+func (f *encFnInfo) binaryMarshal(rv reflect.Value) {
+ var bm binaryMarshaler
+ if f.ti.mIndir == 0 {
+ bm = rv.Interface().(binaryMarshaler)
+ } else if f.ti.mIndir == -1 {
+ bm = rv.Addr().Interface().(binaryMarshaler)
+ } else {
+ for j, k := int8(0), f.ti.mIndir; j < k; j++ {
+ if rv.IsNil() {
+ f.ee.encodeNil()
+ return
+ }
+ rv = rv.Elem()
+ }
+ bm = rv.Interface().(binaryMarshaler)
+ }
+ // debugf(">>>> binaryMarshaler: %T", rv.Interface())
+ bs, fnerr := bm.MarshalBinary()
+ if fnerr != nil {
+ panic(fnerr)
+ }
+ if bs == nil {
+ f.ee.encodeNil()
+ } else {
+ f.ee.encodeStringBytes(c_RAW, bs)
+ }
+}
+
+func (f *encFnInfo) kBool(rv reflect.Value) {
+ f.ee.encodeBool(rv.Bool())
+}
+
+func (f *encFnInfo) kString(rv reflect.Value) {
+ f.ee.encodeString(c_UTF8, rv.String())
+}
+
+func (f *encFnInfo) kFloat64(rv reflect.Value) {
+ f.ee.encodeFloat64(rv.Float())
+}
+
+func (f *encFnInfo) kFloat32(rv reflect.Value) {
+ f.ee.encodeFloat32(float32(rv.Float()))
+}
+
+func (f *encFnInfo) kInt(rv reflect.Value) {
+ f.ee.encodeInt(rv.Int())
+}
+
+func (f *encFnInfo) kUint(rv reflect.Value) {
+ f.ee.encodeUint(rv.Uint())
+}
+
+func (f *encFnInfo) kInvalid(rv reflect.Value) {
+ f.ee.encodeNil()
+}
+
+func (f *encFnInfo) kErr(rv reflect.Value) {
+ encErr("Unsupported kind: %s, for: %#v", rv.Kind(), rv)
+}
+
+func (f *encFnInfo) kSlice(rv reflect.Value) {
+ if rv.IsNil() {
+ f.ee.encodeNil()
+ return
+ }
+
+ if shortCircuitReflectToFastPath {
+ switch f.ti.rtid {
+ case intfSliceTypId:
+ f.e.encSliceIntf(rv.Interface().([]interface{}))
+ return
+ case strSliceTypId:
+ f.e.encSliceStr(rv.Interface().([]string))
+ return
+ case uint64SliceTypId:
+ f.e.encSliceUint64(rv.Interface().([]uint64))
+ return
+ case int64SliceTypId:
+ f.e.encSliceInt64(rv.Interface().([]int64))
+ return
+ }
+ }
+
+ // If in this method, then there was no extension function defined.
+ // So it's okay to treat as []byte.
+ if f.ti.rtid == uint8SliceTypId || f.ti.rt.Elem().Kind() == reflect.Uint8 {
+ f.ee.encodeStringBytes(c_RAW, rv.Bytes())
+ return
+ }
+
+ l := rv.Len()
+ if f.ti.mbs {
+ if l%2 == 1 {
+ encErr("mapBySlice: invalid length (must be divisible by 2): %v", l)
+ }
+ f.ee.encodeMapPreamble(l / 2)
+ } else {
+ f.ee.encodeArrayPreamble(l)
+ }
+ if l == 0 {
+ return
+ }
+ for j := 0; j < l; j++ {
+ // TODO: Consider perf implication of encoding odd index values as symbols if type is string
+ f.e.encodeValue(rv.Index(j))
+ }
+}
+
+func (f *encFnInfo) kArray(rv reflect.Value) {
+ // We cannot share kSlice method, because the array may be non-addressable.
+ // E.g. type struct S{B [2]byte}; Encode(S{}) will bomb on "panic: slice of unaddressable array".
+ // So we have to duplicate the functionality here.
+ // f.e.encodeValue(rv.Slice(0, rv.Len()))
+ // f.kSlice(rv.Slice(0, rv.Len()))
+
+ l := rv.Len()
+ // Handle an array of bytes specially (in line with what is done for slices)
+ if f.ti.rt.Elem().Kind() == reflect.Uint8 {
+ if l == 0 {
+ f.ee.encodeStringBytes(c_RAW, nil)
+ return
+ }
+ var bs []byte
+ if rv.CanAddr() {
+ bs = rv.Slice(0, l).Bytes()
+ } else {
+ bs = make([]byte, l)
+ for i := 0; i < l; i++ {
+ bs[i] = byte(rv.Index(i).Uint())
+ }
+ }
+ f.ee.encodeStringBytes(c_RAW, bs)
+ return
+ }
+
+ if f.ti.mbs {
+ if l%2 == 1 {
+ encErr("mapBySlice: invalid length (must be divisible by 2): %v", l)
+ }
+ f.ee.encodeMapPreamble(l / 2)
+ } else {
+ f.ee.encodeArrayPreamble(l)
+ }
+ if l == 0 {
+ return
+ }
+ for j := 0; j < l; j++ {
+ // TODO: Consider perf implication of encoding odd index values as symbols if type is string
+ f.e.encodeValue(rv.Index(j))
+ }
+}
+
+func (f *encFnInfo) kStruct(rv reflect.Value) {
+ fti := f.ti
+ newlen := len(fti.sfi)
+ rvals := make([]reflect.Value, newlen)
+ var encnames []string
+ e := f.e
+ tisfi := fti.sfip
+ toMap := !(fti.toArray || e.h.StructToArray)
+ // if toMap, use the sorted array. If toArray, use unsorted array (to match sequence in struct)
+ if toMap {
+ tisfi = fti.sfi
+ encnames = make([]string, newlen)
+ }
+ newlen = 0
+ for _, si := range tisfi {
+ if si.i != -1 {
+ rvals[newlen] = rv.Field(int(si.i))
+ } else {
+ rvals[newlen] = rv.FieldByIndex(si.is)
+ }
+ if toMap {
+ if si.omitEmpty && isEmptyValue(rvals[newlen]) {
+ continue
+ }
+ encnames[newlen] = si.encName
+ } else {
+ if si.omitEmpty && isEmptyValue(rvals[newlen]) {
+ rvals[newlen] = reflect.Value{} //encode as nil
+ }
+ }
+ newlen++
+ }
+
+ // debugf(">>>> kStruct: newlen: %v", newlen)
+ if toMap {
+ ee := f.ee //don't dereference everytime
+ ee.encodeMapPreamble(newlen)
+ // asSymbols := e.h.AsSymbols&AsSymbolStructFieldNameFlag != 0
+ asSymbols := e.h.AsSymbols == AsSymbolDefault || e.h.AsSymbols&AsSymbolStructFieldNameFlag != 0
+ for j := 0; j < newlen; j++ {
+ if asSymbols {
+ ee.encodeSymbol(encnames[j])
+ } else {
+ ee.encodeString(c_UTF8, encnames[j])
+ }
+ e.encodeValue(rvals[j])
+ }
+ } else {
+ f.ee.encodeArrayPreamble(newlen)
+ for j := 0; j < newlen; j++ {
+ e.encodeValue(rvals[j])
+ }
+ }
+}
+
+// func (f *encFnInfo) kPtr(rv reflect.Value) {
+// debugf(">>>>>>> ??? encode kPtr called - shouldn't get called")
+// if rv.IsNil() {
+// f.ee.encodeNil()
+// return
+// }
+// f.e.encodeValue(rv.Elem())
+// }
+
+func (f *encFnInfo) kInterface(rv reflect.Value) {
+ if rv.IsNil() {
+ f.ee.encodeNil()
+ return
+ }
+ f.e.encodeValue(rv.Elem())
+}
+
+func (f *encFnInfo) kMap(rv reflect.Value) {
+ if rv.IsNil() {
+ f.ee.encodeNil()
+ return
+ }
+
+ if shortCircuitReflectToFastPath {
+ switch f.ti.rtid {
+ case mapIntfIntfTypId:
+ f.e.encMapIntfIntf(rv.Interface().(map[interface{}]interface{}))
+ return
+ case mapStrIntfTypId:
+ f.e.encMapStrIntf(rv.Interface().(map[string]interface{}))
+ return
+ case mapStrStrTypId:
+ f.e.encMapStrStr(rv.Interface().(map[string]string))
+ return
+ case mapInt64IntfTypId:
+ f.e.encMapInt64Intf(rv.Interface().(map[int64]interface{}))
+ return
+ case mapUint64IntfTypId:
+ f.e.encMapUint64Intf(rv.Interface().(map[uint64]interface{}))
+ return
+ }
+ }
+
+ l := rv.Len()
+ f.ee.encodeMapPreamble(l)
+ if l == 0 {
+ return
+ }
+ // keyTypeIsString := f.ti.rt.Key().Kind() == reflect.String
+ keyTypeIsString := f.ti.rt.Key() == stringTyp
+ var asSymbols bool
+ if keyTypeIsString {
+ asSymbols = f.e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0
+ }
+ mks := rv.MapKeys()
+ // for j, lmks := 0, len(mks); j < lmks; j++ {
+ for j := range mks {
+ if keyTypeIsString {
+ if asSymbols {
+ f.ee.encodeSymbol(mks[j].String())
+ } else {
+ f.ee.encodeString(c_UTF8, mks[j].String())
+ }
+ } else {
+ f.e.encodeValue(mks[j])
+ }
+ f.e.encodeValue(rv.MapIndex(mks[j]))
+ }
+
+}
+
+// --------------------------------------------------
+
+// encFn encapsulates the captured variables and the encode function.
+// This way, we only do some calculations one times, and pass to the
+// code block that should be called (encapsulated in a function)
+// instead of executing the checks every time.
+type encFn struct {
+ i *encFnInfo
+ f func(*encFnInfo, reflect.Value)
+}
+
+// --------------------------------------------------
+
+// An Encoder writes an object to an output stream in the codec format.
+type Encoder struct {
+ w encWriter
+ e encDriver
+ h *BasicHandle
+ hh Handle
+ f map[uintptr]encFn
+ x []uintptr
+ s []encFn
+}
+
+// NewEncoder returns an Encoder for encoding into an io.Writer.
+//
+// For efficiency, Users are encouraged to pass in a memory buffered writer
+// (eg bufio.Writer, bytes.Buffer).
+func NewEncoder(w io.Writer, h Handle) *Encoder {
+ ww, ok := w.(ioEncWriterWriter)
+ if !ok {
+ sww := simpleIoEncWriterWriter{w: w}
+ sww.bw, _ = w.(io.ByteWriter)
+ sww.sw, _ = w.(ioEncStringWriter)
+ ww = &sww
+ //ww = bufio.NewWriterSize(w, defEncByteBufSize)
+ }
+ z := ioEncWriter{
+ w: ww,
+ }
+ return &Encoder{w: &z, hh: h, h: h.getBasicHandle(), e: h.newEncDriver(&z)}
+}
+
+// NewEncoderBytes returns an encoder for encoding directly and efficiently
+// into a byte slice, using zero-copying to temporary slices.
+//
+// It will potentially replace the output byte slice pointed to.
+// After encoding, the out parameter contains the encoded contents.
+func NewEncoderBytes(out *[]byte, h Handle) *Encoder {
+ in := *out
+ if in == nil {
+ in = make([]byte, defEncByteBufSize)
+ }
+ z := bytesEncWriter{
+ b: in,
+ out: out,
+ }
+ return &Encoder{w: &z, hh: h, h: h.getBasicHandle(), e: h.newEncDriver(&z)}
+}
+
+// Encode writes an object into a stream in the codec format.
+//
+// Encoding can be configured via the "codec" struct tag for the fields.
+//
+// The "codec" key in struct field's tag value is the key name,
+// followed by an optional comma and options.
+//
+// To set an option on all fields (e.g. omitempty on all fields), you
+// can create a field called _struct, and set flags on it.
+//
+// Struct values "usually" encode as maps. Each exported struct field is encoded unless:
+// - the field's codec tag is "-", OR
+// - the field is empty and its codec tag specifies the "omitempty" option.
+//
+// When encoding as a map, the first string in the tag (before the comma)
+// is the map key string to use when encoding.
+//
+// However, struct values may encode as arrays. This happens when:
+// - StructToArray Encode option is set, OR
+// - the codec tag on the _struct field sets the "toarray" option
+//
+// Values with types that implement MapBySlice are encoded as stream maps.
+//
+// The empty values (for omitempty option) are false, 0, any nil pointer
+// or interface value, and any array, slice, map, or string of length zero.
+//
+// Anonymous fields are encoded inline if no struct tag is present.
+// Else they are encoded as regular fields.
+//
+// Examples:
+//
+// type MyStruct struct {
+// _struct bool `codec:",omitempty"` //set omitempty for every field
+// Field1 string `codec:"-"` //skip this field
+// Field2 int `codec:"myName"` //Use key "myName" in encode stream
+// Field3 int32 `codec:",omitempty"` //use key "Field3". Omit if empty.
+// Field4 bool `codec:"f4,omitempty"` //use key "f4". Omit if empty.
+// ...
+// }
+//
+// type MyStruct struct {
+// _struct bool `codec:",omitempty,toarray"` //set omitempty for every field
+// //and encode struct as an array
+// }
+//
+// The mode of encoding is based on the type of the value. When a value is seen:
+// - If an extension is registered for it, call that extension function
+// - If it implements BinaryMarshaler, call its MarshalBinary() (data []byte, err error)
+// - Else encode it based on its reflect.Kind
+//
+// Note that struct field names and keys in map[string]XXX will be treated as symbols.
+// Some formats support symbols (e.g. binc) and will properly encode the string
+// only once in the stream, and use a tag to refer to it thereafter.
+func (e *Encoder) Encode(v interface{}) (err error) {
+ defer panicToErr(&err)
+ e.encode(v)
+ e.w.atEndOfEncode()
+ return
+}
+
+func (e *Encoder) encode(iv interface{}) {
+ switch v := iv.(type) {
+ case nil:
+ e.e.encodeNil()
+
+ case reflect.Value:
+ e.encodeValue(v)
+
+ case string:
+ e.e.encodeString(c_UTF8, v)
+ case bool:
+ e.e.encodeBool(v)
+ case int:
+ e.e.encodeInt(int64(v))
+ case int8:
+ e.e.encodeInt(int64(v))
+ case int16:
+ e.e.encodeInt(int64(v))
+ case int32:
+ e.e.encodeInt(int64(v))
+ case int64:
+ e.e.encodeInt(v)
+ case uint:
+ e.e.encodeUint(uint64(v))
+ case uint8:
+ e.e.encodeUint(uint64(v))
+ case uint16:
+ e.e.encodeUint(uint64(v))
+ case uint32:
+ e.e.encodeUint(uint64(v))
+ case uint64:
+ e.e.encodeUint(v)
+ case float32:
+ e.e.encodeFloat32(v)
+ case float64:
+ e.e.encodeFloat64(v)
+
+ case []interface{}:
+ e.encSliceIntf(v)
+ case []string:
+ e.encSliceStr(v)
+ case []int64:
+ e.encSliceInt64(v)
+ case []uint64:
+ e.encSliceUint64(v)
+ case []uint8:
+ e.e.encodeStringBytes(c_RAW, v)
+
+ case map[interface{}]interface{}:
+ e.encMapIntfIntf(v)
+ case map[string]interface{}:
+ e.encMapStrIntf(v)
+ case map[string]string:
+ e.encMapStrStr(v)
+ case map[int64]interface{}:
+ e.encMapInt64Intf(v)
+ case map[uint64]interface{}:
+ e.encMapUint64Intf(v)
+
+ case *string:
+ e.e.encodeString(c_UTF8, *v)
+ case *bool:
+ e.e.encodeBool(*v)
+ case *int:
+ e.e.encodeInt(int64(*v))
+ case *int8:
+ e.e.encodeInt(int64(*v))
+ case *int16:
+ e.e.encodeInt(int64(*v))
+ case *int32:
+ e.e.encodeInt(int64(*v))
+ case *int64:
+ e.e.encodeInt(*v)
+ case *uint:
+ e.e.encodeUint(uint64(*v))
+ case *uint8:
+ e.e.encodeUint(uint64(*v))
+ case *uint16:
+ e.e.encodeUint(uint64(*v))
+ case *uint32:
+ e.e.encodeUint(uint64(*v))
+ case *uint64:
+ e.e.encodeUint(*v)
+ case *float32:
+ e.e.encodeFloat32(*v)
+ case *float64:
+ e.e.encodeFloat64(*v)
+
+ case *[]interface{}:
+ e.encSliceIntf(*v)
+ case *[]string:
+ e.encSliceStr(*v)
+ case *[]int64:
+ e.encSliceInt64(*v)
+ case *[]uint64:
+ e.encSliceUint64(*v)
+ case *[]uint8:
+ e.e.encodeStringBytes(c_RAW, *v)
+
+ case *map[interface{}]interface{}:
+ e.encMapIntfIntf(*v)
+ case *map[string]interface{}:
+ e.encMapStrIntf(*v)
+ case *map[string]string:
+ e.encMapStrStr(*v)
+ case *map[int64]interface{}:
+ e.encMapInt64Intf(*v)
+ case *map[uint64]interface{}:
+ e.encMapUint64Intf(*v)
+
+ default:
+ e.encodeValue(reflect.ValueOf(iv))
+ }
+}
+
+func (e *Encoder) encodeValue(rv reflect.Value) {
+ for rv.Kind() == reflect.Ptr {
+ if rv.IsNil() {
+ e.e.encodeNil()
+ return
+ }
+ rv = rv.Elem()
+ }
+
+ rt := rv.Type()
+ rtid := reflect.ValueOf(rt).Pointer()
+
+ // if e.f == nil && e.s == nil { debugf("---->Creating new enc f map for type: %v\n", rt) }
+ var fn encFn
+ var ok bool
+ if useMapForCodecCache {
+ fn, ok = e.f[rtid]
+ } else {
+ for i, v := range e.x {
+ if v == rtid {
+ fn, ok = e.s[i], true
+ break
+ }
+ }
+ }
+ if !ok {
+ // debugf("\tCreating new enc fn for type: %v\n", rt)
+ fi := encFnInfo{ti: getTypeInfo(rtid, rt), e: e, ee: e.e}
+ fn.i = &fi
+ if rtid == rawExtTypId {
+ fn.f = (*encFnInfo).rawExt
+ } else if e.e.isBuiltinType(rtid) {
+ fn.f = (*encFnInfo).builtin
+ } else if xfTag, xfFn := e.h.getEncodeExt(rtid); xfFn != nil {
+ fi.xfTag, fi.xfFn = xfTag, xfFn
+ fn.f = (*encFnInfo).ext
+ } else if supportBinaryMarshal && fi.ti.m {
+ fn.f = (*encFnInfo).binaryMarshal
+ } else {
+ switch rk := rt.Kind(); rk {
+ case reflect.Bool:
+ fn.f = (*encFnInfo).kBool
+ case reflect.String:
+ fn.f = (*encFnInfo).kString
+ case reflect.Float64:
+ fn.f = (*encFnInfo).kFloat64
+ case reflect.Float32:
+ fn.f = (*encFnInfo).kFloat32
+ case reflect.Int, reflect.Int8, reflect.Int64, reflect.Int32, reflect.Int16:
+ fn.f = (*encFnInfo).kInt
+ case reflect.Uint8, reflect.Uint64, reflect.Uint, reflect.Uint32, reflect.Uint16:
+ fn.f = (*encFnInfo).kUint
+ case reflect.Invalid:
+ fn.f = (*encFnInfo).kInvalid
+ case reflect.Slice:
+ fn.f = (*encFnInfo).kSlice
+ case reflect.Array:
+ fn.f = (*encFnInfo).kArray
+ case reflect.Struct:
+ fn.f = (*encFnInfo).kStruct
+ // case reflect.Ptr:
+ // fn.f = (*encFnInfo).kPtr
+ case reflect.Interface:
+ fn.f = (*encFnInfo).kInterface
+ case reflect.Map:
+ fn.f = (*encFnInfo).kMap
+ default:
+ fn.f = (*encFnInfo).kErr
+ }
+ }
+ if useMapForCodecCache {
+ if e.f == nil {
+ e.f = make(map[uintptr]encFn, 16)
+ }
+ e.f[rtid] = fn
+ } else {
+ e.s = append(e.s, fn)
+ e.x = append(e.x, rtid)
+ }
+ }
+
+ fn.f(fn.i, rv)
+
+}
+
+func (e *Encoder) encRawExt(re RawExt) {
+ if re.Data == nil {
+ e.e.encodeNil()
+ return
+ }
+ if e.hh.writeExt() {
+ e.e.encodeExtPreamble(re.Tag, len(re.Data))
+ e.w.writeb(re.Data)
+ } else {
+ e.e.encodeStringBytes(c_RAW, re.Data)
+ }
+}
+
+// ---------------------------------------------
+// short circuit functions for common maps and slices
+
+func (e *Encoder) encSliceIntf(v []interface{}) {
+ e.e.encodeArrayPreamble(len(v))
+ for _, v2 := range v {
+ e.encode(v2)
+ }
+}
+
+func (e *Encoder) encSliceStr(v []string) {
+ e.e.encodeArrayPreamble(len(v))
+ for _, v2 := range v {
+ e.e.encodeString(c_UTF8, v2)
+ }
+}
+
+func (e *Encoder) encSliceInt64(v []int64) {
+ e.e.encodeArrayPreamble(len(v))
+ for _, v2 := range v {
+ e.e.encodeInt(v2)
+ }
+}
+
+func (e *Encoder) encSliceUint64(v []uint64) {
+ e.e.encodeArrayPreamble(len(v))
+ for _, v2 := range v {
+ e.e.encodeUint(v2)
+ }
+}
+
+func (e *Encoder) encMapStrStr(v map[string]string) {
+ e.e.encodeMapPreamble(len(v))
+ asSymbols := e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0
+ for k2, v2 := range v {
+ if asSymbols {
+ e.e.encodeSymbol(k2)
+ } else {
+ e.e.encodeString(c_UTF8, k2)
+ }
+ e.e.encodeString(c_UTF8, v2)
+ }
+}
+
+func (e *Encoder) encMapStrIntf(v map[string]interface{}) {
+ e.e.encodeMapPreamble(len(v))
+ asSymbols := e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0
+ for k2, v2 := range v {
+ if asSymbols {
+ e.e.encodeSymbol(k2)
+ } else {
+ e.e.encodeString(c_UTF8, k2)
+ }
+ e.encode(v2)
+ }
+}
+
+func (e *Encoder) encMapInt64Intf(v map[int64]interface{}) {
+ e.e.encodeMapPreamble(len(v))
+ for k2, v2 := range v {
+ e.e.encodeInt(k2)
+ e.encode(v2)
+ }
+}
+
+func (e *Encoder) encMapUint64Intf(v map[uint64]interface{}) {
+ e.e.encodeMapPreamble(len(v))
+ for k2, v2 := range v {
+ e.e.encodeUint(uint64(k2))
+ e.encode(v2)
+ }
+}
+
+func (e *Encoder) encMapIntfIntf(v map[interface{}]interface{}) {
+ e.e.encodeMapPreamble(len(v))
+ for k2, v2 := range v {
+ e.encode(k2)
+ e.encode(v2)
+ }
+}
+
+// ----------------------------------------
+
+func encErr(format string, params ...interface{}) {
+ doPanic(msgTagEnc, format, params...)
+}
diff -Naur --color b/vendor/github.com/hashicorp/go-msgpack/codec/helper.go a/vendor/github.com/hashicorp/go-msgpack/codec/helper.go
--- b/vendor/github.com/hashicorp/go-msgpack/codec/helper.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-msgpack/codec/helper.go 2022-11-15 23:06:31.555391002 +0100
@@ -0,0 +1,596 @@
+// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved.
+// Use of this source code is governed by a BSD-style license found in the LICENSE file.
+
+package codec
+
+// Contains code shared by both encode and decode.
+
+import (
+ "encoding/binary"
+ "fmt"
+ "math"
+ "reflect"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+ "unicode"
+ "unicode/utf8"
+)
+
+const (
+ structTagName = "codec"
+
+ // Support
+ // encoding.BinaryMarshaler: MarshalBinary() (data []byte, err error)
+ // encoding.BinaryUnmarshaler: UnmarshalBinary(data []byte) error
+ // This constant flag will enable or disable it.
+ supportBinaryMarshal = true
+
+ // Each Encoder or Decoder uses a cache of functions based on conditionals,
+ // so that the conditionals are not run every time.
+ //
+ // Either a map or a slice is used to keep track of the functions.
+ // The map is more natural, but has a higher cost than a slice/array.
+ // This flag (useMapForCodecCache) controls which is used.
+ useMapForCodecCache = false
+
+ // For some common container types, we can short-circuit an elaborate
+ // reflection dance and call encode/decode directly.
+ // The currently supported types are:
+ // - slices of strings, or id's (int64,uint64) or interfaces.
+ // - maps of str->str, str->intf, id(int64,uint64)->intf, intf->intf
+ shortCircuitReflectToFastPath = true
+
+ // for debugging, set this to false, to catch panic traces.
+ // Note that this will always cause rpc tests to fail, since they need io.EOF sent via panic.
+ recoverPanicToErr = true
+
+ // if checkStructForEmptyValue, check structs fields to see if an empty value.
+ // This could be an expensive call, so possibly disable it.
+ checkStructForEmptyValue = false
+
+ // if derefForIsEmptyValue, deref pointers and interfaces when checking isEmptyValue
+ derefForIsEmptyValue = false
+)
+
+type charEncoding uint8
+
+const (
+ c_RAW charEncoding = iota
+ c_UTF8
+ c_UTF16LE
+ c_UTF16BE
+ c_UTF32LE
+ c_UTF32BE
+)
+
+// valueType is the stream type
+type valueType uint8
+
+const (
+ valueTypeUnset valueType = iota
+ valueTypeNil
+ valueTypeInt
+ valueTypeUint
+ valueTypeFloat
+ valueTypeBool
+ valueTypeString
+ valueTypeSymbol
+ valueTypeBytes
+ valueTypeMap
+ valueTypeArray
+ valueTypeTimestamp
+ valueTypeExt
+
+ valueTypeInvalid = 0xff
+)
+
+var (
+ bigen = binary.BigEndian
+ structInfoFieldName = "_struct"
+
+ cachedTypeInfo = make(map[uintptr]*typeInfo, 4)
+ cachedTypeInfoMutex sync.RWMutex
+
+ intfSliceTyp = reflect.TypeOf([]interface{}(nil))
+ intfTyp = intfSliceTyp.Elem()
+
+ strSliceTyp = reflect.TypeOf([]string(nil))
+ boolSliceTyp = reflect.TypeOf([]bool(nil))
+ uintSliceTyp = reflect.TypeOf([]uint(nil))
+ uint8SliceTyp = reflect.TypeOf([]uint8(nil))
+ uint16SliceTyp = reflect.TypeOf([]uint16(nil))
+ uint32SliceTyp = reflect.TypeOf([]uint32(nil))
+ uint64SliceTyp = reflect.TypeOf([]uint64(nil))
+ intSliceTyp = reflect.TypeOf([]int(nil))
+ int8SliceTyp = reflect.TypeOf([]int8(nil))
+ int16SliceTyp = reflect.TypeOf([]int16(nil))
+ int32SliceTyp = reflect.TypeOf([]int32(nil))
+ int64SliceTyp = reflect.TypeOf([]int64(nil))
+ float32SliceTyp = reflect.TypeOf([]float32(nil))
+ float64SliceTyp = reflect.TypeOf([]float64(nil))
+
+ mapIntfIntfTyp = reflect.TypeOf(map[interface{}]interface{}(nil))
+ mapStrIntfTyp = reflect.TypeOf(map[string]interface{}(nil))
+ mapStrStrTyp = reflect.TypeOf(map[string]string(nil))
+
+ mapIntIntfTyp = reflect.TypeOf(map[int]interface{}(nil))
+ mapInt64IntfTyp = reflect.TypeOf(map[int64]interface{}(nil))
+ mapUintIntfTyp = reflect.TypeOf(map[uint]interface{}(nil))
+ mapUint64IntfTyp = reflect.TypeOf(map[uint64]interface{}(nil))
+
+ stringTyp = reflect.TypeOf("")
+ timeTyp = reflect.TypeOf(time.Time{})
+ rawExtTyp = reflect.TypeOf(RawExt{})
+
+ mapBySliceTyp = reflect.TypeOf((*MapBySlice)(nil)).Elem()
+ binaryMarshalerTyp = reflect.TypeOf((*binaryMarshaler)(nil)).Elem()
+ binaryUnmarshalerTyp = reflect.TypeOf((*binaryUnmarshaler)(nil)).Elem()
+
+ rawExtTypId = reflect.ValueOf(rawExtTyp).Pointer()
+ intfTypId = reflect.ValueOf(intfTyp).Pointer()
+ timeTypId = reflect.ValueOf(timeTyp).Pointer()
+
+ intfSliceTypId = reflect.ValueOf(intfSliceTyp).Pointer()
+ strSliceTypId = reflect.ValueOf(strSliceTyp).Pointer()
+
+ boolSliceTypId = reflect.ValueOf(boolSliceTyp).Pointer()
+ uintSliceTypId = reflect.ValueOf(uintSliceTyp).Pointer()
+ uint8SliceTypId = reflect.ValueOf(uint8SliceTyp).Pointer()
+ uint16SliceTypId = reflect.ValueOf(uint16SliceTyp).Pointer()
+ uint32SliceTypId = reflect.ValueOf(uint32SliceTyp).Pointer()
+ uint64SliceTypId = reflect.ValueOf(uint64SliceTyp).Pointer()
+ intSliceTypId = reflect.ValueOf(intSliceTyp).Pointer()
+ int8SliceTypId = reflect.ValueOf(int8SliceTyp).Pointer()
+ int16SliceTypId = reflect.ValueOf(int16SliceTyp).Pointer()
+ int32SliceTypId = reflect.ValueOf(int32SliceTyp).Pointer()
+ int64SliceTypId = reflect.ValueOf(int64SliceTyp).Pointer()
+ float32SliceTypId = reflect.ValueOf(float32SliceTyp).Pointer()
+ float64SliceTypId = reflect.ValueOf(float64SliceTyp).Pointer()
+
+ mapStrStrTypId = reflect.ValueOf(mapStrStrTyp).Pointer()
+ mapIntfIntfTypId = reflect.ValueOf(mapIntfIntfTyp).Pointer()
+ mapStrIntfTypId = reflect.ValueOf(mapStrIntfTyp).Pointer()
+ mapIntIntfTypId = reflect.ValueOf(mapIntIntfTyp).Pointer()
+ mapInt64IntfTypId = reflect.ValueOf(mapInt64IntfTyp).Pointer()
+ mapUintIntfTypId = reflect.ValueOf(mapUintIntfTyp).Pointer()
+ mapUint64IntfTypId = reflect.ValueOf(mapUint64IntfTyp).Pointer()
+ // Id = reflect.ValueOf().Pointer()
+ // mapBySliceTypId = reflect.ValueOf(mapBySliceTyp).Pointer()
+
+ binaryMarshalerTypId = reflect.ValueOf(binaryMarshalerTyp).Pointer()
+ binaryUnmarshalerTypId = reflect.ValueOf(binaryUnmarshalerTyp).Pointer()
+
+ intBitsize uint8 = uint8(reflect.TypeOf(int(0)).Bits())
+ uintBitsize uint8 = uint8(reflect.TypeOf(uint(0)).Bits())
+
+ bsAll0x00 = []byte{0, 0, 0, 0, 0, 0, 0, 0}
+ bsAll0xff = []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
+)
+
+type binaryUnmarshaler interface {
+ UnmarshalBinary(data []byte) error
+}
+
+type binaryMarshaler interface {
+ MarshalBinary() (data []byte, err error)
+}
+
+// MapBySlice represents a slice which should be encoded as a map in the stream.
+// The slice contains a sequence of key-value pairs.
+type MapBySlice interface {
+ MapBySlice()
+}
+
+// WARNING: DO NOT USE DIRECTLY. EXPORTED FOR GODOC BENEFIT. WILL BE REMOVED.
+//
+// BasicHandle encapsulates the common options and extension functions.
+type BasicHandle struct {
+ extHandle
+ EncodeOptions
+ DecodeOptions
+}
+
+// Handle is the interface for a specific encoding format.
+//
+// Typically, a Handle is pre-configured before first time use,
+// and not modified while in use. Such a pre-configured Handle
+// is safe for concurrent access.
+type Handle interface {
+ writeExt() bool
+ getBasicHandle() *BasicHandle
+ newEncDriver(w encWriter) encDriver
+ newDecDriver(r decReader) decDriver
+}
+
+// RawExt represents raw unprocessed extension data.
+type RawExt struct {
+ Tag byte
+ Data []byte
+}
+
+type extTypeTagFn struct {
+ rtid uintptr
+ rt reflect.Type
+ tag byte
+ encFn func(reflect.Value) ([]byte, error)
+ decFn func(reflect.Value, []byte) error
+}
+
+type extHandle []*extTypeTagFn
+
+// AddExt registers an encode and decode function for a reflect.Type.
+// Note that the type must be a named type, and specifically not
+// a pointer or Interface. An error is returned if that is not honored.
+//
+// To Deregister an ext, call AddExt with 0 tag, nil encfn and nil decfn.
+func (o *extHandle) AddExt(
+ rt reflect.Type,
+ tag byte,
+ encfn func(reflect.Value) ([]byte, error),
+ decfn func(reflect.Value, []byte) error,
+) (err error) {
+ // o is a pointer, because we may need to initialize it
+ if rt.PkgPath() == "" || rt.Kind() == reflect.Interface {
+ err = fmt.Errorf("codec.Handle.AddExt: Takes named type, especially not a pointer or interface: %T",
+ reflect.Zero(rt).Interface())
+ return
+ }
+
+ // o cannot be nil, since it is always embedded in a Handle.
+ // if nil, let it panic.
+ // if o == nil {
+ // err = errors.New("codec.Handle.AddExt: extHandle cannot be a nil pointer.")
+ // return
+ // }
+
+ rtid := reflect.ValueOf(rt).Pointer()
+ for _, v := range *o {
+ if v.rtid == rtid {
+ v.tag, v.encFn, v.decFn = tag, encfn, decfn
+ return
+ }
+ }
+
+ *o = append(*o, &extTypeTagFn{rtid, rt, tag, encfn, decfn})
+ return
+}
+
+func (o extHandle) getExt(rtid uintptr) *extTypeTagFn {
+ for _, v := range o {
+ if v.rtid == rtid {
+ return v
+ }
+ }
+ return nil
+}
+
+func (o extHandle) getExtForTag(tag byte) *extTypeTagFn {
+ for _, v := range o {
+ if v.tag == tag {
+ return v
+ }
+ }
+ return nil
+}
+
+func (o extHandle) getDecodeExtForTag(tag byte) (
+ rv reflect.Value, fn func(reflect.Value, []byte) error) {
+ if x := o.getExtForTag(tag); x != nil {
+ // ext is only registered for base
+ rv = reflect.New(x.rt).Elem()
+ fn = x.decFn
+ }
+ return
+}
+
+func (o extHandle) getDecodeExt(rtid uintptr) (tag byte, fn func(reflect.Value, []byte) error) {
+ if x := o.getExt(rtid); x != nil {
+ tag = x.tag
+ fn = x.decFn
+ }
+ return
+}
+
+func (o extHandle) getEncodeExt(rtid uintptr) (tag byte, fn func(reflect.Value) ([]byte, error)) {
+ if x := o.getExt(rtid); x != nil {
+ tag = x.tag
+ fn = x.encFn
+ }
+ return
+}
+
+type structFieldInfo struct {
+ encName string // encode name
+
+ // only one of 'i' or 'is' can be set. If 'i' is -1, then 'is' has been set.
+
+ is []int // (recursive/embedded) field index in struct
+ i int16 // field index in struct
+ omitEmpty bool
+ toArray bool // if field is _struct, is the toArray set?
+
+ // tag string // tag
+ // name string // field name
+ // encNameBs []byte // encoded name as byte stream
+ // ikind int // kind of the field as an int i.e. int(reflect.Kind)
+}
+
+func parseStructFieldInfo(fname string, stag string) *structFieldInfo {
+ if fname == "" {
+ panic("parseStructFieldInfo: No Field Name")
+ }
+ si := structFieldInfo{
+ // name: fname,
+ encName: fname,
+ // tag: stag,
+ }
+
+ if stag != "" {
+ for i, s := range strings.Split(stag, ",") {
+ if i == 0 {
+ if s != "" {
+ si.encName = s
+ }
+ } else {
+ switch s {
+ case "omitempty":
+ si.omitEmpty = true
+ case "toarray":
+ si.toArray = true
+ }
+ }
+ }
+ }
+ // si.encNameBs = []byte(si.encName)
+ return &si
+}
+
+type sfiSortedByEncName []*structFieldInfo
+
+func (p sfiSortedByEncName) Len() int {
+ return len(p)
+}
+
+func (p sfiSortedByEncName) Less(i, j int) bool {
+ return p[i].encName < p[j].encName
+}
+
+func (p sfiSortedByEncName) Swap(i, j int) {
+ p[i], p[j] = p[j], p[i]
+}
+
+// typeInfo keeps information about each type referenced in the encode/decode sequence.
+//
+// During an encode/decode sequence, we work as below:
+// - If base is a built in type, en/decode base value
+// - If base is registered as an extension, en/decode base value
+// - If type is binary(M/Unm)arshaler, call Binary(M/Unm)arshal method
+// - Else decode appropriately based on the reflect.Kind
+type typeInfo struct {
+ sfi []*structFieldInfo // sorted. Used when enc/dec struct to map.
+ sfip []*structFieldInfo // unsorted. Used when enc/dec struct to array.
+
+ rt reflect.Type
+ rtid uintptr
+
+ // baseId gives pointer to the base reflect.Type, after deferencing
+ // the pointers. E.g. base type of ***time.Time is time.Time.
+ base reflect.Type
+ baseId uintptr
+ baseIndir int8 // number of indirections to get to base
+
+ mbs bool // base type (T or *T) is a MapBySlice
+
+ m bool // base type (T or *T) is a binaryMarshaler
+ unm bool // base type (T or *T) is a binaryUnmarshaler
+ mIndir int8 // number of indirections to get to binaryMarshaler type
+ unmIndir int8 // number of indirections to get to binaryUnmarshaler type
+ toArray bool // whether this (struct) type should be encoded as an array
+}
+
+func (ti *typeInfo) indexForEncName(name string) int {
+ //tisfi := ti.sfi
+ const binarySearchThreshold = 16
+ if sfilen := len(ti.sfi); sfilen < binarySearchThreshold {
+ // linear search. faster than binary search in my testing up to 16-field structs.
+ for i, si := range ti.sfi {
+ if si.encName == name {
+ return i
+ }
+ }
+ } else {
+ // binary search. adapted from sort/search.go.
+ h, i, j := 0, 0, sfilen
+ for i < j {
+ h = i + (j-i)/2
+ if ti.sfi[h].encName < name {
+ i = h + 1
+ } else {
+ j = h
+ }
+ }
+ if i < sfilen && ti.sfi[i].encName == name {
+ return i
+ }
+ }
+ return -1
+}
+
+func getTypeInfo(rtid uintptr, rt reflect.Type) (pti *typeInfo) {
+ var ok bool
+ cachedTypeInfoMutex.RLock()
+ pti, ok = cachedTypeInfo[rtid]
+ cachedTypeInfoMutex.RUnlock()
+ if ok {
+ return
+ }
+
+ cachedTypeInfoMutex.Lock()
+ defer cachedTypeInfoMutex.Unlock()
+ if pti, ok = cachedTypeInfo[rtid]; ok {
+ return
+ }
+
+ ti := typeInfo{rt: rt, rtid: rtid}
+ pti = &ti
+
+ var indir int8
+ if ok, indir = implementsIntf(rt, binaryMarshalerTyp); ok {
+ ti.m, ti.mIndir = true, indir
+ }
+ if ok, indir = implementsIntf(rt, binaryUnmarshalerTyp); ok {
+ ti.unm, ti.unmIndir = true, indir
+ }
+ if ok, _ = implementsIntf(rt, mapBySliceTyp); ok {
+ ti.mbs = true
+ }
+
+ pt := rt
+ var ptIndir int8
+ // for ; pt.Kind() == reflect.Ptr; pt, ptIndir = pt.Elem(), ptIndir+1 { }
+ for pt.Kind() == reflect.Ptr {
+ pt = pt.Elem()
+ ptIndir++
+ }
+ if ptIndir == 0 {
+ ti.base = rt
+ ti.baseId = rtid
+ } else {
+ ti.base = pt
+ ti.baseId = reflect.ValueOf(pt).Pointer()
+ ti.baseIndir = ptIndir
+ }
+
+ if rt.Kind() == reflect.Struct {
+ var siInfo *structFieldInfo
+ if f, ok := rt.FieldByName(structInfoFieldName); ok {
+ siInfo = parseStructFieldInfo(structInfoFieldName, f.Tag.Get(structTagName))
+ ti.toArray = siInfo.toArray
+ }
+ sfip := make([]*structFieldInfo, 0, rt.NumField())
+ rgetTypeInfo(rt, nil, make(map[string]bool), &sfip, siInfo)
+
+ // // try to put all si close together
+ // const tryToPutAllStructFieldInfoTogether = true
+ // if tryToPutAllStructFieldInfoTogether {
+ // sfip2 := make([]structFieldInfo, len(sfip))
+ // for i, si := range sfip {
+ // sfip2[i] = *si
+ // }
+ // for i := range sfip {
+ // sfip[i] = &sfip2[i]
+ // }
+ // }
+
+ ti.sfip = make([]*structFieldInfo, len(sfip))
+ ti.sfi = make([]*structFieldInfo, len(sfip))
+ copy(ti.sfip, sfip)
+ sort.Sort(sfiSortedByEncName(sfip))
+ copy(ti.sfi, sfip)
+ }
+ // sfi = sfip
+ cachedTypeInfo[rtid] = pti
+ return
+}
+
+func rgetTypeInfo(rt reflect.Type, indexstack []int, fnameToHastag map[string]bool,
+ sfi *[]*structFieldInfo, siInfo *structFieldInfo,
+) {
+ // for rt.Kind() == reflect.Ptr {
+ // // indexstack = append(indexstack, 0)
+ // rt = rt.Elem()
+ // }
+ for j := 0; j < rt.NumField(); j++ {
+ f := rt.Field(j)
+ stag := f.Tag.Get(structTagName)
+ if stag == "-" {
+ continue
+ }
+ if r1, _ := utf8.DecodeRuneInString(f.Name); r1 == utf8.RuneError || !unicode.IsUpper(r1) {
+ continue
+ }
+ // if anonymous and there is no struct tag and its a struct (or pointer to struct), inline it.
+ if f.Anonymous && stag == "" {
+ ft := f.Type
+ for ft.Kind() == reflect.Ptr {
+ ft = ft.Elem()
+ }
+ if ft.Kind() == reflect.Struct {
+ indexstack2 := append(append(make([]int, 0, len(indexstack)+4), indexstack...), j)
+ rgetTypeInfo(ft, indexstack2, fnameToHastag, sfi, siInfo)
+ continue
+ }
+ }
+ // do not let fields with same name in embedded structs override field at higher level.
+ // this must be done after anonymous check, to allow anonymous field
+ // still include their child fields
+ if _, ok := fnameToHastag[f.Name]; ok {
+ continue
+ }
+ si := parseStructFieldInfo(f.Name, stag)
+ // si.ikind = int(f.Type.Kind())
+ if len(indexstack) == 0 {
+ si.i = int16(j)
+ } else {
+ si.i = -1
+ si.is = append(append(make([]int, 0, len(indexstack)+4), indexstack...), j)
+ }
+
+ if siInfo != nil {
+ if siInfo.omitEmpty {
+ si.omitEmpty = true
+ }
+ }
+ *sfi = append(*sfi, si)
+ fnameToHastag[f.Name] = stag != ""
+ }
+}
+
+func panicToErr(err *error) {
+ if recoverPanicToErr {
+ if x := recover(); x != nil {
+ //debug.PrintStack()
+ panicValToErr(x, err)
+ }
+ }
+}
+
+func doPanic(tag string, format string, params ...interface{}) {
+ params2 := make([]interface{}, len(params)+1)
+ params2[0] = tag
+ copy(params2[1:], params)
+ panic(fmt.Errorf("%s: "+format, params2...))
+}
+
+func checkOverflowFloat32(f float64, doCheck bool) {
+ if !doCheck {
+ return
+ }
+ // check overflow (logic adapted from std pkg reflect/value.go OverflowFloat()
+ f2 := f
+ if f2 < 0 {
+ f2 = -f
+ }
+ if math.MaxFloat32 < f2 && f2 <= math.MaxFloat64 {
+ decErr("Overflow float32 value: %v", f2)
+ }
+}
+
+func checkOverflow(ui uint64, i int64, bitsize uint8) {
+ // check overflow (logic adapted from std pkg reflect/value.go OverflowUint()
+ if bitsize == 0 {
+ return
+ }
+ if i != 0 {
+ if trunc := (i << (64 - bitsize)) >> (64 - bitsize); i != trunc {
+ decErr("Overflow int value: %v", i)
+ }
+ }
+ if ui != 0 {
+ if trunc := (ui << (64 - bitsize)) >> (64 - bitsize); ui != trunc {
+ decErr("Overflow uint value: %v", ui)
+ }
+ }
+}
diff -Naur --color b/vendor/github.com/hashicorp/go-msgpack/codec/helper_internal.go a/vendor/github.com/hashicorp/go-msgpack/codec/helper_internal.go
--- b/vendor/github.com/hashicorp/go-msgpack/codec/helper_internal.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-msgpack/codec/helper_internal.go 2022-11-15 23:06:31.555391002 +0100
@@ -0,0 +1,132 @@
+// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved.
+// Use of this source code is governed by a BSD-style license found in the LICENSE file.
+
+package codec
+
+// All non-std package dependencies live in this file,
+// so porting to different environment is easy (just update functions).
+
+import (
+ "errors"
+ "fmt"
+ "math"
+ "reflect"
+)
+
+var (
+ raisePanicAfterRecover = false
+ debugging = true
+)
+
+func panicValToErr(panicVal interface{}, err *error) {
+ switch xerr := panicVal.(type) {
+ case error:
+ *err = xerr
+ case string:
+ *err = errors.New(xerr)
+ default:
+ *err = fmt.Errorf("%v", panicVal)
+ }
+ if raisePanicAfterRecover {
+ panic(panicVal)
+ }
+ return
+}
+
+func hIsEmptyValue(v reflect.Value, deref, checkStruct bool) bool {
+ switch v.Kind() {
+ case reflect.Invalid:
+ return true
+ case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
+ return v.Len() == 0
+ case reflect.Bool:
+ return !v.Bool()
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+ return v.Int() == 0
+ case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
+ return v.Uint() == 0
+ case reflect.Float32, reflect.Float64:
+ return v.Float() == 0
+ case reflect.Interface, reflect.Ptr:
+ if deref {
+ if v.IsNil() {
+ return true
+ }
+ return hIsEmptyValue(v.Elem(), deref, checkStruct)
+ } else {
+ return v.IsNil()
+ }
+ case reflect.Struct:
+ if !checkStruct {
+ return false
+ }
+ // return true if all fields are empty. else return false.
+
+ // we cannot use equality check, because some fields may be maps/slices/etc
+ // and consequently the structs are not comparable.
+ // return v.Interface() == reflect.Zero(v.Type()).Interface()
+ for i, n := 0, v.NumField(); i < n; i++ {
+ if !hIsEmptyValue(v.Field(i), deref, checkStruct) {
+ return false
+ }
+ }
+ return true
+ }
+ return false
+}
+
+func isEmptyValue(v reflect.Value) bool {
+ return hIsEmptyValue(v, derefForIsEmptyValue, checkStructForEmptyValue)
+}
+
+func debugf(format string, args ...interface{}) {
+ if debugging {
+ if len(format) == 0 || format[len(format)-1] != '\n' {
+ format = format + "\n"
+ }
+ fmt.Printf(format, args...)
+ }
+}
+
+func pruneSignExt(v []byte, pos bool) (n int) {
+ if len(v) < 2 {
+ } else if pos && v[0] == 0 {
+ for ; v[n] == 0 && n+1 < len(v) && (v[n+1]&(1<<7) == 0); n++ {
+ }
+ } else if !pos && v[0] == 0xff {
+ for ; v[n] == 0xff && n+1 < len(v) && (v[n+1]&(1<<7) != 0); n++ {
+ }
+ }
+ return
+}
+
+func implementsIntf(typ, iTyp reflect.Type) (success bool, indir int8) {
+ if typ == nil {
+ return
+ }
+ rt := typ
+ // The type might be a pointer and we need to keep
+ // dereferencing to the base type until we find an implementation.
+ for {
+ if rt.Implements(iTyp) {
+ return true, indir
+ }
+ if p := rt; p.Kind() == reflect.Ptr {
+ indir++
+ if indir >= math.MaxInt8 { // insane number of indirections
+ return false, 0
+ }
+ rt = p.Elem()
+ continue
+ }
+ break
+ }
+ // No luck yet, but if this is a base type (non-pointer), the pointer might satisfy.
+ if typ.Kind() != reflect.Ptr {
+ // Not a pointer, but does the pointer work?
+ if reflect.PtrTo(typ).Implements(iTyp) {
+ return true, -1
+ }
+ }
+ return false, 0
+}
diff -Naur --color b/vendor/github.com/hashicorp/go-msgpack/codec/msgpack.go a/vendor/github.com/hashicorp/go-msgpack/codec/msgpack.go
--- b/vendor/github.com/hashicorp/go-msgpack/codec/msgpack.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-msgpack/codec/msgpack.go 2022-11-15 23:06:31.555391002 +0100
@@ -0,0 +1,816 @@
+// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved.
+// Use of this source code is governed by a BSD-style license found in the LICENSE file.
+
+/*
+MSGPACK
+
+Msgpack-c implementation powers the c, c++, python, ruby, etc libraries.
+We need to maintain compatibility with it and how it encodes integer values
+without caring about the type.
+
+For compatibility with behaviour of msgpack-c reference implementation:
+ - Go intX (>0) and uintX
+ IS ENCODED AS
+ msgpack +ve fixnum, unsigned
+ - Go intX (<0)
+ IS ENCODED AS
+ msgpack -ve fixnum, signed
+
+*/
+package codec
+
+import (
+ "fmt"
+ "io"
+ "math"
+ "net/rpc"
+)
+
+const (
+ mpPosFixNumMin byte = 0x00
+ mpPosFixNumMax = 0x7f
+ mpFixMapMin = 0x80
+ mpFixMapMax = 0x8f
+ mpFixArrayMin = 0x90
+ mpFixArrayMax = 0x9f
+ mpFixStrMin = 0xa0
+ mpFixStrMax = 0xbf
+ mpNil = 0xc0
+ _ = 0xc1
+ mpFalse = 0xc2
+ mpTrue = 0xc3
+ mpFloat = 0xca
+ mpDouble = 0xcb
+ mpUint8 = 0xcc
+ mpUint16 = 0xcd
+ mpUint32 = 0xce
+ mpUint64 = 0xcf
+ mpInt8 = 0xd0
+ mpInt16 = 0xd1
+ mpInt32 = 0xd2
+ mpInt64 = 0xd3
+
+ // extensions below
+ mpBin8 = 0xc4
+ mpBin16 = 0xc5
+ mpBin32 = 0xc6
+ mpExt8 = 0xc7
+ mpExt16 = 0xc8
+ mpExt32 = 0xc9
+ mpFixExt1 = 0xd4
+ mpFixExt2 = 0xd5
+ mpFixExt4 = 0xd6
+ mpFixExt8 = 0xd7
+ mpFixExt16 = 0xd8
+
+ mpStr8 = 0xd9 // new
+ mpStr16 = 0xda
+ mpStr32 = 0xdb
+
+ mpArray16 = 0xdc
+ mpArray32 = 0xdd
+
+ mpMap16 = 0xde
+ mpMap32 = 0xdf
+
+ mpNegFixNumMin = 0xe0
+ mpNegFixNumMax = 0xff
+)
+
+// MsgpackSpecRpcMultiArgs is a special type which signifies to the MsgpackSpecRpcCodec
+// that the backend RPC service takes multiple arguments, which have been arranged
+// in sequence in the slice.
+//
+// The Codec then passes it AS-IS to the rpc service (without wrapping it in an
+// array of 1 element).
+type MsgpackSpecRpcMultiArgs []interface{}
+
+// A MsgpackContainer type specifies the different types of msgpackContainers.
+type msgpackContainerType struct {
+ fixCutoff int
+ bFixMin, b8, b16, b32 byte
+ hasFixMin, has8, has8Always bool
+}
+
+var (
+ msgpackContainerStr = msgpackContainerType{32, mpFixStrMin, mpStr8, mpStr16, mpStr32, true, true, false}
+ msgpackContainerBin = msgpackContainerType{0, 0, mpBin8, mpBin16, mpBin32, false, true, true}
+ msgpackContainerList = msgpackContainerType{16, mpFixArrayMin, 0, mpArray16, mpArray32, true, false, false}
+ msgpackContainerMap = msgpackContainerType{16, mpFixMapMin, 0, mpMap16, mpMap32, true, false, false}
+)
+
+//---------------------------------------------
+
+type msgpackEncDriver struct {
+ w encWriter
+ h *MsgpackHandle
+}
+
+func (e *msgpackEncDriver) isBuiltinType(rt uintptr) bool {
+ //no builtin types. All encodings are based on kinds. Types supported as extensions.
+ return false
+}
+
+func (e *msgpackEncDriver) encodeBuiltin(rt uintptr, v interface{}) {}
+
+func (e *msgpackEncDriver) encodeNil() {
+ e.w.writen1(mpNil)
+}
+
+func (e *msgpackEncDriver) encodeInt(i int64) {
+
+ switch {
+ case i >= 0:
+ e.encodeUint(uint64(i))
+ case i >= -32:
+ e.w.writen1(byte(i))
+ case i >= math.MinInt8:
+ e.w.writen2(mpInt8, byte(i))
+ case i >= math.MinInt16:
+ e.w.writen1(mpInt16)
+ e.w.writeUint16(uint16(i))
+ case i >= math.MinInt32:
+ e.w.writen1(mpInt32)
+ e.w.writeUint32(uint32(i))
+ default:
+ e.w.writen1(mpInt64)
+ e.w.writeUint64(uint64(i))
+ }
+}
+
+func (e *msgpackEncDriver) encodeUint(i uint64) {
+ switch {
+ case i <= math.MaxInt8:
+ e.w.writen1(byte(i))
+ case i <= math.MaxUint8:
+ e.w.writen2(mpUint8, byte(i))
+ case i <= math.MaxUint16:
+ e.w.writen1(mpUint16)
+ e.w.writeUint16(uint16(i))
+ case i <= math.MaxUint32:
+ e.w.writen1(mpUint32)
+ e.w.writeUint32(uint32(i))
+ default:
+ e.w.writen1(mpUint64)
+ e.w.writeUint64(uint64(i))
+ }
+}
+
+func (e *msgpackEncDriver) encodeBool(b bool) {
+ if b {
+ e.w.writen1(mpTrue)
+ } else {
+ e.w.writen1(mpFalse)
+ }
+}
+
+func (e *msgpackEncDriver) encodeFloat32(f float32) {
+ e.w.writen1(mpFloat)
+ e.w.writeUint32(math.Float32bits(f))
+}
+
+func (e *msgpackEncDriver) encodeFloat64(f float64) {
+ e.w.writen1(mpDouble)
+ e.w.writeUint64(math.Float64bits(f))
+}
+
+func (e *msgpackEncDriver) encodeExtPreamble(xtag byte, l int) {
+ switch {
+ case l == 1:
+ e.w.writen2(mpFixExt1, xtag)
+ case l == 2:
+ e.w.writen2(mpFixExt2, xtag)
+ case l == 4:
+ e.w.writen2(mpFixExt4, xtag)
+ case l == 8:
+ e.w.writen2(mpFixExt8, xtag)
+ case l == 16:
+ e.w.writen2(mpFixExt16, xtag)
+ case l < 256:
+ e.w.writen2(mpExt8, byte(l))
+ e.w.writen1(xtag)
+ case l < 65536:
+ e.w.writen1(mpExt16)
+ e.w.writeUint16(uint16(l))
+ e.w.writen1(xtag)
+ default:
+ e.w.writen1(mpExt32)
+ e.w.writeUint32(uint32(l))
+ e.w.writen1(xtag)
+ }
+}
+
+func (e *msgpackEncDriver) encodeArrayPreamble(length int) {
+ e.writeContainerLen(msgpackContainerList, length)
+}
+
+func (e *msgpackEncDriver) encodeMapPreamble(length int) {
+ e.writeContainerLen(msgpackContainerMap, length)
+}
+
+func (e *msgpackEncDriver) encodeString(c charEncoding, s string) {
+ if c == c_RAW && e.h.WriteExt {
+ e.writeContainerLen(msgpackContainerBin, len(s))
+ } else {
+ e.writeContainerLen(msgpackContainerStr, len(s))
+ }
+ if len(s) > 0 {
+ e.w.writestr(s)
+ }
+}
+
+func (e *msgpackEncDriver) encodeSymbol(v string) {
+ e.encodeString(c_UTF8, v)
+}
+
+func (e *msgpackEncDriver) encodeStringBytes(c charEncoding, bs []byte) {
+ if c == c_RAW && e.h.WriteExt {
+ e.writeContainerLen(msgpackContainerBin, len(bs))
+ } else {
+ e.writeContainerLen(msgpackContainerStr, len(bs))
+ }
+ if len(bs) > 0 {
+ e.w.writeb(bs)
+ }
+}
+
+func (e *msgpackEncDriver) writeContainerLen(ct msgpackContainerType, l int) {
+ switch {
+ case ct.hasFixMin && l < ct.fixCutoff:
+ e.w.writen1(ct.bFixMin | byte(l))
+ case ct.has8 && l < 256 && (ct.has8Always || e.h.WriteExt):
+ e.w.writen2(ct.b8, uint8(l))
+ case l < 65536:
+ e.w.writen1(ct.b16)
+ e.w.writeUint16(uint16(l))
+ default:
+ e.w.writen1(ct.b32)
+ e.w.writeUint32(uint32(l))
+ }
+}
+
+//---------------------------------------------
+
+type msgpackDecDriver struct {
+ r decReader
+ h *MsgpackHandle
+ bd byte
+ bdRead bool
+ bdType valueType
+}
+
+func (d *msgpackDecDriver) isBuiltinType(rt uintptr) bool {
+ //no builtin types. All encodings are based on kinds. Types supported as extensions.
+ return false
+}
+
+func (d *msgpackDecDriver) decodeBuiltin(rt uintptr, v interface{}) {}
+
+// Note: This returns either a primitive (int, bool, etc) for non-containers,
+// or a containerType, or a specific type denoting nil or extension.
+// It is called when a nil interface{} is passed, leaving it up to the DecDriver
+// to introspect the stream and decide how best to decode.
+// It deciphers the value by looking at the stream first.
+func (d *msgpackDecDriver) decodeNaked() (v interface{}, vt valueType, decodeFurther bool) {
+ d.initReadNext()
+ bd := d.bd
+
+ switch bd {
+ case mpNil:
+ vt = valueTypeNil
+ d.bdRead = false
+ case mpFalse:
+ vt = valueTypeBool
+ v = false
+ case mpTrue:
+ vt = valueTypeBool
+ v = true
+
+ case mpFloat:
+ vt = valueTypeFloat
+ v = float64(math.Float32frombits(d.r.readUint32()))
+ case mpDouble:
+ vt = valueTypeFloat
+ v = math.Float64frombits(d.r.readUint64())
+
+ case mpUint8:
+ vt = valueTypeUint
+ v = uint64(d.r.readn1())
+ case mpUint16:
+ vt = valueTypeUint
+ v = uint64(d.r.readUint16())
+ case mpUint32:
+ vt = valueTypeUint
+ v = uint64(d.r.readUint32())
+ case mpUint64:
+ vt = valueTypeUint
+ v = uint64(d.r.readUint64())
+
+ case mpInt8:
+ vt = valueTypeInt
+ v = int64(int8(d.r.readn1()))
+ case mpInt16:
+ vt = valueTypeInt
+ v = int64(int16(d.r.readUint16()))
+ case mpInt32:
+ vt = valueTypeInt
+ v = int64(int32(d.r.readUint32()))
+ case mpInt64:
+ vt = valueTypeInt
+ v = int64(int64(d.r.readUint64()))
+
+ default:
+ switch {
+ case bd >= mpPosFixNumMin && bd <= mpPosFixNumMax:
+ // positive fixnum (always signed)
+ vt = valueTypeInt
+ v = int64(int8(bd))
+ case bd >= mpNegFixNumMin && bd <= mpNegFixNumMax:
+ // negative fixnum
+ vt = valueTypeInt
+ v = int64(int8(bd))
+ case bd == mpStr8, bd == mpStr16, bd == mpStr32, bd >= mpFixStrMin && bd <= mpFixStrMax:
+ if d.h.RawToString {
+ var rvm string
+ vt = valueTypeString
+ v = &rvm
+ } else {
+ var rvm = []byte{}
+ vt = valueTypeBytes
+ v = &rvm
+ }
+ decodeFurther = true
+ case bd == mpBin8, bd == mpBin16, bd == mpBin32:
+ var rvm = []byte{}
+ vt = valueTypeBytes
+ v = &rvm
+ decodeFurther = true
+ case bd == mpArray16, bd == mpArray32, bd >= mpFixArrayMin && bd <= mpFixArrayMax:
+ vt = valueTypeArray
+ decodeFurther = true
+ case bd == mpMap16, bd == mpMap32, bd >= mpFixMapMin && bd <= mpFixMapMax:
+ vt = valueTypeMap
+ decodeFurther = true
+ case bd >= mpFixExt1 && bd <= mpFixExt16, bd >= mpExt8 && bd <= mpExt32:
+ clen := d.readExtLen()
+ var re RawExt
+ re.Tag = d.r.readn1()
+ re.Data = d.r.readn(clen)
+ v = &re
+ vt = valueTypeExt
+ default:
+ decErr("Nil-Deciphered DecodeValue: %s: hex: %x, dec: %d", msgBadDesc, bd, bd)
+ }
+ }
+ if !decodeFurther {
+ d.bdRead = false
+ }
+ return
+}
+
+// int can be decoded from msgpack type: intXXX or uintXXX
+func (d *msgpackDecDriver) decodeInt(bitsize uint8) (i int64) {
+ switch d.bd {
+ case mpUint8:
+ i = int64(uint64(d.r.readn1()))
+ case mpUint16:
+ i = int64(uint64(d.r.readUint16()))
+ case mpUint32:
+ i = int64(uint64(d.r.readUint32()))
+ case mpUint64:
+ i = int64(d.r.readUint64())
+ case mpInt8:
+ i = int64(int8(d.r.readn1()))
+ case mpInt16:
+ i = int64(int16(d.r.readUint16()))
+ case mpInt32:
+ i = int64(int32(d.r.readUint32()))
+ case mpInt64:
+ i = int64(d.r.readUint64())
+ default:
+ switch {
+ case d.bd >= mpPosFixNumMin && d.bd <= mpPosFixNumMax:
+ i = int64(int8(d.bd))
+ case d.bd >= mpNegFixNumMin && d.bd <= mpNegFixNumMax:
+ i = int64(int8(d.bd))
+ default:
+ decErr("Unhandled single-byte unsigned integer value: %s: %x", msgBadDesc, d.bd)
+ }
+ }
+ // check overflow (logic adapted from std pkg reflect/value.go OverflowUint()
+ if bitsize > 0 {
+ if trunc := (i << (64 - bitsize)) >> (64 - bitsize); i != trunc {
+ decErr("Overflow int value: %v", i)
+ }
+ }
+ d.bdRead = false
+ return
+}
+
+// uint can be decoded from msgpack type: intXXX or uintXXX
+func (d *msgpackDecDriver) decodeUint(bitsize uint8) (ui uint64) {
+ switch d.bd {
+ case mpUint8:
+ ui = uint64(d.r.readn1())
+ case mpUint16:
+ ui = uint64(d.r.readUint16())
+ case mpUint32:
+ ui = uint64(d.r.readUint32())
+ case mpUint64:
+ ui = d.r.readUint64()
+ case mpInt8:
+ if i := int64(int8(d.r.readn1())); i >= 0 {
+ ui = uint64(i)
+ } else {
+ decErr("Assigning negative signed value: %v, to unsigned type", i)
+ }
+ case mpInt16:
+ if i := int64(int16(d.r.readUint16())); i >= 0 {
+ ui = uint64(i)
+ } else {
+ decErr("Assigning negative signed value: %v, to unsigned type", i)
+ }
+ case mpInt32:
+ if i := int64(int32(d.r.readUint32())); i >= 0 {
+ ui = uint64(i)
+ } else {
+ decErr("Assigning negative signed value: %v, to unsigned type", i)
+ }
+ case mpInt64:
+ if i := int64(d.r.readUint64()); i >= 0 {
+ ui = uint64(i)
+ } else {
+ decErr("Assigning negative signed value: %v, to unsigned type", i)
+ }
+ default:
+ switch {
+ case d.bd >= mpPosFixNumMin && d.bd <= mpPosFixNumMax:
+ ui = uint64(d.bd)
+ case d.bd >= mpNegFixNumMin && d.bd <= mpNegFixNumMax:
+ decErr("Assigning negative signed value: %v, to unsigned type", int(d.bd))
+ default:
+ decErr("Unhandled single-byte unsigned integer value: %s: %x", msgBadDesc, d.bd)
+ }
+ }
+ // check overflow (logic adapted from std pkg reflect/value.go OverflowUint()
+ if bitsize > 0 {
+ if trunc := (ui << (64 - bitsize)) >> (64 - bitsize); ui != trunc {
+ decErr("Overflow uint value: %v", ui)
+ }
+ }
+ d.bdRead = false
+ return
+}
+
+// float can either be decoded from msgpack type: float, double or intX
+func (d *msgpackDecDriver) decodeFloat(chkOverflow32 bool) (f float64) {
+ switch d.bd {
+ case mpFloat:
+ f = float64(math.Float32frombits(d.r.readUint32()))
+ case mpDouble:
+ f = math.Float64frombits(d.r.readUint64())
+ default:
+ f = float64(d.decodeInt(0))
+ }
+ checkOverflowFloat32(f, chkOverflow32)
+ d.bdRead = false
+ return
+}
+
+// bool can be decoded from bool, fixnum 0 or 1.
+func (d *msgpackDecDriver) decodeBool() (b bool) {
+ switch d.bd {
+ case mpFalse, 0:
+ // b = false
+ case mpTrue, 1:
+ b = true
+ default:
+ decErr("Invalid single-byte value for bool: %s: %x", msgBadDesc, d.bd)
+ }
+ d.bdRead = false
+ return
+}
+
+func (d *msgpackDecDriver) decodeString() (s string) {
+ clen := d.readContainerLen(msgpackContainerStr)
+ if clen > 0 {
+ s = string(d.r.readn(clen))
+ }
+ d.bdRead = false
+ return
+}
+
+// Callers must check if changed=true (to decide whether to replace the one they have)
+func (d *msgpackDecDriver) decodeBytes(bs []byte) (bsOut []byte, changed bool) {
+ // bytes can be decoded from msgpackContainerStr or msgpackContainerBin
+ var clen int
+ switch d.bd {
+ case mpBin8, mpBin16, mpBin32:
+ clen = d.readContainerLen(msgpackContainerBin)
+ default:
+ clen = d.readContainerLen(msgpackContainerStr)
+ }
+ // if clen < 0 {
+ // changed = true
+ // panic("length cannot be zero. this cannot be nil.")
+ // }
+ if clen > 0 {
+ // if no contents in stream, don't update the passed byteslice
+ if len(bs) != clen {
+ // Return changed=true if length of passed slice diff from length of bytes in stream
+ if len(bs) > clen {
+ bs = bs[:clen]
+ } else {
+ bs = make([]byte, clen)
+ }
+ bsOut = bs
+ changed = true
+ }
+ d.r.readb(bs)
+ }
+ d.bdRead = false
+ return
+}
+
+// Every top-level decode funcs (i.e. decodeValue, decode) must call this first.
+func (d *msgpackDecDriver) initReadNext() {
+ if d.bdRead {
+ return
+ }
+ d.bd = d.r.readn1()
+ d.bdRead = true
+ d.bdType = valueTypeUnset
+}
+
+func (d *msgpackDecDriver) currentEncodedType() valueType {
+ if d.bdType == valueTypeUnset {
+ bd := d.bd
+ switch bd {
+ case mpNil:
+ d.bdType = valueTypeNil
+ case mpFalse, mpTrue:
+ d.bdType = valueTypeBool
+ case mpFloat, mpDouble:
+ d.bdType = valueTypeFloat
+ case mpUint8, mpUint16, mpUint32, mpUint64:
+ d.bdType = valueTypeUint
+ case mpInt8, mpInt16, mpInt32, mpInt64:
+ d.bdType = valueTypeInt
+ default:
+ switch {
+ case bd >= mpPosFixNumMin && bd <= mpPosFixNumMax:
+ d.bdType = valueTypeInt
+ case bd >= mpNegFixNumMin && bd <= mpNegFixNumMax:
+ d.bdType = valueTypeInt
+ case bd == mpStr8, bd == mpStr16, bd == mpStr32, bd >= mpFixStrMin && bd <= mpFixStrMax:
+ if d.h.RawToString {
+ d.bdType = valueTypeString
+ } else {
+ d.bdType = valueTypeBytes
+ }
+ case bd == mpBin8, bd == mpBin16, bd == mpBin32:
+ d.bdType = valueTypeBytes
+ case bd == mpArray16, bd == mpArray32, bd >= mpFixArrayMin && bd <= mpFixArrayMax:
+ d.bdType = valueTypeArray
+ case bd == mpMap16, bd == mpMap32, bd >= mpFixMapMin && bd <= mpFixMapMax:
+ d.bdType = valueTypeMap
+ case bd >= mpFixExt1 && bd <= mpFixExt16, bd >= mpExt8 && bd <= mpExt32:
+ d.bdType = valueTypeExt
+ default:
+ decErr("currentEncodedType: Undeciphered descriptor: %s: hex: %x, dec: %d", msgBadDesc, bd, bd)
+ }
+ }
+ }
+ return d.bdType
+}
+
+func (d *msgpackDecDriver) tryDecodeAsNil() bool {
+ if d.bd == mpNil {
+ d.bdRead = false
+ return true
+ }
+ return false
+}
+
+func (d *msgpackDecDriver) readContainerLen(ct msgpackContainerType) (clen int) {
+ bd := d.bd
+ switch {
+ case bd == mpNil:
+ clen = -1 // to represent nil
+ case bd == ct.b8:
+ clen = int(d.r.readn1())
+ case bd == ct.b16:
+ clen = int(d.r.readUint16())
+ case bd == ct.b32:
+ clen = int(d.r.readUint32())
+ case (ct.bFixMin & bd) == ct.bFixMin:
+ clen = int(ct.bFixMin ^ bd)
+ default:
+ decErr("readContainerLen: %s: hex: %x, dec: %d", msgBadDesc, bd, bd)
+ }
+ d.bdRead = false
+ return
+}
+
+func (d *msgpackDecDriver) readMapLen() int {
+ return d.readContainerLen(msgpackContainerMap)
+}
+
+func (d *msgpackDecDriver) readArrayLen() int {
+ return d.readContainerLen(msgpackContainerList)
+}
+
+func (d *msgpackDecDriver) readExtLen() (clen int) {
+ switch d.bd {
+ case mpNil:
+ clen = -1 // to represent nil
+ case mpFixExt1:
+ clen = 1
+ case mpFixExt2:
+ clen = 2
+ case mpFixExt4:
+ clen = 4
+ case mpFixExt8:
+ clen = 8
+ case mpFixExt16:
+ clen = 16
+ case mpExt8:
+ clen = int(d.r.readn1())
+ case mpExt16:
+ clen = int(d.r.readUint16())
+ case mpExt32:
+ clen = int(d.r.readUint32())
+ default:
+ decErr("decoding ext bytes: found unexpected byte: %x", d.bd)
+ }
+ return
+}
+
+func (d *msgpackDecDriver) decodeExt(verifyTag bool, tag byte) (xtag byte, xbs []byte) {
+ xbd := d.bd
+ switch {
+ case xbd == mpBin8, xbd == mpBin16, xbd == mpBin32:
+ xbs, _ = d.decodeBytes(nil)
+ case xbd == mpStr8, xbd == mpStr16, xbd == mpStr32,
+ xbd >= mpFixStrMin && xbd <= mpFixStrMax:
+ xbs = []byte(d.decodeString())
+ default:
+ clen := d.readExtLen()
+ xtag = d.r.readn1()
+ if verifyTag && xtag != tag {
+ decErr("Wrong extension tag. Got %b. Expecting: %v", xtag, tag)
+ }
+ xbs = d.r.readn(clen)
+ }
+ d.bdRead = false
+ return
+}
+
+//--------------------------------------------------
+
+//MsgpackHandle is a Handle for the Msgpack Schema-Free Encoding Format.
+type MsgpackHandle struct {
+ BasicHandle
+
+ // RawToString controls how raw bytes are decoded into a nil interface{}.
+ RawToString bool
+ // WriteExt flag supports encoding configured extensions with extension tags.
+ // It also controls whether other elements of the new spec are encoded (ie Str8).
+ //
+ // With WriteExt=false, configured extensions are serialized as raw bytes
+ // and Str8 is not encoded.
+ //
+ // A stream can still be decoded into a typed value, provided an appropriate value
+ // is provided, but the type cannot be inferred from the stream. If no appropriate
+ // type is provided (e.g. decoding into a nil interface{}), you get back
+ // a []byte or string based on the setting of RawToString.
+ WriteExt bool
+}
+
+func (h *MsgpackHandle) newEncDriver(w encWriter) encDriver {
+ return &msgpackEncDriver{w: w, h: h}
+}
+
+func (h *MsgpackHandle) newDecDriver(r decReader) decDriver {
+ return &msgpackDecDriver{r: r, h: h}
+}
+
+func (h *MsgpackHandle) writeExt() bool {
+ return h.WriteExt
+}
+
+func (h *MsgpackHandle) getBasicHandle() *BasicHandle {
+ return &h.BasicHandle
+}
+
+//--------------------------------------------------
+
+type msgpackSpecRpcCodec struct {
+ rpcCodec
+}
+
+// /////////////// Spec RPC Codec ///////////////////
+func (c *msgpackSpecRpcCodec) WriteRequest(r *rpc.Request, body interface{}) error {
+ // WriteRequest can write to both a Go service, and other services that do
+ // not abide by the 1 argument rule of a Go service.
+ // We discriminate based on if the body is a MsgpackSpecRpcMultiArgs
+ var bodyArr []interface{}
+ if m, ok := body.(MsgpackSpecRpcMultiArgs); ok {
+ bodyArr = ([]interface{})(m)
+ } else {
+ bodyArr = []interface{}{body}
+ }
+ r2 := []interface{}{0, uint32(r.Seq), r.ServiceMethod, bodyArr}
+ return c.write(r2, nil, false, true)
+}
+
+func (c *msgpackSpecRpcCodec) WriteResponse(r *rpc.Response, body interface{}) error {
+ var moe interface{}
+ if r.Error != "" {
+ moe = r.Error
+ }
+ if moe != nil && body != nil {
+ body = nil
+ }
+ r2 := []interface{}{1, uint32(r.Seq), moe, body}
+ return c.write(r2, nil, false, true)
+}
+
+func (c *msgpackSpecRpcCodec) ReadResponseHeader(r *rpc.Response) error {
+ return c.parseCustomHeader(1, &r.Seq, &r.Error)
+}
+
+func (c *msgpackSpecRpcCodec) ReadRequestHeader(r *rpc.Request) error {
+ return c.parseCustomHeader(0, &r.Seq, &r.ServiceMethod)
+}
+
+func (c *msgpackSpecRpcCodec) ReadRequestBody(body interface{}) error {
+ if body == nil { // read and discard
+ return c.read(nil)
+ }
+ bodyArr := []interface{}{body}
+ return c.read(&bodyArr)
+}
+
+func (c *msgpackSpecRpcCodec) parseCustomHeader(expectTypeByte byte, msgid *uint64, methodOrError *string) (err error) {
+
+ if c.cls {
+ return io.EOF
+ }
+
+ // We read the response header by hand
+ // so that the body can be decoded on its own from the stream at a later time.
+
+ const fia byte = 0x94 //four item array descriptor value
+ // Not sure why the panic of EOF is swallowed above.
+ // if bs1 := c.dec.r.readn1(); bs1 != fia {
+ // err = fmt.Errorf("Unexpected value for array descriptor: Expecting %v. Received %v", fia, bs1)
+ // return
+ // }
+ var b byte
+ b, err = c.br.ReadByte()
+ if err != nil {
+ return
+ }
+ if b != fia {
+ err = fmt.Errorf("Unexpected value for array descriptor: Expecting %v. Received %v", fia, b)
+ return
+ }
+
+ if err = c.read(&b); err != nil {
+ return
+ }
+ if b != expectTypeByte {
+ err = fmt.Errorf("Unexpected byte descriptor in header. Expecting %v. Received %v", expectTypeByte, b)
+ return
+ }
+ if err = c.read(msgid); err != nil {
+ return
+ }
+ if err = c.read(methodOrError); err != nil {
+ return
+ }
+ return
+}
+
+//--------------------------------------------------
+
+// msgpackSpecRpc is the implementation of Rpc that uses custom communication protocol
+// as defined in the msgpack spec at https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md
+type msgpackSpecRpc struct{}
+
+// MsgpackSpecRpc implements Rpc using the communication protocol defined in
+// the msgpack spec at https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md .
+// Its methods (ServerCodec and ClientCodec) return values that implement RpcCodecBuffered.
+var MsgpackSpecRpc msgpackSpecRpc
+
+func (x msgpackSpecRpc) ServerCodec(conn io.ReadWriteCloser, h Handle) rpc.ServerCodec {
+ return &msgpackSpecRpcCodec{newRPCCodec(conn, h)}
+}
+
+func (x msgpackSpecRpc) ClientCodec(conn io.ReadWriteCloser, h Handle) rpc.ClientCodec {
+ return &msgpackSpecRpcCodec{newRPCCodec(conn, h)}
+}
+
+var _ decDriver = (*msgpackDecDriver)(nil)
+var _ encDriver = (*msgpackEncDriver)(nil)
diff -Naur --color b/vendor/github.com/hashicorp/go-msgpack/codec/msgpack_test.py a/vendor/github.com/hashicorp/go-msgpack/codec/msgpack_test.py
--- b/vendor/github.com/hashicorp/go-msgpack/codec/msgpack_test.py 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-msgpack/codec/msgpack_test.py 2022-11-15 23:06:31.555391002 +0100
@@ -0,0 +1,110 @@
+#!/usr/bin/env python
+
+# This will create golden files in a directory passed to it.
+# A Test calls this internally to create the golden files
+# So it can process them (so we don't have to checkin the files).
+
+import msgpack, msgpackrpc, sys, os, threading
+
+def get_test_data_list():
+ # get list with all primitive types, and a combo type
+ l0 = [
+ -8,
+ -1616,
+ -32323232,
+ -6464646464646464,
+ 192,
+ 1616,
+ 32323232,
+ 6464646464646464,
+ 192,
+ -3232.0,
+ -6464646464.0,
+ 3232.0,
+ 6464646464.0,
+ False,
+ True,
+ None,
+ "someday",
+ "",
+ "bytestring",
+ 1328176922000002000,
+ -2206187877999998000,
+ 0,
+ -6795364578871345152
+ ]
+ l1 = [
+ { "true": True,
+ "false": False },
+ { "true": "True",
+ "false": False,
+ "uint16(1616)": 1616 },
+ { "list": [1616, 32323232, True, -3232.0, {"TRUE":True, "FALSE":False}, [True, False] ],
+ "int32":32323232, "bool": True,
+ "LONG STRING": "123456789012345678901234567890123456789012345678901234567890",
+ "SHORT STRING": "1234567890" },
+ { True: "true", 8: False, "false": 0 }
+ ]
+
+ l = []
+ l.extend(l0)
+ l.append(l0)
+ l.extend(l1)
+ return l
+
+def build_test_data(destdir):
+ l = get_test_data_list()
+ for i in range(len(l)):
+ packer = msgpack.Packer()
+ serialized = packer.pack(l[i])
+ f = open(os.path.join(destdir, str(i) + '.golden'), 'wb')
+ f.write(serialized)
+ f.close()
+
+def doRpcServer(port, stopTimeSec):
+ class EchoHandler(object):
+ def Echo123(self, msg1, msg2, msg3):
+ return ("1:%s 2:%s 3:%s" % (msg1, msg2, msg3))
+ def EchoStruct(self, msg):
+ return ("%s" % msg)
+
+ addr = msgpackrpc.Address('localhost', port)
+ server = msgpackrpc.Server(EchoHandler())
+ server.listen(addr)
+ # run thread to stop it after stopTimeSec seconds if > 0
+ if stopTimeSec > 0:
+ def myStopRpcServer():
+ server.stop()
+ t = threading.Timer(stopTimeSec, myStopRpcServer)
+ t.start()
+ server.start()
+
+def doRpcClientToPythonSvc(port):
+ address = msgpackrpc.Address('localhost', port)
+ client = msgpackrpc.Client(address, unpack_encoding='utf-8')
+ print client.call("Echo123", "A1", "B2", "C3")
+ print client.call("EchoStruct", {"A" :"Aa", "B":"Bb", "C":"Cc"})
+
+def doRpcClientToGoSvc(port):
+ # print ">>>> port: ", port, " <<<<<"
+ address = msgpackrpc.Address('localhost', port)
+ client = msgpackrpc.Client(address, unpack_encoding='utf-8')
+ print client.call("TestRpcInt.Echo123", ["A1", "B2", "C3"])
+ print client.call("TestRpcInt.EchoStruct", {"A" :"Aa", "B":"Bb", "C":"Cc"})
+
+def doMain(args):
+ if len(args) == 2 and args[0] == "testdata":
+ build_test_data(args[1])
+ elif len(args) == 3 and args[0] == "rpc-server":
+ doRpcServer(int(args[1]), int(args[2]))
+ elif len(args) == 2 and args[0] == "rpc-client-python-service":
+ doRpcClientToPythonSvc(int(args[1]))
+ elif len(args) == 2 and args[0] == "rpc-client-go-service":
+ doRpcClientToGoSvc(int(args[1]))
+ else:
+ print("Usage: msgpack_test.py " +
+ "[testdata|rpc-server|rpc-client-python-service|rpc-client-go-service] ...")
+
+if __name__ == "__main__":
+ doMain(sys.argv[1:])
+
diff -Naur --color b/vendor/github.com/hashicorp/go-msgpack/codec/README.md a/vendor/github.com/hashicorp/go-msgpack/codec/README.md
--- b/vendor/github.com/hashicorp/go-msgpack/codec/README.md 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-msgpack/codec/README.md 2022-11-15 23:06:31.555391002 +0100
@@ -0,0 +1,174 @@
+# Codec
+
+High Performance and Feature-Rich Idiomatic Go Library providing
+encode/decode support for different serialization formats.
+
+Supported Serialization formats are:
+
+ - msgpack: [https://github.com/msgpack/msgpack]
+ - binc: [http://github.com/ugorji/binc]
+
+To install:
+
+ go get github.com/ugorji/go/codec
+
+Online documentation: [http://godoc.org/github.com/ugorji/go/codec]
+
+The idiomatic Go support is as seen in other encoding packages in
+the standard library (ie json, xml, gob, etc).
+
+Rich Feature Set includes:
+
+ - Simple but extremely powerful and feature-rich API
+ - Very High Performance.
+ Our extensive benchmarks show us outperforming Gob, Json and Bson by 2-4X.
+ This was achieved by taking extreme care on:
+ - managing allocation
+ - function frame size (important due to Go's use of split stacks),
+ - reflection use (and by-passing reflection for common types)
+ - recursion implications
+ - zero-copy mode (encoding/decoding to byte slice without using temp buffers)
+ - Correct.
+ Care was taken to precisely handle corner cases like:
+ overflows, nil maps and slices, nil value in stream, etc.
+ - Efficient zero-copying into temporary byte buffers
+ when encoding into or decoding from a byte slice.
+ - Standard field renaming via tags
+ - Encoding from any value
+ (struct, slice, map, primitives, pointers, interface{}, etc)
+ - Decoding into pointer to any non-nil typed value
+ (struct, slice, map, int, float32, bool, string, reflect.Value, etc)
+ - Supports extension functions to handle the encode/decode of custom types
+ - Support Go 1.2 encoding.BinaryMarshaler/BinaryUnmarshaler
+ - Schema-less decoding
+ (decode into a pointer to a nil interface{} as opposed to a typed non-nil value).
+ Includes Options to configure what specific map or slice type to use
+ when decoding an encoded list or map into a nil interface{}
+ - Provides a RPC Server and Client Codec for net/rpc communication protocol.
+ - Msgpack Specific:
+ - Provides extension functions to handle spec-defined extensions (binary, timestamp)
+ - Options to resolve ambiguities in handling raw bytes (as string or []byte)
+ during schema-less decoding (decoding into a nil interface{})
+ - RPC Server/Client Codec for msgpack-rpc protocol defined at:
+ https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md
+ - Fast Paths for some container types:
+ For some container types, we circumvent reflection and its associated overhead
+ and allocation costs, and encode/decode directly. These types are:
+ []interface{}
+ []int
+ []string
+ map[interface{}]interface{}
+ map[int]interface{}
+ map[string]interface{}
+
+## Extension Support
+
+Users can register a function to handle the encoding or decoding of
+their custom types.
+
+There are no restrictions on what the custom type can be. Some examples:
+
+ type BisSet []int
+ type BitSet64 uint64
+ type UUID string
+ type MyStructWithUnexportedFields struct { a int; b bool; c []int; }
+ type GifImage struct { ... }
+
+As an illustration, MyStructWithUnexportedFields would normally be
+encoded as an empty map because it has no exported fields, while UUID
+would be encoded as a string. However, with extension support, you can
+encode any of these however you like.
+
+## RPC
+
+RPC Client and Server Codecs are implemented, so the codecs can be used
+with the standard net/rpc package.
+
+## Usage
+
+Typical usage model:
+
+ // create and configure Handle
+ var (
+ bh codec.BincHandle
+ mh codec.MsgpackHandle
+ )
+
+ mh.MapType = reflect.TypeOf(map[string]interface{}(nil))
+
+ // configure extensions
+ // e.g. for msgpack, define functions and enable Time support for tag 1
+ // mh.AddExt(reflect.TypeOf(time.Time{}), 1, myMsgpackTimeEncodeExtFn, myMsgpackTimeDecodeExtFn)
+
+ // create and use decoder/encoder
+ var (
+ r io.Reader
+ w io.Writer
+ b []byte
+ h = &bh // or mh to use msgpack
+ )
+
+ dec = codec.NewDecoder(r, h)
+ dec = codec.NewDecoderBytes(b, h)
+ err = dec.Decode(&v)
+
+ enc = codec.NewEncoder(w, h)
+ enc = codec.NewEncoderBytes(&b, h)
+ err = enc.Encode(v)
+
+ //RPC Server
+ go func() {
+ for {
+ conn, err := listener.Accept()
+ rpcCodec := codec.GoRpc.ServerCodec(conn, h)
+ //OR rpcCodec := codec.MsgpackSpecRpc.ServerCodec(conn, h)
+ rpc.ServeCodec(rpcCodec)
+ }
+ }()
+
+ //RPC Communication (client side)
+ conn, err = net.Dial("tcp", "localhost:5555")
+ rpcCodec := codec.GoRpc.ClientCodec(conn, h)
+ //OR rpcCodec := codec.MsgpackSpecRpc.ClientCodec(conn, h)
+ client := rpc.NewClientWithCodec(rpcCodec)
+
+## Representative Benchmark Results
+
+A sample run of benchmark using "go test -bi -bench=. -benchmem":
+
+ /proc/cpuinfo: Intel(R) Core(TM) i7-2630QM CPU @ 2.00GHz (HT)
+
+ ..............................................
+ BENCHMARK INIT: 2013-10-16 11:02:50.345970786 -0400 EDT
+ To run full benchmark comparing encodings (MsgPack, Binc, JSON, GOB, etc), use: "go test -bench=."
+ Benchmark:
+ Struct recursive Depth: 1
+ ApproxDeepSize Of benchmark Struct: 4694 bytes
+ Benchmark One-Pass Run:
+ v-msgpack: len: 1600 bytes
+ bson: len: 3025 bytes
+ msgpack: len: 1560 bytes
+ binc: len: 1187 bytes
+ gob: len: 1972 bytes
+ json: len: 2538 bytes
+ ..............................................
+ PASS
+ Benchmark__Msgpack____Encode 50000 54359 ns/op 14953 B/op 83 allocs/op
+ Benchmark__Msgpack____Decode 10000 106531 ns/op 14990 B/op 410 allocs/op
+ Benchmark__Binc_NoSym_Encode 50000 53956 ns/op 14966 B/op 83 allocs/op
+ Benchmark__Binc_NoSym_Decode 10000 103751 ns/op 14529 B/op 386 allocs/op
+ Benchmark__Binc_Sym___Encode 50000 65961 ns/op 17130 B/op 88 allocs/op
+ Benchmark__Binc_Sym___Decode 10000 106310 ns/op 15857 B/op 287 allocs/op
+ Benchmark__Gob________Encode 10000 135944 ns/op 21189 B/op 237 allocs/op
+ Benchmark__Gob________Decode 5000 405390 ns/op 83460 B/op 1841 allocs/op
+ Benchmark__Json_______Encode 20000 79412 ns/op 13874 B/op 102 allocs/op
+ Benchmark__Json_______Decode 10000 247979 ns/op 14202 B/op 493 allocs/op
+ Benchmark__Bson_______Encode 10000 121762 ns/op 27814 B/op 514 allocs/op
+ Benchmark__Bson_______Decode 10000 162126 ns/op 16514 B/op 789 allocs/op
+ Benchmark__VMsgpack___Encode 50000 69155 ns/op 12370 B/op 344 allocs/op
+ Benchmark__VMsgpack___Decode 10000 151609 ns/op 20307 B/op 571 allocs/op
+ ok ugorji.net/codec 30.827s
+
+To run full benchmark suite (including against vmsgpack and bson),
+see notes in ext\_dep\_test.go
+
diff -Naur --color b/vendor/github.com/hashicorp/go-msgpack/codec/rpc.go a/vendor/github.com/hashicorp/go-msgpack/codec/rpc.go
--- b/vendor/github.com/hashicorp/go-msgpack/codec/rpc.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-msgpack/codec/rpc.go 2022-11-15 23:06:31.558724400 +0100
@@ -0,0 +1,152 @@
+// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved.
+// Use of this source code is governed by a BSD-style license found in the LICENSE file.
+
+package codec
+
+import (
+ "bufio"
+ "io"
+ "net/rpc"
+ "sync"
+)
+
+// Rpc provides a rpc Server or Client Codec for rpc communication.
+type Rpc interface {
+ ServerCodec(conn io.ReadWriteCloser, h Handle) rpc.ServerCodec
+ ClientCodec(conn io.ReadWriteCloser, h Handle) rpc.ClientCodec
+}
+
+// RpcCodecBuffered allows access to the underlying bufio.Reader/Writer
+// used by the rpc connection. It accomodates use-cases where the connection
+// should be used by rpc and non-rpc functions, e.g. streaming a file after
+// sending an rpc response.
+type RpcCodecBuffered interface {
+ BufferedReader() *bufio.Reader
+ BufferedWriter() *bufio.Writer
+}
+
+// -------------------------------------
+
+// rpcCodec defines the struct members and common methods.
+type rpcCodec struct {
+ rwc io.ReadWriteCloser
+ dec *Decoder
+ enc *Encoder
+ bw *bufio.Writer
+ br *bufio.Reader
+ mu sync.Mutex
+ cls bool
+}
+
+func newRPCCodec(conn io.ReadWriteCloser, h Handle) rpcCodec {
+ bw := bufio.NewWriter(conn)
+ br := bufio.NewReader(conn)
+ return rpcCodec{
+ rwc: conn,
+ bw: bw,
+ br: br,
+ enc: NewEncoder(bw, h),
+ dec: NewDecoder(br, h),
+ }
+}
+
+func (c *rpcCodec) BufferedReader() *bufio.Reader {
+ return c.br
+}
+
+func (c *rpcCodec) BufferedWriter() *bufio.Writer {
+ return c.bw
+}
+
+func (c *rpcCodec) write(obj1, obj2 interface{}, writeObj2, doFlush bool) (err error) {
+ if c.cls {
+ return io.EOF
+ }
+ if err = c.enc.Encode(obj1); err != nil {
+ return
+ }
+ if writeObj2 {
+ if err = c.enc.Encode(obj2); err != nil {
+ return
+ }
+ }
+ if doFlush && c.bw != nil {
+ return c.bw.Flush()
+ }
+ return
+}
+
+func (c *rpcCodec) read(obj interface{}) (err error) {
+ if c.cls {
+ return io.EOF
+ }
+ //If nil is passed in, we should still attempt to read content to nowhere.
+ if obj == nil {
+ var obj2 interface{}
+ return c.dec.Decode(&obj2)
+ }
+ return c.dec.Decode(obj)
+}
+
+func (c *rpcCodec) Close() error {
+ if c.cls {
+ return io.EOF
+ }
+ c.cls = true
+ return c.rwc.Close()
+}
+
+func (c *rpcCodec) ReadResponseBody(body interface{}) error {
+ return c.read(body)
+}
+
+// -------------------------------------
+
+type goRpcCodec struct {
+ rpcCodec
+}
+
+func (c *goRpcCodec) WriteRequest(r *rpc.Request, body interface{}) error {
+ // Must protect for concurrent access as per API
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.write(r, body, true, true)
+}
+
+func (c *goRpcCodec) WriteResponse(r *rpc.Response, body interface{}) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.write(r, body, true, true)
+}
+
+func (c *goRpcCodec) ReadResponseHeader(r *rpc.Response) error {
+ return c.read(r)
+}
+
+func (c *goRpcCodec) ReadRequestHeader(r *rpc.Request) error {
+ return c.read(r)
+}
+
+func (c *goRpcCodec) ReadRequestBody(body interface{}) error {
+ return c.read(body)
+}
+
+// -------------------------------------
+
+// goRpc is the implementation of Rpc that uses the communication protocol
+// as defined in net/rpc package.
+type goRpc struct{}
+
+// GoRpc implements Rpc using the communication protocol defined in net/rpc package.
+// Its methods (ServerCodec and ClientCodec) return values that implement RpcCodecBuffered.
+var GoRpc goRpc
+
+func (x goRpc) ServerCodec(conn io.ReadWriteCloser, h Handle) rpc.ServerCodec {
+ return &goRpcCodec{newRPCCodec(conn, h)}
+}
+
+func (x goRpc) ClientCodec(conn io.ReadWriteCloser, h Handle) rpc.ClientCodec {
+ return &goRpcCodec{newRPCCodec(conn, h)}
+}
+
+var _ RpcCodecBuffered = (*rpcCodec)(nil) // ensure *rpcCodec implements RpcCodecBuffered
diff -Naur --color b/vendor/github.com/hashicorp/go-msgpack/codec/simple.go a/vendor/github.com/hashicorp/go-msgpack/codec/simple.go
--- b/vendor/github.com/hashicorp/go-msgpack/codec/simple.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-msgpack/codec/simple.go 2022-11-15 23:06:31.558724400 +0100
@@ -0,0 +1,461 @@
+// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved.
+// Use of this source code is governed by a BSD-style license found in the LICENSE file.
+
+package codec
+
+import "math"
+
+const (
+ _ uint8 = iota
+ simpleVdNil = 1
+ simpleVdFalse = 2
+ simpleVdTrue = 3
+ simpleVdFloat32 = 4
+ simpleVdFloat64 = 5
+
+ // each lasts for 4 (ie n, n+1, n+2, n+3)
+ simpleVdPosInt = 8
+ simpleVdNegInt = 12
+
+ // containers: each lasts for 4 (ie n, n+1, n+2, ... n+7)
+ simpleVdString = 216
+ simpleVdByteArray = 224
+ simpleVdArray = 232
+ simpleVdMap = 240
+ simpleVdExt = 248
+)
+
+type simpleEncDriver struct {
+ h *SimpleHandle
+ w encWriter
+ //b [8]byte
+}
+
+func (e *simpleEncDriver) isBuiltinType(rt uintptr) bool {
+ return false
+}
+
+func (e *simpleEncDriver) encodeBuiltin(rt uintptr, v interface{}) {
+}
+
+func (e *simpleEncDriver) encodeNil() {
+ e.w.writen1(simpleVdNil)
+}
+
+func (e *simpleEncDriver) encodeBool(b bool) {
+ if b {
+ e.w.writen1(simpleVdTrue)
+ } else {
+ e.w.writen1(simpleVdFalse)
+ }
+}
+
+func (e *simpleEncDriver) encodeFloat32(f float32) {
+ e.w.writen1(simpleVdFloat32)
+ e.w.writeUint32(math.Float32bits(f))
+}
+
+func (e *simpleEncDriver) encodeFloat64(f float64) {
+ e.w.writen1(simpleVdFloat64)
+ e.w.writeUint64(math.Float64bits(f))
+}
+
+func (e *simpleEncDriver) encodeInt(v int64) {
+ if v < 0 {
+ e.encUint(uint64(-v), simpleVdNegInt)
+ } else {
+ e.encUint(uint64(v), simpleVdPosInt)
+ }
+}
+
+func (e *simpleEncDriver) encodeUint(v uint64) {
+ e.encUint(v, simpleVdPosInt)
+}
+
+func (e *simpleEncDriver) encUint(v uint64, bd uint8) {
+ switch {
+ case v <= math.MaxUint8:
+ e.w.writen2(bd, uint8(v))
+ case v <= math.MaxUint16:
+ e.w.writen1(bd + 1)
+ e.w.writeUint16(uint16(v))
+ case v <= math.MaxUint32:
+ e.w.writen1(bd + 2)
+ e.w.writeUint32(uint32(v))
+ case v <= math.MaxUint64:
+ e.w.writen1(bd + 3)
+ e.w.writeUint64(v)
+ }
+}
+
+func (e *simpleEncDriver) encLen(bd byte, length int) {
+ switch {
+ case length == 0:
+ e.w.writen1(bd)
+ case length <= math.MaxUint8:
+ e.w.writen1(bd + 1)
+ e.w.writen1(uint8(length))
+ case length <= math.MaxUint16:
+ e.w.writen1(bd + 2)
+ e.w.writeUint16(uint16(length))
+ case int64(length) <= math.MaxUint32:
+ e.w.writen1(bd + 3)
+ e.w.writeUint32(uint32(length))
+ default:
+ e.w.writen1(bd + 4)
+ e.w.writeUint64(uint64(length))
+ }
+}
+
+func (e *simpleEncDriver) encodeExtPreamble(xtag byte, length int) {
+ e.encLen(simpleVdExt, length)
+ e.w.writen1(xtag)
+}
+
+func (e *simpleEncDriver) encodeArrayPreamble(length int) {
+ e.encLen(simpleVdArray, length)
+}
+
+func (e *simpleEncDriver) encodeMapPreamble(length int) {
+ e.encLen(simpleVdMap, length)
+}
+
+func (e *simpleEncDriver) encodeString(c charEncoding, v string) {
+ e.encLen(simpleVdString, len(v))
+ e.w.writestr(v)
+}
+
+func (e *simpleEncDriver) encodeSymbol(v string) {
+ e.encodeString(c_UTF8, v)
+}
+
+func (e *simpleEncDriver) encodeStringBytes(c charEncoding, v []byte) {
+ e.encLen(simpleVdByteArray, len(v))
+ e.w.writeb(v)
+}
+
+//------------------------------------
+
+type simpleDecDriver struct {
+ h *SimpleHandle
+ r decReader
+ bdRead bool
+ bdType valueType
+ bd byte
+ //b [8]byte
+}
+
+func (d *simpleDecDriver) initReadNext() {
+ if d.bdRead {
+ return
+ }
+ d.bd = d.r.readn1()
+ d.bdRead = true
+ d.bdType = valueTypeUnset
+}
+
+func (d *simpleDecDriver) currentEncodedType() valueType {
+ if d.bdType == valueTypeUnset {
+ switch d.bd {
+ case simpleVdNil:
+ d.bdType = valueTypeNil
+ case simpleVdTrue, simpleVdFalse:
+ d.bdType = valueTypeBool
+ case simpleVdPosInt, simpleVdPosInt + 1, simpleVdPosInt + 2, simpleVdPosInt + 3:
+ d.bdType = valueTypeUint
+ case simpleVdNegInt, simpleVdNegInt + 1, simpleVdNegInt + 2, simpleVdNegInt + 3:
+ d.bdType = valueTypeInt
+ case simpleVdFloat32, simpleVdFloat64:
+ d.bdType = valueTypeFloat
+ case simpleVdString, simpleVdString + 1, simpleVdString + 2, simpleVdString + 3, simpleVdString + 4:
+ d.bdType = valueTypeString
+ case simpleVdByteArray, simpleVdByteArray + 1, simpleVdByteArray + 2, simpleVdByteArray + 3, simpleVdByteArray + 4:
+ d.bdType = valueTypeBytes
+ case simpleVdExt, simpleVdExt + 1, simpleVdExt + 2, simpleVdExt + 3, simpleVdExt + 4:
+ d.bdType = valueTypeExt
+ case simpleVdArray, simpleVdArray + 1, simpleVdArray + 2, simpleVdArray + 3, simpleVdArray + 4:
+ d.bdType = valueTypeArray
+ case simpleVdMap, simpleVdMap + 1, simpleVdMap + 2, simpleVdMap + 3, simpleVdMap + 4:
+ d.bdType = valueTypeMap
+ default:
+ decErr("currentEncodedType: Unrecognized d.vd: 0x%x", d.bd)
+ }
+ }
+ return d.bdType
+}
+
+func (d *simpleDecDriver) tryDecodeAsNil() bool {
+ if d.bd == simpleVdNil {
+ d.bdRead = false
+ return true
+ }
+ return false
+}
+
+func (d *simpleDecDriver) isBuiltinType(rt uintptr) bool {
+ return false
+}
+
+func (d *simpleDecDriver) decodeBuiltin(rt uintptr, v interface{}) {
+}
+
+func (d *simpleDecDriver) decIntAny() (ui uint64, i int64, neg bool) {
+ switch d.bd {
+ case simpleVdPosInt:
+ ui = uint64(d.r.readn1())
+ i = int64(ui)
+ case simpleVdPosInt + 1:
+ ui = uint64(d.r.readUint16())
+ i = int64(ui)
+ case simpleVdPosInt + 2:
+ ui = uint64(d.r.readUint32())
+ i = int64(ui)
+ case simpleVdPosInt + 3:
+ ui = uint64(d.r.readUint64())
+ i = int64(ui)
+ case simpleVdNegInt:
+ ui = uint64(d.r.readn1())
+ i = -(int64(ui))
+ neg = true
+ case simpleVdNegInt + 1:
+ ui = uint64(d.r.readUint16())
+ i = -(int64(ui))
+ neg = true
+ case simpleVdNegInt + 2:
+ ui = uint64(d.r.readUint32())
+ i = -(int64(ui))
+ neg = true
+ case simpleVdNegInt + 3:
+ ui = uint64(d.r.readUint64())
+ i = -(int64(ui))
+ neg = true
+ default:
+ decErr("decIntAny: Integer only valid from pos/neg integer1..8. Invalid descriptor: %v", d.bd)
+ }
+ // don't do this check, because callers may only want the unsigned value.
+ // if ui > math.MaxInt64 {
+ // decErr("decIntAny: Integer out of range for signed int64: %v", ui)
+ // }
+ return
+}
+
+func (d *simpleDecDriver) decodeInt(bitsize uint8) (i int64) {
+ _, i, _ = d.decIntAny()
+ checkOverflow(0, i, bitsize)
+ d.bdRead = false
+ return
+}
+
+func (d *simpleDecDriver) decodeUint(bitsize uint8) (ui uint64) {
+ ui, i, neg := d.decIntAny()
+ if neg {
+ decErr("Assigning negative signed value: %v, to unsigned type", i)
+ }
+ checkOverflow(ui, 0, bitsize)
+ d.bdRead = false
+ return
+}
+
+func (d *simpleDecDriver) decodeFloat(chkOverflow32 bool) (f float64) {
+ switch d.bd {
+ case simpleVdFloat32:
+ f = float64(math.Float32frombits(d.r.readUint32()))
+ case simpleVdFloat64:
+ f = math.Float64frombits(d.r.readUint64())
+ default:
+ if d.bd >= simpleVdPosInt && d.bd <= simpleVdNegInt+3 {
+ _, i, _ := d.decIntAny()
+ f = float64(i)
+ } else {
+ decErr("Float only valid from float32/64: Invalid descriptor: %v", d.bd)
+ }
+ }
+ checkOverflowFloat32(f, chkOverflow32)
+ d.bdRead = false
+ return
+}
+
+// bool can be decoded from bool only (single byte).
+func (d *simpleDecDriver) decodeBool() (b bool) {
+ switch d.bd {
+ case simpleVdTrue:
+ b = true
+ case simpleVdFalse:
+ default:
+ decErr("Invalid single-byte value for bool: %s: %x", msgBadDesc, d.bd)
+ }
+ d.bdRead = false
+ return
+}
+
+func (d *simpleDecDriver) readMapLen() (length int) {
+ d.bdRead = false
+ return d.decLen()
+}
+
+func (d *simpleDecDriver) readArrayLen() (length int) {
+ d.bdRead = false
+ return d.decLen()
+}
+
+func (d *simpleDecDriver) decLen() int {
+ switch d.bd % 8 {
+ case 0:
+ return 0
+ case 1:
+ return int(d.r.readn1())
+ case 2:
+ return int(d.r.readUint16())
+ case 3:
+ ui := uint64(d.r.readUint32())
+ checkOverflow(ui, 0, intBitsize)
+ return int(ui)
+ case 4:
+ ui := d.r.readUint64()
+ checkOverflow(ui, 0, intBitsize)
+ return int(ui)
+ }
+ decErr("decLen: Cannot read length: bd%8 must be in range 0..4. Got: %d", d.bd%8)
+ return -1
+}
+
+func (d *simpleDecDriver) decodeString() (s string) {
+ s = string(d.r.readn(d.decLen()))
+ d.bdRead = false
+ return
+}
+
+func (d *simpleDecDriver) decodeBytes(bs []byte) (bsOut []byte, changed bool) {
+ if clen := d.decLen(); clen > 0 {
+ // if no contents in stream, don't update the passed byteslice
+ if len(bs) != clen {
+ if len(bs) > clen {
+ bs = bs[:clen]
+ } else {
+ bs = make([]byte, clen)
+ }
+ bsOut = bs
+ changed = true
+ }
+ d.r.readb(bs)
+ }
+ d.bdRead = false
+ return
+}
+
+func (d *simpleDecDriver) decodeExt(verifyTag bool, tag byte) (xtag byte, xbs []byte) {
+ switch d.bd {
+ case simpleVdExt, simpleVdExt + 1, simpleVdExt + 2, simpleVdExt + 3, simpleVdExt + 4:
+ l := d.decLen()
+ xtag = d.r.readn1()
+ if verifyTag && xtag != tag {
+ decErr("Wrong extension tag. Got %b. Expecting: %v", xtag, tag)
+ }
+ xbs = d.r.readn(l)
+ case simpleVdByteArray, simpleVdByteArray + 1, simpleVdByteArray + 2, simpleVdByteArray + 3, simpleVdByteArray + 4:
+ xbs, _ = d.decodeBytes(nil)
+ default:
+ decErr("Invalid d.vd for extensions (Expecting extensions or byte array). Got: 0x%x", d.bd)
+ }
+ d.bdRead = false
+ return
+}
+
+func (d *simpleDecDriver) decodeNaked() (v interface{}, vt valueType, decodeFurther bool) {
+ d.initReadNext()
+
+ switch d.bd {
+ case simpleVdNil:
+ vt = valueTypeNil
+ case simpleVdFalse:
+ vt = valueTypeBool
+ v = false
+ case simpleVdTrue:
+ vt = valueTypeBool
+ v = true
+ case simpleVdPosInt, simpleVdPosInt + 1, simpleVdPosInt + 2, simpleVdPosInt + 3:
+ vt = valueTypeUint
+ ui, _, _ := d.decIntAny()
+ v = ui
+ case simpleVdNegInt, simpleVdNegInt + 1, simpleVdNegInt + 2, simpleVdNegInt + 3:
+ vt = valueTypeInt
+ _, i, _ := d.decIntAny()
+ v = i
+ case simpleVdFloat32:
+ vt = valueTypeFloat
+ v = d.decodeFloat(true)
+ case simpleVdFloat64:
+ vt = valueTypeFloat
+ v = d.decodeFloat(false)
+ case simpleVdString, simpleVdString + 1, simpleVdString + 2, simpleVdString + 3, simpleVdString + 4:
+ vt = valueTypeString
+ v = d.decodeString()
+ case simpleVdByteArray, simpleVdByteArray + 1, simpleVdByteArray + 2, simpleVdByteArray + 3, simpleVdByteArray + 4:
+ vt = valueTypeBytes
+ v, _ = d.decodeBytes(nil)
+ case simpleVdExt, simpleVdExt + 1, simpleVdExt + 2, simpleVdExt + 3, simpleVdExt + 4:
+ vt = valueTypeExt
+ l := d.decLen()
+ var re RawExt
+ re.Tag = d.r.readn1()
+ re.Data = d.r.readn(l)
+ v = &re
+ vt = valueTypeExt
+ case simpleVdArray, simpleVdArray + 1, simpleVdArray + 2, simpleVdArray + 3, simpleVdArray + 4:
+ vt = valueTypeArray
+ decodeFurther = true
+ case simpleVdMap, simpleVdMap + 1, simpleVdMap + 2, simpleVdMap + 3, simpleVdMap + 4:
+ vt = valueTypeMap
+ decodeFurther = true
+ default:
+ decErr("decodeNaked: Unrecognized d.vd: 0x%x", d.bd)
+ }
+
+ if !decodeFurther {
+ d.bdRead = false
+ }
+ return
+}
+
+//------------------------------------
+
+// SimpleHandle is a Handle for a very simple encoding format.
+//
+// simple is a simplistic codec similar to binc, but not as compact.
+// - Encoding of a value is always preceeded by the descriptor byte (bd)
+// - True, false, nil are encoded fully in 1 byte (the descriptor)
+// - Integers (intXXX, uintXXX) are encoded in 1, 2, 4 or 8 bytes (plus a descriptor byte).
+// There are positive (uintXXX and intXXX >= 0) and negative (intXXX < 0) integers.
+// - Floats are encoded in 4 or 8 bytes (plus a descriptor byte)
+// - Lenght of containers (strings, bytes, array, map, extensions)
+// are encoded in 0, 1, 2, 4 or 8 bytes.
+// Zero-length containers have no length encoded.
+// For others, the number of bytes is given by pow(2, bd%3)
+// - maps are encoded as [bd] [length] [[key][value]]...
+// - arrays are encoded as [bd] [length] [value]...
+// - extensions are encoded as [bd] [length] [tag] [byte]...
+// - strings/bytearrays are encoded as [bd] [length] [byte]...
+//
+// The full spec will be published soon.
+type SimpleHandle struct {
+ BasicHandle
+}
+
+func (h *SimpleHandle) newEncDriver(w encWriter) encDriver {
+ return &simpleEncDriver{w: w, h: h}
+}
+
+func (h *SimpleHandle) newDecDriver(r decReader) decDriver {
+ return &simpleDecDriver{r: r, h: h}
+}
+
+func (_ *SimpleHandle) writeExt() bool {
+ return true
+}
+
+func (h *SimpleHandle) getBasicHandle() *BasicHandle {
+ return &h.BasicHandle
+}
+
+var _ decDriver = (*simpleDecDriver)(nil)
+var _ encDriver = (*simpleEncDriver)(nil)
diff -Naur --color b/vendor/github.com/hashicorp/go-msgpack/codec/time.go a/vendor/github.com/hashicorp/go-msgpack/codec/time.go
--- b/vendor/github.com/hashicorp/go-msgpack/codec/time.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-msgpack/codec/time.go 2022-11-15 23:06:31.558724400 +0100
@@ -0,0 +1,193 @@
+// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved.
+// Use of this source code is governed by a BSD-style license found in the LICENSE file.
+
+package codec
+
+import (
+ "time"
+)
+
+var (
+ timeDigits = [...]byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
+)
+
+// EncodeTime encodes a time.Time as a []byte, including
+// information on the instant in time and UTC offset.
+//
+// Format Description
+//
+// A timestamp is composed of 3 components:
+//
+// - secs: signed integer representing seconds since unix epoch
+// - nsces: unsigned integer representing fractional seconds as a
+// nanosecond offset within secs, in the range 0 <= nsecs < 1e9
+// - tz: signed integer representing timezone offset in minutes east of UTC,
+// and a dst (daylight savings time) flag
+//
+// When encoding a timestamp, the first byte is the descriptor, which
+// defines which components are encoded and how many bytes are used to
+// encode secs and nsecs components. *If secs/nsecs is 0 or tz is UTC, it
+// is not encoded in the byte array explicitly*.
+//
+// Descriptor 8 bits are of the form `A B C DDD EE`:
+// A: Is secs component encoded? 1 = true
+// B: Is nsecs component encoded? 1 = true
+// C: Is tz component encoded? 1 = true
+// DDD: Number of extra bytes for secs (range 0-7).
+// If A = 1, secs encoded in DDD+1 bytes.
+// If A = 0, secs is not encoded, and is assumed to be 0.
+// If A = 1, then we need at least 1 byte to encode secs.
+// DDD says the number of extra bytes beyond that 1.
+// E.g. if DDD=0, then secs is represented in 1 byte.
+// if DDD=2, then secs is represented in 3 bytes.
+// EE: Number of extra bytes for nsecs (range 0-3).
+// If B = 1, nsecs encoded in EE+1 bytes (similar to secs/DDD above)
+//
+// Following the descriptor bytes, subsequent bytes are:
+//
+// secs component encoded in `DDD + 1` bytes (if A == 1)
+// nsecs component encoded in `EE + 1` bytes (if B == 1)
+// tz component encoded in 2 bytes (if C == 1)
+//
+// secs and nsecs components are integers encoded in a BigEndian
+// 2-complement encoding format.
+//
+// tz component is encoded as 2 bytes (16 bits). Most significant bit 15 to
+// Least significant bit 0 are described below:
+//
+// Timezone offset has a range of -12:00 to +14:00 (ie -720 to +840 minutes).
+// Bit 15 = have\_dst: set to 1 if we set the dst flag.
+// Bit 14 = dst\_on: set to 1 if dst is in effect at the time, or 0 if not.
+// Bits 13..0 = timezone offset in minutes. It is a signed integer in Big Endian format.
+//
+func encodeTime(t time.Time) []byte {
+ //t := rv.Interface().(time.Time)
+ tsecs, tnsecs := t.Unix(), t.Nanosecond()
+ var (
+ bd byte
+ btmp [8]byte
+ bs [16]byte
+ i int = 1
+ )
+ l := t.Location()
+ if l == time.UTC {
+ l = nil
+ }
+ if tsecs != 0 {
+ bd = bd | 0x80
+ bigen.PutUint64(btmp[:], uint64(tsecs))
+ f := pruneSignExt(btmp[:], tsecs >= 0)
+ bd = bd | (byte(7-f) << 2)
+ copy(bs[i:], btmp[f:])
+ i = i + (8 - f)
+ }
+ if tnsecs != 0 {
+ bd = bd | 0x40
+ bigen.PutUint32(btmp[:4], uint32(tnsecs))
+ f := pruneSignExt(btmp[:4], true)
+ bd = bd | byte(3-f)
+ copy(bs[i:], btmp[f:4])
+ i = i + (4 - f)
+ }
+ if l != nil {
+ bd = bd | 0x20
+ // Note that Go Libs do not give access to dst flag.
+ _, zoneOffset := t.Zone()
+ //zoneName, zoneOffset := t.Zone()
+ zoneOffset /= 60
+ z := uint16(zoneOffset)
+ bigen.PutUint16(btmp[:2], z)
+ // clear dst flags
+ bs[i] = btmp[0] & 0x3f
+ bs[i+1] = btmp[1]
+ i = i + 2
+ }
+ bs[0] = bd
+ return bs[0:i]
+}
+
+// DecodeTime decodes a []byte into a time.Time.
+func decodeTime(bs []byte) (tt time.Time, err error) {
+ bd := bs[0]
+ var (
+ tsec int64
+ tnsec uint32
+ tz uint16
+ i byte = 1
+ i2 byte
+ n byte
+ )
+ if bd&(1<<7) != 0 {
+ var btmp [8]byte
+ n = ((bd >> 2) & 0x7) + 1
+ i2 = i + n
+ copy(btmp[8-n:], bs[i:i2])
+ //if first bit of bs[i] is set, then fill btmp[0..8-n] with 0xff (ie sign extend it)
+ if bs[i]&(1<<7) != 0 {
+ copy(btmp[0:8-n], bsAll0xff)
+ //for j,k := byte(0), 8-n; j < k; j++ { btmp[j] = 0xff }
+ }
+ i = i2
+ tsec = int64(bigen.Uint64(btmp[:]))
+ }
+ if bd&(1<<6) != 0 {
+ var btmp [4]byte
+ n = (bd & 0x3) + 1
+ i2 = i + n
+ copy(btmp[4-n:], bs[i:i2])
+ i = i2
+ tnsec = bigen.Uint32(btmp[:])
+ }
+ if bd&(1<<5) == 0 {
+ tt = time.Unix(tsec, int64(tnsec)).UTC()
+ return
+ }
+ // In stdlib time.Parse, when a date is parsed without a zone name, it uses "" as zone name.
+ // However, we need name here, so it can be shown when time is printed.
+ // Zone name is in form: UTC-08:00.
+ // Note that Go Libs do not give access to dst flag, so we ignore dst bits
+
+ i2 = i + 2
+ tz = bigen.Uint16(bs[i:i2])
+ i = i2
+ // sign extend sign bit into top 2 MSB (which were dst bits):
+ if tz&(1<<13) == 0 { // positive
+ tz = tz & 0x3fff //clear 2 MSBs: dst bits
+ } else { // negative
+ tz = tz | 0xc000 //set 2 MSBs: dst bits
+ //tzname[3] = '-' (TODO: verify. this works here)
+ }
+ tzint := int16(tz)
+ if tzint == 0 {
+ tt = time.Unix(tsec, int64(tnsec)).UTC()
+ } else {
+ // For Go Time, do not use a descriptive timezone.
+ // It's unnecessary, and makes it harder to do a reflect.DeepEqual.
+ // The Offset already tells what the offset should be, if not on UTC and unknown zone name.
+ // var zoneName = timeLocUTCName(tzint)
+ tt = time.Unix(tsec, int64(tnsec)).In(time.FixedZone("", int(tzint)*60))
+ }
+ return
+}
+
+func timeLocUTCName(tzint int16) string {
+ if tzint == 0 {
+ return "UTC"
+ }
+ var tzname = []byte("UTC+00:00")
+ //tzname := fmt.Sprintf("UTC%s%02d:%02d", tzsign, tz/60, tz%60) //perf issue using Sprintf. inline below.
+ //tzhr, tzmin := tz/60, tz%60 //faster if u convert to int first
+ var tzhr, tzmin int16
+ if tzint < 0 {
+ tzname[3] = '-' // (TODO: verify. this works here)
+ tzhr, tzmin = -tzint/60, (-tzint)%60
+ } else {
+ tzhr, tzmin = tzint/60, tzint%60
+ }
+ tzname[4] = timeDigits[tzhr/10]
+ tzname[5] = timeDigits[tzhr%10]
+ tzname[7] = timeDigits[tzmin/10]
+ tzname[8] = timeDigits[tzmin%10]
+ return string(tzname)
+ //return time.FixedZone(string(tzname), int(tzint)*60)
+}
diff -Naur --color b/vendor/github.com/hashicorp/go-msgpack/LICENSE a/vendor/github.com/hashicorp/go-msgpack/LICENSE
--- b/vendor/github.com/hashicorp/go-msgpack/LICENSE 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/go-msgpack/LICENSE 2022-11-15 23:06:31.558724400 +0100
@@ -0,0 +1,25 @@
+Copyright (c) 2012, 2013 Ugorji Nwoke.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+* Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+* Neither the name of the author nor the names of its contributors may be used
+ to endorse or promote products derived from this software
+ without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff -Naur --color b/vendor/github.com/hashicorp/raft/api.go a/vendor/github.com/hashicorp/raft/api.go
--- b/vendor/github.com/hashicorp/raft/api.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/api.go 2022-11-15 23:06:31.562057797 +0100
@@ -0,0 +1,1101 @@
+package raft
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "strconv"
+ "sync"
+ "time"
+
+ "github.com/hashicorp/go-hclog"
+
+ "github.com/armon/go-metrics"
+)
+
+const (
+ // This is the current suggested max size of the data in a raft log entry.
+ // This is based on current architecture, default timing, etc. Clients can
+ // ignore this value if they want as there is no actual hard checking
+ // within the library. As the library is enhanced this value may change
+ // over time to reflect current suggested maximums.
+ //
+ // Increasing beyond this risks RPC IO taking too long and preventing
+ // timely heartbeat signals which are sent in serial in current transports,
+ // potentially causing leadership instability.
+ SuggestedMaxDataSize = 512 * 1024
+)
+
+var (
+ // ErrLeader is returned when an operation can't be completed on a
+ // leader node.
+ ErrLeader = errors.New("node is the leader")
+
+ // ErrNotLeader is returned when an operation can't be completed on a
+ // follower or candidate node.
+ ErrNotLeader = errors.New("node is not the leader")
+
+ // ErrLeadershipLost is returned when a leader fails to commit a log entry
+ // because it's been deposed in the process.
+ ErrLeadershipLost = errors.New("leadership lost while committing log")
+
+ // ErrAbortedByRestore is returned when a leader fails to commit a log
+ // entry because it's been superseded by a user snapshot restore.
+ ErrAbortedByRestore = errors.New("snapshot restored while committing log")
+
+ // ErrRaftShutdown is returned when operations are requested against an
+ // inactive Raft.
+ ErrRaftShutdown = errors.New("raft is already shutdown")
+
+ // ErrEnqueueTimeout is returned when a command fails due to a timeout.
+ ErrEnqueueTimeout = errors.New("timed out enqueuing operation")
+
+ // ErrNothingNewToSnapshot is returned when trying to create a snapshot
+ // but there's nothing new commited to the FSM since we started.
+ ErrNothingNewToSnapshot = errors.New("nothing new to snapshot")
+
+ // ErrUnsupportedProtocol is returned when an operation is attempted
+ // that's not supported by the current protocol version.
+ ErrUnsupportedProtocol = errors.New("operation not supported with current protocol version")
+
+ // ErrCantBootstrap is returned when attempt is made to bootstrap a
+ // cluster that already has state present.
+ ErrCantBootstrap = errors.New("bootstrap only works on new clusters")
+
+ // ErrLeadershipTransferInProgress is returned when the leader is rejecting
+ // client requests because it is attempting to transfer leadership.
+ ErrLeadershipTransferInProgress = errors.New("leadership transfer in progress")
+)
+
+// Raft implements a Raft node.
+type Raft struct {
+ raftState
+
+ // protocolVersion is used to inter-operate with Raft servers running
+ // different versions of the library. See comments in config.go for more
+ // details.
+ protocolVersion ProtocolVersion
+
+ // applyCh is used to async send logs to the main thread to
+ // be committed and applied to the FSM.
+ applyCh chan *logFuture
+
+ // Configuration provided at Raft initialization
+ conf Config
+
+ // FSM is the client state machine to apply commands to
+ fsm FSM
+
+ // fsmMutateCh is used to send state-changing updates to the FSM. This
+ // receives pointers to commitTuple structures when applying logs or
+ // pointers to restoreFuture structures when restoring a snapshot. We
+ // need control over the order of these operations when doing user
+ // restores so that we finish applying any old log applies before we
+ // take a user snapshot on the leader, otherwise we might restore the
+ // snapshot and apply old logs to it that were in the pipe.
+ fsmMutateCh chan interface{}
+
+ // fsmSnapshotCh is used to trigger a new snapshot being taken
+ fsmSnapshotCh chan *reqSnapshotFuture
+
+ // lastContact is the last time we had contact from the
+ // leader node. This can be used to gauge staleness.
+ lastContact time.Time
+ lastContactLock sync.RWMutex
+
+ // Leader is the current cluster leader
+ leader ServerAddress
+ leaderLock sync.RWMutex
+
+ // leaderCh is used to notify of leadership changes
+ leaderCh chan bool
+
+ // leaderState used only while state is leader
+ leaderState leaderState
+
+ // candidateFromLeadershipTransfer is used to indicate that this server became
+ // candidate because the leader tries to transfer leadership. This flag is
+ // used in RequestVoteRequest to express that a leadership transfer is going
+ // on.
+ candidateFromLeadershipTransfer bool
+
+ // Stores our local server ID, used to avoid sending RPCs to ourself
+ localID ServerID
+
+ // Stores our local addr
+ localAddr ServerAddress
+
+ // Used for our logging
+ logger hclog.Logger
+
+ // LogStore provides durable storage for logs
+ logs LogStore
+
+ // Used to request the leader to make configuration changes.
+ configurationChangeCh chan *configurationChangeFuture
+
+ // Tracks the latest configuration and latest committed configuration from
+ // the log/snapshot.
+ configurations configurations
+
+ // RPC chan comes from the transport layer
+ rpcCh <-chan RPC
+
+ // Shutdown channel to exit, protected to prevent concurrent exits
+ shutdown bool
+ shutdownCh chan struct{}
+ shutdownLock sync.Mutex
+
+ // snapshots is used to store and retrieve snapshots
+ snapshots SnapshotStore
+
+ // userSnapshotCh is used for user-triggered snapshots
+ userSnapshotCh chan *userSnapshotFuture
+
+ // userRestoreCh is used for user-triggered restores of external
+ // snapshots
+ userRestoreCh chan *userRestoreFuture
+
+ // stable is a StableStore implementation for durable state
+ // It provides stable storage for many fields in raftState
+ stable StableStore
+
+ // The transport layer we use
+ trans Transport
+
+ // verifyCh is used to async send verify futures to the main thread
+ // to verify we are still the leader
+ verifyCh chan *verifyFuture
+
+ // configurationsCh is used to get the configuration data safely from
+ // outside of the main thread.
+ configurationsCh chan *configurationsFuture
+
+ // bootstrapCh is used to attempt an initial bootstrap from outside of
+ // the main thread.
+ bootstrapCh chan *bootstrapFuture
+
+ // List of observers and the mutex that protects them. The observers list
+ // is indexed by an artificial ID which is used for deregistration.
+ observersLock sync.RWMutex
+ observers map[uint64]*Observer
+
+ // leadershipTransferCh is used to start a leadership transfer from outside of
+ // the main thread.
+ leadershipTransferCh chan *leadershipTransferFuture
+}
+
+// BootstrapCluster initializes a server's storage with the given cluster
+// configuration. This should only be called at the beginning of time for the
+// cluster with an identical configuration listing all Voter servers. There is
+// no need to bootstrap Nonvoter and Staging servers.
+//
+// A cluster can only be bootstrapped once from a single participating Voter
+// server. Any further attempts to bootstrap will return an error that can be
+// safely ignored.
+//
+// One sane approach is to bootstrap a single server with a configuration
+// listing just itself as a Voter, then invoke AddVoter() on it to add other
+// servers to the cluster.
+func BootstrapCluster(conf *Config, logs LogStore, stable StableStore,
+ snaps SnapshotStore, trans Transport, configuration Configuration) error {
+ // Validate the Raft server config.
+ if err := ValidateConfig(conf); err != nil {
+ return err
+ }
+
+ // Sanity check the Raft peer configuration.
+ if err := checkConfiguration(configuration); err != nil {
+ return err
+ }
+
+ // Make sure the cluster is in a clean state.
+ hasState, err := HasExistingState(logs, stable, snaps)
+ if err != nil {
+ return fmt.Errorf("failed to check for existing state: %v", err)
+ }
+ if hasState {
+ return ErrCantBootstrap
+ }
+
+ // Set current term to 1.
+ if err := stable.SetUint64(keyCurrentTerm, 1); err != nil {
+ return fmt.Errorf("failed to save current term: %v", err)
+ }
+
+ // Append configuration entry to log.
+ entry := &Log{
+ Index: 1,
+ Term: 1,
+ }
+ if conf.ProtocolVersion < 3 {
+ entry.Type = LogRemovePeerDeprecated
+ entry.Data = encodePeers(configuration, trans)
+ } else {
+ entry.Type = LogConfiguration
+ entry.Data = encodeConfiguration(configuration)
+ }
+ if err := logs.StoreLog(entry); err != nil {
+ return fmt.Errorf("failed to append configuration entry to log: %v", err)
+ }
+
+ return nil
+}
+
+// RecoverCluster is used to manually force a new configuration in order to
+// recover from a loss of quorum where the current configuration cannot be
+// restored, such as when several servers die at the same time. This works by
+// reading all the current state for this server, creating a snapshot with the
+// supplied configuration, and then truncating the Raft log. This is the only
+// safe way to force a given configuration without actually altering the log to
+// insert any new entries, which could cause conflicts with other servers with
+// different state.
+//
+// WARNING! This operation implicitly commits all entries in the Raft log, so
+// in general this is an extremely unsafe operation. If you've lost your other
+// servers and are performing a manual recovery, then you've also lost the
+// commit information, so this is likely the best you can do, but you should be
+// aware that calling this can cause Raft log entries that were in the process
+// of being replicated but not yet be committed to be committed.
+//
+// Note the FSM passed here is used for the snapshot operations and will be
+// left in a state that should not be used by the application. Be sure to
+// discard this FSM and any associated state and provide a fresh one when
+// calling NewRaft later.
+//
+// A typical way to recover the cluster is to shut down all servers and then
+// run RecoverCluster on every server using an identical configuration. When
+// the cluster is then restarted, and election should occur and then Raft will
+// resume normal operation. If it's desired to make a particular server the
+// leader, this can be used to inject a new configuration with that server as
+// the sole voter, and then join up other new clean-state peer servers using
+// the usual APIs in order to bring the cluster back into a known state.
+func RecoverCluster(conf *Config, fsm FSM, logs LogStore, stable StableStore,
+ snaps SnapshotStore, trans Transport, configuration Configuration) error {
+ // Validate the Raft server config.
+ if err := ValidateConfig(conf); err != nil {
+ return err
+ }
+
+ // Sanity check the Raft peer configuration.
+ if err := checkConfiguration(configuration); err != nil {
+ return err
+ }
+
+ // Refuse to recover if there's no existing state. This would be safe to
+ // do, but it is likely an indication of an operator error where they
+ // expect data to be there and it's not. By refusing, we force them
+ // to show intent to start a cluster fresh by explicitly doing a
+ // bootstrap, rather than quietly fire up a fresh cluster here.
+ hasState, err := HasExistingState(logs, stable, snaps)
+ if err != nil {
+ return fmt.Errorf("failed to check for existing state: %v", err)
+ }
+ if !hasState {
+ return fmt.Errorf("refused to recover cluster with no initial state, this is probably an operator error")
+ }
+
+ // Attempt to restore any snapshots we find, newest to oldest.
+ var snapshotIndex uint64
+ var snapshotTerm uint64
+ snapshots, err := snaps.List()
+ if err != nil {
+ return fmt.Errorf("failed to list snapshots: %v", err)
+ }
+ for _, snapshot := range snapshots {
+ if !conf.NoSnapshotRestoreOnStart {
+ _, source, err := snaps.Open(snapshot.ID)
+ if err != nil {
+ // Skip this one and try the next. We will detect if we
+ // couldn't open any snapshots.
+ continue
+ }
+
+ err = fsm.Restore(source)
+ // Close the source after the restore has completed
+ source.Close()
+ if err != nil {
+ // Same here, skip and try the next one.
+ continue
+ }
+ }
+
+ snapshotIndex = snapshot.Index
+ snapshotTerm = snapshot.Term
+ break
+ }
+ if len(snapshots) > 0 && (snapshotIndex == 0 || snapshotTerm == 0) {
+ return fmt.Errorf("failed to restore any of the available snapshots")
+ }
+
+ // The snapshot information is the best known end point for the data
+ // until we play back the Raft log entries.
+ lastIndex := snapshotIndex
+ lastTerm := snapshotTerm
+
+ // Apply any Raft log entries past the snapshot.
+ lastLogIndex, err := logs.LastIndex()
+ if err != nil {
+ return fmt.Errorf("failed to find last log: %v", err)
+ }
+ for index := snapshotIndex + 1; index <= lastLogIndex; index++ {
+ var entry Log
+ if err := logs.GetLog(index, &entry); err != nil {
+ return fmt.Errorf("failed to get log at index %d: %v", index, err)
+ }
+ if entry.Type == LogCommand {
+ _ = fsm.Apply(&entry)
+ }
+ lastIndex = entry.Index
+ lastTerm = entry.Term
+ }
+
+ // Create a new snapshot, placing the configuration in as if it was
+ // committed at index 1.
+ snapshot, err := fsm.Snapshot()
+ if err != nil {
+ return fmt.Errorf("failed to snapshot FSM: %v", err)
+ }
+ version := getSnapshotVersion(conf.ProtocolVersion)
+ sink, err := snaps.Create(version, lastIndex, lastTerm, configuration, 1, trans)
+ if err != nil {
+ return fmt.Errorf("failed to create snapshot: %v", err)
+ }
+ if err := snapshot.Persist(sink); err != nil {
+ return fmt.Errorf("failed to persist snapshot: %v", err)
+ }
+ if err := sink.Close(); err != nil {
+ return fmt.Errorf("failed to finalize snapshot: %v", err)
+ }
+
+ // Compact the log so that we don't get bad interference from any
+ // configuration change log entries that might be there.
+ firstLogIndex, err := logs.FirstIndex()
+ if err != nil {
+ return fmt.Errorf("failed to get first log index: %v", err)
+ }
+ if err := logs.DeleteRange(firstLogIndex, lastLogIndex); err != nil {
+ return fmt.Errorf("log compaction failed: %v", err)
+ }
+
+ return nil
+}
+
+// HasExistingState returns true if the server has any existing state (logs,
+// knowledge of a current term, or any snapshots).
+func HasExistingState(logs LogStore, stable StableStore, snaps SnapshotStore) (bool, error) {
+ // Make sure we don't have a current term.
+ currentTerm, err := stable.GetUint64(keyCurrentTerm)
+ if err == nil {
+ if currentTerm > 0 {
+ return true, nil
+ }
+ } else {
+ if err.Error() != "not found" {
+ return false, fmt.Errorf("failed to read current term: %v", err)
+ }
+ }
+
+ // Make sure we have an empty log.
+ lastIndex, err := logs.LastIndex()
+ if err != nil {
+ return false, fmt.Errorf("failed to get last log index: %v", err)
+ }
+ if lastIndex > 0 {
+ return true, nil
+ }
+
+ // Make sure we have no snapshots
+ snapshots, err := snaps.List()
+ if err != nil {
+ return false, fmt.Errorf("failed to list snapshots: %v", err)
+ }
+ if len(snapshots) > 0 {
+ return true, nil
+ }
+
+ return false, nil
+}
+
+// NewRaft is used to construct a new Raft node. It takes a configuration, as well
+// as implementations of various interfaces that are required. If we have any
+// old state, such as snapshots, logs, peers, etc, all those will be restored
+// when creating the Raft node.
+func NewRaft(conf *Config, fsm FSM, logs LogStore, stable StableStore, snaps SnapshotStore, trans Transport) (*Raft, error) {
+ // Validate the configuration.
+ if err := ValidateConfig(conf); err != nil {
+ return nil, err
+ }
+
+ // Ensure we have a LogOutput.
+ var logger hclog.Logger
+ if conf.Logger != nil {
+ logger = conf.Logger
+ } else {
+ if conf.LogOutput == nil {
+ conf.LogOutput = os.Stderr
+ }
+
+ logger = hclog.New(&hclog.LoggerOptions{
+ Name: "raft",
+ Level: hclog.LevelFromString(conf.LogLevel),
+ Output: conf.LogOutput,
+ })
+ }
+
+ // Try to restore the current term.
+ currentTerm, err := stable.GetUint64(keyCurrentTerm)
+ if err != nil && err.Error() != "not found" {
+ return nil, fmt.Errorf("failed to load current term: %v", err)
+ }
+
+ // Read the index of the last log entry.
+ lastIndex, err := logs.LastIndex()
+ if err != nil {
+ return nil, fmt.Errorf("failed to find last log: %v", err)
+ }
+
+ // Get the last log entry.
+ var lastLog Log
+ if lastIndex > 0 {
+ if err = logs.GetLog(lastIndex, &lastLog); err != nil {
+ return nil, fmt.Errorf("failed to get last log at index %d: %v", lastIndex, err)
+ }
+ }
+
+ // Make sure we have a valid server address and ID.
+ protocolVersion := conf.ProtocolVersion
+ localAddr := ServerAddress(trans.LocalAddr())
+ localID := conf.LocalID
+
+ // TODO (slackpad) - When we deprecate protocol version 2, remove this
+ // along with the AddPeer() and RemovePeer() APIs.
+ if protocolVersion < 3 && string(localID) != string(localAddr) {
+ return nil, fmt.Errorf("when running with ProtocolVersion < 3, LocalID must be set to the network address")
+ }
+
+ // Create Raft struct.
+ r := &Raft{
+ protocolVersion: protocolVersion,
+ applyCh: make(chan *logFuture),
+ conf: *conf,
+ fsm: fsm,
+ fsmMutateCh: make(chan interface{}, 128),
+ fsmSnapshotCh: make(chan *reqSnapshotFuture),
+ leaderCh: make(chan bool),
+ localID: localID,
+ localAddr: localAddr,
+ logger: logger,
+ logs: logs,
+ configurationChangeCh: make(chan *configurationChangeFuture),
+ configurations: configurations{},
+ rpcCh: trans.Consumer(),
+ snapshots: snaps,
+ userSnapshotCh: make(chan *userSnapshotFuture),
+ userRestoreCh: make(chan *userRestoreFuture),
+ shutdownCh: make(chan struct{}),
+ stable: stable,
+ trans: trans,
+ verifyCh: make(chan *verifyFuture, 64),
+ configurationsCh: make(chan *configurationsFuture, 8),
+ bootstrapCh: make(chan *bootstrapFuture),
+ observers: make(map[uint64]*Observer),
+ leadershipTransferCh: make(chan *leadershipTransferFuture, 1),
+ }
+
+ // Initialize as a follower.
+ r.setState(Follower)
+
+ // Start as leader if specified. This should only be used
+ // for testing purposes.
+ if conf.StartAsLeader {
+ r.setState(Leader)
+ r.setLeader(r.localAddr)
+ }
+
+ // Restore the current term and the last log.
+ r.setCurrentTerm(currentTerm)
+ r.setLastLog(lastLog.Index, lastLog.Term)
+
+ // Attempt to restore a snapshot if there are any.
+ if err := r.restoreSnapshot(); err != nil {
+ return nil, err
+ }
+
+ // Scan through the log for any configuration change entries.
+ snapshotIndex, _ := r.getLastSnapshot()
+ for index := snapshotIndex + 1; index <= lastLog.Index; index++ {
+ var entry Log
+ if err := r.logs.GetLog(index, &entry); err != nil {
+ r.logger.Error(fmt.Sprintf("Failed to get log at %d: %v", index, err))
+ panic(err)
+ }
+ r.processConfigurationLogEntry(&entry)
+ }
+ r.logger.Info(fmt.Sprintf("Initial configuration (index=%d): %+v",
+ r.configurations.latestIndex, r.configurations.latest.Servers))
+
+ // Setup a heartbeat fast-path to avoid head-of-line
+ // blocking where possible. It MUST be safe for this
+ // to be called concurrently with a blocking RPC.
+ trans.SetHeartbeatHandler(r.processHeartbeat)
+
+ // Start the background work.
+ r.goFunc(r.run)
+ r.goFunc(r.runFSM)
+ r.goFunc(r.runSnapshots)
+ return r, nil
+}
+
+// restoreSnapshot attempts to restore the latest snapshots, and fails if none
+// of them can be restored. This is called at initialization time, and is
+// completely unsafe to call at any other time.
+func (r *Raft) restoreSnapshot() error {
+ snapshots, err := r.snapshots.List()
+ if err != nil {
+ r.logger.Error(fmt.Sprintf("Failed to list snapshots: %v", err))
+ return err
+ }
+
+ // Try to load in order of newest to oldest
+ for _, snapshot := range snapshots {
+ if !r.conf.NoSnapshotRestoreOnStart {
+ _, source, err := r.snapshots.Open(snapshot.ID)
+ if err != nil {
+ r.logger.Error(fmt.Sprintf("Failed to open snapshot %v: %v", snapshot.ID, err))
+ continue
+ }
+
+ err = r.fsm.Restore(source)
+ // Close the source after the restore has completed
+ source.Close()
+ if err != nil {
+ r.logger.Error(fmt.Sprintf("Failed to restore snapshot %v: %v", snapshot.ID, err))
+ continue
+ }
+
+ r.logger.Info(fmt.Sprintf("Restored from snapshot %v", snapshot.ID))
+ }
+ // Update the lastApplied so we don't replay old logs
+ r.setLastApplied(snapshot.Index)
+
+ // Update the last stable snapshot info
+ r.setLastSnapshot(snapshot.Index, snapshot.Term)
+
+ // Update the configuration
+ if snapshot.Version > 0 {
+ r.configurations.committed = snapshot.Configuration
+ r.configurations.committedIndex = snapshot.ConfigurationIndex
+ r.configurations.latest = snapshot.Configuration
+ r.configurations.latestIndex = snapshot.ConfigurationIndex
+ } else {
+ configuration := decodePeers(snapshot.Peers, r.trans)
+ r.configurations.committed = configuration
+ r.configurations.committedIndex = snapshot.Index
+ r.configurations.latest = configuration
+ r.configurations.latestIndex = snapshot.Index
+ }
+
+ // Success!
+ return nil
+ }
+
+ // If we had snapshots and failed to load them, its an error
+ if len(snapshots) > 0 {
+ return fmt.Errorf("failed to load any existing snapshots")
+ }
+ return nil
+}
+
+// BootstrapCluster is equivalent to non-member BootstrapCluster but can be
+// called on an un-bootstrapped Raft instance after it has been created. This
+// should only be called at the beginning of time for the cluster with an
+// identical configuration listing all Voter servers. There is no need to
+// bootstrap Nonvoter and Staging servers.
+//
+// A cluster can only be bootstrapped once from a single participating Voter
+// server. Any further attempts to bootstrap will return an error that can be
+// safely ignored.
+//
+// One sane approach is to bootstrap a single server with a configuration
+// listing just itself as a Voter, then invoke AddVoter() on it to add other
+// servers to the cluster.
+func (r *Raft) BootstrapCluster(configuration Configuration) Future {
+ bootstrapReq := &bootstrapFuture{}
+ bootstrapReq.init()
+ bootstrapReq.configuration = configuration
+ select {
+ case <-r.shutdownCh:
+ return errorFuture{ErrRaftShutdown}
+ case r.bootstrapCh <- bootstrapReq:
+ return bootstrapReq
+ }
+}
+
+// Leader is used to return the current leader of the cluster.
+// It may return empty string if there is no current leader
+// or the leader is unknown.
+func (r *Raft) Leader() ServerAddress {
+ r.leaderLock.RLock()
+ leader := r.leader
+ r.leaderLock.RUnlock()
+ return leader
+}
+
+// Apply is used to apply a command to the FSM in a highly consistent
+// manner. This returns a future that can be used to wait on the application.
+// An optional timeout can be provided to limit the amount of time we wait
+// for the command to be started. This must be run on the leader or it
+// will fail.
+func (r *Raft) Apply(cmd []byte, timeout time.Duration) ApplyFuture {
+ return r.ApplyLog(Log{Data: cmd}, timeout)
+}
+
+// ApplyLog performs Apply but takes in a Log directly. The only values
+// currently taken from the submitted Log are Data and Extensions.
+func (r *Raft) ApplyLog(log Log, timeout time.Duration) ApplyFuture {
+ metrics.IncrCounter([]string{"raft", "apply"}, 1)
+
+ var timer <-chan time.Time
+ if timeout > 0 {
+ timer = time.After(timeout)
+ }
+
+ // Create a log future, no index or term yet
+ logFuture := &logFuture{
+ log: Log{
+ Type: LogCommand,
+ Data: log.Data,
+ Extensions: log.Extensions,
+ },
+ }
+ logFuture.init()
+
+ select {
+ case <-timer:
+ return errorFuture{ErrEnqueueTimeout}
+ case <-r.shutdownCh:
+ return errorFuture{ErrRaftShutdown}
+ case r.applyCh <- logFuture:
+ return logFuture
+ }
+}
+
+// Barrier is used to issue a command that blocks until all preceeding
+// operations have been applied to the FSM. It can be used to ensure the
+// FSM reflects all queued writes. An optional timeout can be provided to
+// limit the amount of time we wait for the command to be started. This
+// must be run on the leader or it will fail.
+func (r *Raft) Barrier(timeout time.Duration) Future {
+ metrics.IncrCounter([]string{"raft", "barrier"}, 1)
+ var timer <-chan time.Time
+ if timeout > 0 {
+ timer = time.After(timeout)
+ }
+
+ // Create a log future, no index or term yet
+ logFuture := &logFuture{
+ log: Log{
+ Type: LogBarrier,
+ },
+ }
+ logFuture.init()
+
+ select {
+ case <-timer:
+ return errorFuture{ErrEnqueueTimeout}
+ case <-r.shutdownCh:
+ return errorFuture{ErrRaftShutdown}
+ case r.applyCh <- logFuture:
+ return logFuture
+ }
+}
+
+// VerifyLeader is used to ensure the current node is still
+// the leader. This can be done to prevent stale reads when a
+// new leader has potentially been elected.
+func (r *Raft) VerifyLeader() Future {
+ metrics.IncrCounter([]string{"raft", "verify_leader"}, 1)
+ verifyFuture := &verifyFuture{}
+ verifyFuture.init()
+ select {
+ case <-r.shutdownCh:
+ return errorFuture{ErrRaftShutdown}
+ case r.verifyCh <- verifyFuture:
+ return verifyFuture
+ }
+}
+
+// GetConfiguration returns the latest configuration and its associated index
+// currently in use. This may not yet be committed. This must not be called on
+// the main thread (which can access the information directly).
+func (r *Raft) GetConfiguration() ConfigurationFuture {
+ configReq := &configurationsFuture{}
+ configReq.init()
+ select {
+ case <-r.shutdownCh:
+ configReq.respond(ErrRaftShutdown)
+ return configReq
+ case r.configurationsCh <- configReq:
+ return configReq
+ }
+}
+
+// AddPeer (deprecated) is used to add a new peer into the cluster. This must be
+// run on the leader or it will fail. Use AddVoter/AddNonvoter instead.
+func (r *Raft) AddPeer(peer ServerAddress) Future {
+ if r.protocolVersion > 2 {
+ return errorFuture{ErrUnsupportedProtocol}
+ }
+
+ return r.requestConfigChange(configurationChangeRequest{
+ command: AddStaging,
+ serverID: ServerID(peer),
+ serverAddress: peer,
+ prevIndex: 0,
+ }, 0)
+}
+
+// RemovePeer (deprecated) is used to remove a peer from the cluster. If the
+// current leader is being removed, it will cause a new election
+// to occur. This must be run on the leader or it will fail.
+// Use RemoveServer instead.
+func (r *Raft) RemovePeer(peer ServerAddress) Future {
+ if r.protocolVersion > 2 {
+ return errorFuture{ErrUnsupportedProtocol}
+ }
+
+ return r.requestConfigChange(configurationChangeRequest{
+ command: RemoveServer,
+ serverID: ServerID(peer),
+ prevIndex: 0,
+ }, 0)
+}
+
+// AddVoter will add the given server to the cluster as a staging server. If the
+// server is already in the cluster as a voter, this updates the server's address.
+// This must be run on the leader or it will fail. The leader will promote the
+// staging server to a voter once that server is ready. If nonzero, prevIndex is
+// the index of the only configuration upon which this change may be applied; if
+// another configuration entry has been added in the meantime, this request will
+// fail. If nonzero, timeout is how long this server should wait before the
+// configuration change log entry is appended.
+func (r *Raft) AddVoter(id ServerID, address ServerAddress, prevIndex uint64, timeout time.Duration) IndexFuture {
+ if r.protocolVersion < 2 {
+ return errorFuture{ErrUnsupportedProtocol}
+ }
+
+ return r.requestConfigChange(configurationChangeRequest{
+ command: AddStaging,
+ serverID: id,
+ serverAddress: address,
+ prevIndex: prevIndex,
+ }, timeout)
+}
+
+// AddNonvoter will add the given server to the cluster but won't assign it a
+// vote. The server will receive log entries, but it won't participate in
+// elections or log entry commitment. If the server is already in the cluster,
+// this updates the server's address. This must be run on the leader or it will
+// fail. For prevIndex and timeout, see AddVoter.
+func (r *Raft) AddNonvoter(id ServerID, address ServerAddress, prevIndex uint64, timeout time.Duration) IndexFuture {
+ if r.protocolVersion < 3 {
+ return errorFuture{ErrUnsupportedProtocol}
+ }
+
+ return r.requestConfigChange(configurationChangeRequest{
+ command: AddNonvoter,
+ serverID: id,
+ serverAddress: address,
+ prevIndex: prevIndex,
+ }, timeout)
+}
+
+// RemoveServer will remove the given server from the cluster. If the current
+// leader is being removed, it will cause a new election to occur. This must be
+// run on the leader or it will fail. For prevIndex and timeout, see AddVoter.
+func (r *Raft) RemoveServer(id ServerID, prevIndex uint64, timeout time.Duration) IndexFuture {
+ if r.protocolVersion < 2 {
+ return errorFuture{ErrUnsupportedProtocol}
+ }
+
+ return r.requestConfigChange(configurationChangeRequest{
+ command: RemoveServer,
+ serverID: id,
+ prevIndex: prevIndex,
+ }, timeout)
+}
+
+// DemoteVoter will take away a server's vote, if it has one. If present, the
+// server will continue to receive log entries, but it won't participate in
+// elections or log entry commitment. If the server is not in the cluster, this
+// does nothing. This must be run on the leader or it will fail. For prevIndex
+// and timeout, see AddVoter.
+func (r *Raft) DemoteVoter(id ServerID, prevIndex uint64, timeout time.Duration) IndexFuture {
+ if r.protocolVersion < 3 {
+ return errorFuture{ErrUnsupportedProtocol}
+ }
+
+ return r.requestConfigChange(configurationChangeRequest{
+ command: DemoteVoter,
+ serverID: id,
+ prevIndex: prevIndex,
+ }, timeout)
+}
+
+// Shutdown is used to stop the Raft background routines.
+// This is not a graceful operation. Provides a future that
+// can be used to block until all background routines have exited.
+func (r *Raft) Shutdown() Future {
+ r.shutdownLock.Lock()
+ defer r.shutdownLock.Unlock()
+
+ if !r.shutdown {
+ close(r.shutdownCh)
+ r.shutdown = true
+ r.setState(Shutdown)
+ return &shutdownFuture{r}
+ }
+
+ // avoid closing transport twice
+ return &shutdownFuture{nil}
+}
+
+// Snapshot is used to manually force Raft to take a snapshot. Returns a future
+// that can be used to block until complete, and that contains a function that
+// can be used to open the snapshot.
+func (r *Raft) Snapshot() SnapshotFuture {
+ future := &userSnapshotFuture{}
+ future.init()
+ select {
+ case r.userSnapshotCh <- future:
+ return future
+ case <-r.shutdownCh:
+ future.respond(ErrRaftShutdown)
+ return future
+ }
+}
+
+// Restore is used to manually force Raft to consume an external snapshot, such
+// as if restoring from a backup. We will use the current Raft configuration,
+// not the one from the snapshot, so that we can restore into a new cluster. We
+// will also use the higher of the index of the snapshot, or the current index,
+// and then add 1 to that, so we force a new state with a hole in the Raft log,
+// so that the snapshot will be sent to followers and used for any new joiners.
+// This can only be run on the leader, and blocks until the restore is complete
+// or an error occurs.
+//
+// WARNING! This operation has the leader take on the state of the snapshot and
+// then sets itself up so that it replicates that to its followers though the
+// install snapshot process. This involves a potentially dangerous period where
+// the leader commits ahead of its followers, so should only be used for disaster
+// recovery into a fresh cluster, and should not be used in normal operations.
+func (r *Raft) Restore(meta *SnapshotMeta, reader io.Reader, timeout time.Duration) error {
+ metrics.IncrCounter([]string{"raft", "restore"}, 1)
+ var timer <-chan time.Time
+ if timeout > 0 {
+ timer = time.After(timeout)
+ }
+
+ // Perform the restore.
+ restore := &userRestoreFuture{
+ meta: meta,
+ reader: reader,
+ }
+ restore.init()
+ select {
+ case <-timer:
+ return ErrEnqueueTimeout
+ case <-r.shutdownCh:
+ return ErrRaftShutdown
+ case r.userRestoreCh <- restore:
+ // If the restore is ingested then wait for it to complete.
+ if err := restore.Error(); err != nil {
+ return err
+ }
+ }
+
+ // Apply a no-op log entry. Waiting for this allows us to wait until the
+ // followers have gotten the restore and replicated at least this new
+ // entry, which shows that we've also faulted and installed the
+ // snapshot with the contents of the restore.
+ noop := &logFuture{
+ log: Log{
+ Type: LogNoop,
+ },
+ }
+ noop.init()
+ select {
+ case <-timer:
+ return ErrEnqueueTimeout
+ case <-r.shutdownCh:
+ return ErrRaftShutdown
+ case r.applyCh <- noop:
+ return noop.Error()
+ }
+}
+
+// State is used to return the current raft state.
+func (r *Raft) State() RaftState {
+ return r.getState()
+}
+
+// LeaderCh is used to get a channel which delivers signals on
+// acquiring or losing leadership. It sends true if we become
+// the leader, and false if we lose it. The channel is not buffered,
+// and does not block on writes.
+func (r *Raft) LeaderCh() <-chan bool {
+ return r.leaderCh
+}
+
+// String returns a string representation of this Raft node.
+func (r *Raft) String() string {
+ return fmt.Sprintf("Node at %s [%v]", r.localAddr, r.getState())
+}
+
+// LastContact returns the time of last contact by a leader.
+// This only makes sense if we are currently a follower.
+func (r *Raft) LastContact() time.Time {
+ r.lastContactLock.RLock()
+ last := r.lastContact
+ r.lastContactLock.RUnlock()
+ return last
+}
+
+// Stats is used to return a map of various internal stats. This
+// should only be used for informative purposes or debugging.
+//
+// Keys are: "state", "term", "last_log_index", "last_log_term",
+// "commit_index", "applied_index", "fsm_pending",
+// "last_snapshot_index", "last_snapshot_term",
+// "latest_configuration", "last_contact", and "num_peers".
+//
+// The value of "state" is a numeric constant representing one of
+// the possible leadership states the node is in at any given time.
+// the possible states are: "Follower", "Candidate", "Leader", "Shutdown".
+//
+// The value of "latest_configuration" is a string which contains
+// the id of each server, its suffrage status, and its address.
+//
+// The value of "last_contact" is either "never" if there
+// has been no contact with a leader, "0" if the node is in the
+// leader state, or the time since last contact with a leader
+// formatted as a string.
+//
+// The value of "num_peers" is the number of other voting servers in the
+// cluster, not including this node. If this node isn't part of the
+// configuration then this will be "0".
+//
+// All other values are uint64s, formatted as strings.
+func (r *Raft) Stats() map[string]string {
+ toString := func(v uint64) string {
+ return strconv.FormatUint(v, 10)
+ }
+ lastLogIndex, lastLogTerm := r.getLastLog()
+ lastSnapIndex, lastSnapTerm := r.getLastSnapshot()
+ s := map[string]string{
+ "state": r.getState().String(),
+ "term": toString(r.getCurrentTerm()),
+ "last_log_index": toString(lastLogIndex),
+ "last_log_term": toString(lastLogTerm),
+ "commit_index": toString(r.getCommitIndex()),
+ "applied_index": toString(r.getLastApplied()),
+ "fsm_pending": toString(uint64(len(r.fsmMutateCh))),
+ "last_snapshot_index": toString(lastSnapIndex),
+ "last_snapshot_term": toString(lastSnapTerm),
+ "protocol_version": toString(uint64(r.protocolVersion)),
+ "protocol_version_min": toString(uint64(ProtocolVersionMin)),
+ "protocol_version_max": toString(uint64(ProtocolVersionMax)),
+ "snapshot_version_min": toString(uint64(SnapshotVersionMin)),
+ "snapshot_version_max": toString(uint64(SnapshotVersionMax)),
+ }
+
+ future := r.GetConfiguration()
+ if err := future.Error(); err != nil {
+ r.logger.Warn(fmt.Sprintf("could not get configuration for Stats: %v", err))
+ } else {
+ configuration := future.Configuration()
+ s["latest_configuration_index"] = toString(future.Index())
+ s["latest_configuration"] = fmt.Sprintf("%+v", configuration.Servers)
+
+ // This is a legacy metric that we've seen people use in the wild.
+ hasUs := false
+ numPeers := 0
+ for _, server := range configuration.Servers {
+ if server.Suffrage == Voter {
+ if server.ID == r.localID {
+ hasUs = true
+ } else {
+ numPeers++
+ }
+ }
+ }
+ if !hasUs {
+ numPeers = 0
+ }
+ s["num_peers"] = toString(uint64(numPeers))
+ }
+
+ last := r.LastContact()
+ if r.getState() == Leader {
+ s["last_contact"] = "0"
+ } else if last.IsZero() {
+ s["last_contact"] = "never"
+ } else {
+ s["last_contact"] = fmt.Sprintf("%v", time.Now().Sub(last))
+ }
+ return s
+}
+
+// LastIndex returns the last index in stable storage,
+// either from the last log or from the last snapshot.
+func (r *Raft) LastIndex() uint64 {
+ return r.getLastIndex()
+}
+
+// AppliedIndex returns the last index applied to the FSM. This is generally
+// lagging behind the last index, especially for indexes that are persisted but
+// have not yet been considered committed by the leader. NOTE - this reflects
+// the last index that was sent to the application's FSM over the apply channel
+// but DOES NOT mean that the application's FSM has yet consumed it and applied
+// it to its internal state. Thus, the application's state may lag behind this
+// index.
+func (r *Raft) AppliedIndex() uint64 {
+ return r.getLastApplied()
+}
+
+// LeadershipTransfer will transfer leadership to a server in the cluster.
+// This can only be called from the leader, or it will fail. The leader will
+// stop accepting client requests, make sure the target server is up to date
+// and starts the transfer with a TimeoutNow message. This message has the same
+// effect as if the election timeout on the on the target server fires. Since
+// it is unlikely that another server is starting an election, it is very
+// likely that the target server is able to win the election. Note that raft
+// protocol version 3 is not sufficient to use LeadershipTransfer. A recent
+// version of that library has to be used that includes this feature. Using
+// transfer leadership is safe however in a cluster where not every node has
+// the latest version. If a follower cannot be promoted, it will fail
+// gracefully.
+func (r *Raft) LeadershipTransfer() Future {
+ if r.protocolVersion < 3 {
+ return errorFuture{ErrUnsupportedProtocol}
+ }
+
+ return r.initiateLeadershipTransfer(nil, nil)
+}
+
+// LeadershipTransferToServer does the same as LeadershipTransfer but takes a
+// server in the arguments in case a leadership should be transitioned to a
+// specific server in the cluster. Note that raft protocol version 3 is not
+// sufficient to use LeadershipTransfer. A recent version of that library has
+// to be used that includes this feature. Using transfer leadership is safe
+// however in a cluster where not every node has the latest version. If a
+// follower cannot be promoted, it will fail gracefully.
+func (r *Raft) LeadershipTransferToServer(id ServerID, address ServerAddress) Future {
+ if r.protocolVersion < 3 {
+ return errorFuture{ErrUnsupportedProtocol}
+ }
+
+ return r.initiateLeadershipTransfer(&id, &address)
+}
diff -Naur --color b/vendor/github.com/hashicorp/raft/CHANGELOG.md a/vendor/github.com/hashicorp/raft/CHANGELOG.md
--- b/vendor/github.com/hashicorp/raft/CHANGELOG.md 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/CHANGELOG.md 2022-11-15 23:06:31.562057797 +0100
@@ -0,0 +1,52 @@
+# UNRELEASED
+
+# 1.1.1 (July 23rd, 2019)
+
+FEATURES
+
+* Add support for extensions to be sent on log entries [[GH-353](https://github.com/hashicorp/raft/pull/353)]
+* Add config option to skip snapshot restore on startup [[GH-340](https://github.com/hashicorp/raft/pull/340)]
+* Add optional configuration store interface [[GH-339](https://github.com/hashicorp/raft/pull/339)]
+
+IMPROVEMENTS
+
+* Break out of group commit early when no logs are present [[GH-341](https://github.com/hashicorp/raft/pull/341)]
+
+BUGFIXES
+
+* Fix 64-bit counters on 32-bit platforms [[GH-344](https://github.com/hashicorp/raft/pull/344)]
+* Don't defer closing source in recover/restore operations since it's in a loop [[GH-337](https://github.com/hashicorp/raft/pull/337)]
+
+# 1.1.0 (May 23rd, 2019)
+
+FEATURES
+
+* Add transfer leadership extension [[GH-306](https://github.com/hashicorp/raft/pull/306)]
+
+IMPROVEMENTS
+
+* Move to `go mod` [[GH-323](https://github.com/hashicorp/consul/pull/323)]
+* Leveled log [[GH-321](https://github.com/hashicorp/consul/pull/321)]
+* Add peer changes to observations [[GH-326](https://github.com/hashicorp/consul/pull/326)]
+
+BUGFIXES
+
+* Copy the contents of an InmemSnapshotStore when opening a snapshot [[GH-270](https://github.com/hashicorp/consul/pull/270)]
+* Fix logging panic when converting parameters to strings [[GH-332](https://github.com/hashicorp/consul/pull/332)]
+
+# 1.0.1 (April 12th, 2019)
+
+IMPROVEMENTS
+
+* InMemTransport: Add timeout for sending a message [[GH-313](https://github.com/hashicorp/raft/pull/313)]
+* ensure 'make deps' downloads test dependencies like testify [[GH-310](https://github.com/hashicorp/raft/pull/310)]
+* Clarifies function of CommitTimeout [[GH-309](https://github.com/hashicorp/raft/pull/309)]
+* Add additional metrics regarding log dispatching and committal [[GH-316](https://github.com/hashicorp/raft/pull/316)]
+
+# 1.0.0 (October 3rd, 2017)
+
+v1.0.0 takes the changes that were staged in the library-v2-stage-one branch. This version manages server identities using a UUID, so introduces some breaking API changes. It also versions the Raft protocol, and requires some special steps when interoperating with Raft servers running older versions of the library (see the detailed comment in config.go about version compatibility). You can reference https://github.com/hashicorp/consul/pull/2222 for an idea of what was required to port Consul to these new interfaces.
+
+# 0.1.0 (September 29th, 2017)
+
+v0.1.0 is the original stable version of the library that was in master and has been maintained with no breaking API changes. This was in use by Consul prior to version 0.7.0.
diff -Naur --color b/vendor/github.com/hashicorp/raft/commands.go a/vendor/github.com/hashicorp/raft/commands.go
--- b/vendor/github.com/hashicorp/raft/commands.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/commands.go 2022-11-15 23:06:31.562057797 +0100
@@ -0,0 +1,177 @@
+package raft
+
+// RPCHeader is a common sub-structure used to pass along protocol version and
+// other information about the cluster. For older Raft implementations before
+// versioning was added this will default to a zero-valued structure when read
+// by newer Raft versions.
+type RPCHeader struct {
+ // ProtocolVersion is the version of the protocol the sender is
+ // speaking.
+ ProtocolVersion ProtocolVersion
+}
+
+// WithRPCHeader is an interface that exposes the RPC header.
+type WithRPCHeader interface {
+ GetRPCHeader() RPCHeader
+}
+
+// AppendEntriesRequest is the command used to append entries to the
+// replicated log.
+type AppendEntriesRequest struct {
+ RPCHeader
+
+ // Provide the current term and leader
+ Term uint64
+ Leader []byte
+
+ // Provide the previous entries for integrity checking
+ PrevLogEntry uint64
+ PrevLogTerm uint64
+
+ // New entries to commit
+ Entries []*Log
+
+ // Commit index on the leader
+ LeaderCommitIndex uint64
+}
+
+// See WithRPCHeader.
+func (r *AppendEntriesRequest) GetRPCHeader() RPCHeader {
+ return r.RPCHeader
+}
+
+// AppendEntriesResponse is the response returned from an
+// AppendEntriesRequest.
+type AppendEntriesResponse struct {
+ RPCHeader
+
+ // Newer term if leader is out of date
+ Term uint64
+
+ // Last Log is a hint to help accelerate rebuilding slow nodes
+ LastLog uint64
+
+ // We may not succeed if we have a conflicting entry
+ Success bool
+
+ // There are scenarios where this request didn't succeed
+ // but there's no need to wait/back-off the next attempt.
+ NoRetryBackoff bool
+}
+
+// See WithRPCHeader.
+func (r *AppendEntriesResponse) GetRPCHeader() RPCHeader {
+ return r.RPCHeader
+}
+
+// RequestVoteRequest is the command used by a candidate to ask a Raft peer
+// for a vote in an election.
+type RequestVoteRequest struct {
+ RPCHeader
+
+ // Provide the term and our id
+ Term uint64
+ Candidate []byte
+
+ // Used to ensure safety
+ LastLogIndex uint64
+ LastLogTerm uint64
+
+ // Used to indicate to peers if this vote was triggered by a leadership
+ // transfer. It is required for leadership transfer to work, because servers
+ // wouldn't vote otherwise if they are aware of an existing leader.
+ LeadershipTransfer bool
+}
+
+// See WithRPCHeader.
+func (r *RequestVoteRequest) GetRPCHeader() RPCHeader {
+ return r.RPCHeader
+}
+
+// RequestVoteResponse is the response returned from a RequestVoteRequest.
+type RequestVoteResponse struct {
+ RPCHeader
+
+ // Newer term if leader is out of date.
+ Term uint64
+
+ // Peers is deprecated, but required by servers that only understand
+ // protocol version 0. This is not populated in protocol version 2
+ // and later.
+ Peers []byte
+
+ // Is the vote granted.
+ Granted bool
+}
+
+// See WithRPCHeader.
+func (r *RequestVoteResponse) GetRPCHeader() RPCHeader {
+ return r.RPCHeader
+}
+
+// InstallSnapshotRequest is the command sent to a Raft peer to bootstrap its
+// log (and state machine) from a snapshot on another peer.
+type InstallSnapshotRequest struct {
+ RPCHeader
+ SnapshotVersion SnapshotVersion
+
+ Term uint64
+ Leader []byte
+
+ // These are the last index/term included in the snapshot
+ LastLogIndex uint64
+ LastLogTerm uint64
+
+ // Peer Set in the snapshot. This is deprecated in favor of Configuration
+ // but remains here in case we receive an InstallSnapshot from a leader
+ // that's running old code.
+ Peers []byte
+
+ // Cluster membership.
+ Configuration []byte
+ // Log index where 'Configuration' entry was originally written.
+ ConfigurationIndex uint64
+
+ // Size of the snapshot
+ Size int64
+}
+
+// See WithRPCHeader.
+func (r *InstallSnapshotRequest) GetRPCHeader() RPCHeader {
+ return r.RPCHeader
+}
+
+// InstallSnapshotResponse is the response returned from an
+// InstallSnapshotRequest.
+type InstallSnapshotResponse struct {
+ RPCHeader
+
+ Term uint64
+ Success bool
+}
+
+// See WithRPCHeader.
+func (r *InstallSnapshotResponse) GetRPCHeader() RPCHeader {
+ return r.RPCHeader
+}
+
+// TimeoutNowRequest is the command used by a leader to signal another server to
+// start an election.
+type TimeoutNowRequest struct {
+ RPCHeader
+}
+
+// See WithRPCHeader.
+func (r *TimeoutNowRequest) GetRPCHeader() RPCHeader {
+ return r.RPCHeader
+}
+
+// TimeoutNowResponse is the response to TimeoutNowRequest.
+type TimeoutNowResponse struct {
+ RPCHeader
+}
+
+// See WithRPCHeader.
+func (r *TimeoutNowResponse) GetRPCHeader() RPCHeader {
+ return r.RPCHeader
+}
diff -Naur --color b/vendor/github.com/hashicorp/raft/commitment.go a/vendor/github.com/hashicorp/raft/commitment.go
--- b/vendor/github.com/hashicorp/raft/commitment.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/commitment.go 2022-11-15 23:06:31.565391195 +0100
@@ -0,0 +1,101 @@
+package raft
+
+import (
+ "sort"
+ "sync"
+)
+
+// Commitment is used to advance the leader's commit index. The leader and
+// replication goroutines report in newly written entries with Match(), and
+// this notifies on commitCh when the commit index has advanced.
+type commitment struct {
+ // protects matchIndexes and commitIndex
+ sync.Mutex
+ // notified when commitIndex increases
+ commitCh chan struct{}
+ // voter ID to log index: the server stores up through this log entry
+ matchIndexes map[ServerID]uint64
+ // a quorum stores up through this log entry. monotonically increases.
+ commitIndex uint64
+ // the first index of this leader's term: this needs to be replicated to a
+ // majority of the cluster before this leader may mark anything committed
+ // (per Raft's commitment rule)
+ startIndex uint64
+}
+
+// newCommitment returns an commitment struct that notifies the provided
+// channel when log entries have been committed. A new commitment struct is
+// created each time this server becomes leader for a particular term.
+// 'configuration' is the servers in the cluster.
+// 'startIndex' is the first index created in this term (see
+// its description above).
+func newCommitment(commitCh chan struct{}, configuration Configuration, startIndex uint64) *commitment {
+ matchIndexes := make(map[ServerID]uint64)
+ for _, server := range configuration.Servers {
+ if server.Suffrage == Voter {
+ matchIndexes[server.ID] = 0
+ }
+ }
+ return &commitment{
+ commitCh: commitCh,
+ matchIndexes: matchIndexes,
+ commitIndex: 0,
+ startIndex: startIndex,
+ }
+}
+
+// Called when a new cluster membership configuration is created: it will be
+// used to determine commitment from now on. 'configuration' is the servers in
+// the cluster.
+func (c *commitment) setConfiguration(configuration Configuration) {
+ c.Lock()
+ defer c.Unlock()
+ oldMatchIndexes := c.matchIndexes
+ c.matchIndexes = make(map[ServerID]uint64)
+ for _, server := range configuration.Servers {
+ if server.Suffrage == Voter {
+ c.matchIndexes[server.ID] = oldMatchIndexes[server.ID] // defaults to 0
+ }
+ }
+ c.recalculate()
+}
+
+// Called by leader after commitCh is notified
+func (c *commitment) getCommitIndex() uint64 {
+ c.Lock()
+ defer c.Unlock()
+ return c.commitIndex
+}
+
+// Match is called once a server completes writing entries to disk: either the
+// leader has written the new entry or a follower has replied to an
+// AppendEntries RPC. The given server's disk agrees with this server's log up
+// through the given index.
+func (c *commitment) match(server ServerID, matchIndex uint64) {
+ c.Lock()
+ defer c.Unlock()
+ if prev, hasVote := c.matchIndexes[server]; hasVote && matchIndex > prev {
+ c.matchIndexes[server] = matchIndex
+ c.recalculate()
+ }
+}
+
+// Internal helper to calculate new commitIndex from matchIndexes.
+// Must be called with lock held.
+func (c *commitment) recalculate() {
+ if len(c.matchIndexes) == 0 {
+ return
+ }
+
+ matched := make([]uint64, 0, len(c.matchIndexes))
+ for _, idx := range c.matchIndexes {
+ matched = append(matched, idx)
+ }
+ sort.Sort(uint64Slice(matched))
+ quorumMatchIndex := matched[(len(matched)-1)/2]
+
+ if quorumMatchIndex > c.commitIndex && quorumMatchIndex >= c.startIndex {
+ c.commitIndex = quorumMatchIndex
+ asyncNotifyCh(c.commitCh)
+ }
+}
diff -Naur --color b/vendor/github.com/hashicorp/raft/config.go a/vendor/github.com/hashicorp/raft/config.go
--- b/vendor/github.com/hashicorp/raft/config.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/config.go 2022-11-15 23:06:31.565391195 +0100
@@ -0,0 +1,272 @@
+package raft
+
+import (
+ "fmt"
+ "io"
+ "time"
+
+ "github.com/hashicorp/go-hclog"
+)
+
+// These are the versions of the protocol (which includes RPC messages as
+// well as Raft-specific log entries) that this server can _understand_. Use
+// the ProtocolVersion member of the Config object to control the version of
+// the protocol to use when _speaking_ to other servers. Note that depending on
+// the protocol version being spoken, some otherwise understood RPC messages
+// may be refused. See dispositionRPC for details of this logic.
+//
+// There are notes about the upgrade path in the description of the versions
+// below. If you are starting a fresh cluster then there's no reason not to
+// jump right to the latest protocol version. If you need to interoperate with
+// older, version 0 Raft servers you'll need to drive the cluster through the
+// different versions in order.
+//
+// The version details are complicated, but here's a summary of what's required
+// to get from a version 0 cluster to version 3:
+//
+// 1. In version N of your app that starts using the new Raft library with
+// versioning, set ProtocolVersion to 1.
+// 2. Make version N+1 of your app require version N as a prerequisite (all
+// servers must be upgraded). For version N+1 of your app set ProtocolVersion
+// to 2.
+// 3. Similarly, make version N+2 of your app require version N+1 as a
+// prerequisite. For version N+2 of your app, set ProtocolVersion to 3.
+//
+// During this upgrade, older cluster members will still have Server IDs equal
+// to their network addresses. To upgrade an older member and give it an ID, it
+// needs to leave the cluster and re-enter:
+//
+// 1. Remove the server from the cluster with RemoveServer, using its network
+// address as its ServerID.
+// 2. Update the server's config to use a UUID or something else that is
+// not tied to the machine as the ServerID (restarting the server).
+// 3. Add the server back to the cluster with AddVoter, using its new ID.
+//
+// You can do this during the rolling upgrade from N+1 to N+2 of your app, or
+// as a rolling change at any time after the upgrade.
+//
+// Version History
+//
+// 0: Original Raft library before versioning was added. Servers running this
+// version of the Raft library use AddPeerDeprecated/RemovePeerDeprecated
+// for all configuration changes, and have no support for LogConfiguration.
+// 1: First versioned protocol, used to interoperate with old servers, and begin
+// the migration path to newer versions of the protocol. Under this version
+// all configuration changes are propagated using the now-deprecated
+// RemovePeerDeprecated Raft log entry. This means that server IDs are always
+// set to be the same as the server addresses (since the old log entry type
+// cannot transmit an ID), and only AddPeer/RemovePeer APIs are supported.
+// Servers running this version of the protocol can understand the new
+// LogConfiguration Raft log entry but will never generate one so they can
+// remain compatible with version 0 Raft servers in the cluster.
+// 2: Transitional protocol used when migrating an existing cluster to the new
+// server ID system. Server IDs are still set to be the same as server
+// addresses, but all configuration changes are propagated using the new
+// LogConfiguration Raft log entry type, which can carry full ID information.
+// This version supports the old AddPeer/RemovePeer APIs as well as the new
+// ID-based AddVoter/RemoveServer APIs which should be used when adding
+// version 3 servers to the cluster later. This version sheds all
+// interoperability with version 0 servers, but can interoperate with newer
+// Raft servers running with protocol version 1 since they can understand the
+// new LogConfiguration Raft log entry, and this version can still understand
+// their RemovePeerDeprecated Raft log entries. We need this protocol version
+// as an intermediate step between 1 and 3 so that servers will propagate the
+// ID information that will come from newly-added (or -rolled) servers using
+// protocol version 3, but since they are still using their address-based IDs
+// from the previous step they will still be able to track commitments and
+// their own voting status properly. If we skipped this step, servers would
+// be started with their new IDs, but they wouldn't see themselves in the old
+// address-based configuration, so none of the servers would think they had a
+// vote.
+// 3: Protocol adding full support for server IDs and new ID-based server APIs
+// (AddVoter, AddNonvoter, etc.), old AddPeer/RemovePeer APIs are no longer
+// supported. Version 2 servers should be swapped out by removing them from
+// the cluster one-by-one and re-adding them with updated configuration for
+// this protocol version, along with their server ID. The remove/add cycle
+// is required to populate their server ID. Note that removing must be done
+// by ID, which will be the old server's address.
+type ProtocolVersion int
+
+const (
+ ProtocolVersionMin ProtocolVersion = 0
+ ProtocolVersionMax = 3
+)
+
+// These are versions of snapshots that this server can _understand_. Currently,
+// it is always assumed that this server generates the latest version, though
+// this may be changed in the future to include a configurable version.
+//
+// Version History
+//
+// 0: Original Raft library before versioning was added. The peers portion of
+// these snapshots is encoded in the legacy format which requires decodePeers
+// to parse. This version of snapshots should only be produced by the
+// unversioned Raft library.
+// 1: New format which adds support for a full configuration structure and its
+// associated log index, with support for server IDs and non-voting server
+// modes. To ease upgrades, this also includes the legacy peers structure but
+// that will never be used by servers that understand version 1 snapshots.
+// Since the original Raft library didn't enforce any versioning, we must
+// include the legacy peers structure for this version, but we can deprecate
+// it in the next snapshot version.
+type SnapshotVersion int
+
+const (
+ SnapshotVersionMin SnapshotVersion = 0
+ SnapshotVersionMax = 1
+)
+
+// Config provides any necessary configuration for the Raft server.
+type Config struct {
+ // ProtocolVersion allows a Raft server to inter-operate with older
+ // Raft servers running an older version of the code. This is used to
+ // version the wire protocol as well as Raft-specific log entries that
+ // the server uses when _speaking_ to other servers. There is currently
+ // no auto-negotiation of versions so all servers must be manually
+ // configured with compatible versions. See ProtocolVersionMin and
+ // ProtocolVersionMax for the versions of the protocol that this server
+ // can _understand_.
+ ProtocolVersion ProtocolVersion
+
+ // HeartbeatTimeout specifies the time in follower state without
+ // a leader before we attempt an election.
+ HeartbeatTimeout time.Duration
+
+ // ElectionTimeout specifies the time in candidate state without
+ // a leader before we attempt an election.
+ ElectionTimeout time.Duration
+
+ // CommitTimeout controls the time without an Apply() operation
+ // before we heartbeat to ensure a timely commit. Due to random
+ // staggering, may be delayed as much as 2x this value.
+ CommitTimeout time.Duration
+
+ // MaxAppendEntries controls the maximum number of append entries
+ // to send at once. We want to strike a balance between efficiency
+ // and avoiding waste if the follower is going to reject because of
+ // an inconsistent log.
+ MaxAppendEntries int
+
+ // If we are a member of a cluster, and RemovePeer is invoked for the
+ // local node, then we forget all peers and transition into the follower state.
+ // If ShutdownOnRemove is is set, we additional shutdown Raft. Otherwise,
+ // we can become a leader of a cluster containing only this node.
+ ShutdownOnRemove bool
+
+ // TrailingLogs controls how many logs we leave after a snapshot. This is
+ // used so that we can quickly replay logs on a follower instead of being
+ // forced to send an entire snapshot.
+ TrailingLogs uint64
+
+ // SnapshotInterval controls how often we check if we should perform a snapshot.
+ // We randomly stagger between this value and 2x this value to avoid the entire
+ // cluster from performing a snapshot at once.
+ SnapshotInterval time.Duration
+
+ // SnapshotThreshold controls how many outstanding logs there must be before
+ // we perform a snapshot. This is to prevent excessive snapshots when we can
+ // just replay a small set of logs.
+ SnapshotThreshold uint64
+
+ // LeaderLeaseTimeout is used to control how long the "lease" lasts
+ // for being the leader without being able to contact a quorum
+ // of nodes. If we reach this interval without contact, we will
+ // step down as leader.
+ LeaderLeaseTimeout time.Duration
+
+ // StartAsLeader forces Raft to start in the leader state. This should
+ // never be used except for testing purposes, as it can cause a split-brain.
+ StartAsLeader bool
+
+ // The unique ID for this server across all time. When running with
+ // ProtocolVersion < 3, you must set this to be the same as the network
+ // address of your transport.
+ LocalID ServerID
+
+ // NotifyCh is used to provide a channel that will be notified of leadership
+ // changes. Raft will block writing to this channel, so it should either be
+ // buffered or aggressively consumed.
+ NotifyCh chan<- bool
+
+ // LogOutput is used as a sink for logs, unless Logger is specified.
+ // Defaults to os.Stderr.
+ LogOutput io.Writer
+
+ // LogLevel represents a log level. If a no matching string is specified,
+ // hclog.NoLevel is assumed.
+ LogLevel string
+
+ // Logger is a user-provided hc-log logger. If nil, a logger writing to
+ // LogOutput with LogLevel is used.
+ Logger hclog.Logger
+
+ // NoSnapshotRestoreOnStart controls if raft will restore a snapshot to the
+ // FSM on start. This is useful if your FSM recovers from other mechanisms
+ // than raft snapshotting. Snapshot metadata will still be used to initalize
+ // raft's configuration and index values. This is used in NewRaft and
+ // RestoreCluster.
+ NoSnapshotRestoreOnStart bool
+}
+
+// DefaultConfig returns a Config with usable defaults.
+func DefaultConfig() *Config {
+ return &Config{
+ ProtocolVersion: ProtocolVersionMax,
+ HeartbeatTimeout: 1000 * time.Millisecond,
+ ElectionTimeout: 1000 * time.Millisecond,
+ CommitTimeout: 50 * time.Millisecond,
+ MaxAppendEntries: 64,
+ ShutdownOnRemove: true,
+ TrailingLogs: 10240,
+ SnapshotInterval: 120 * time.Second,
+ SnapshotThreshold: 8192,
+ LeaderLeaseTimeout: 500 * time.Millisecond,
+ LogLevel: "DEBUG",
+ }
+}
+
+// ValidateConfig is used to validate a sane configuration
+func ValidateConfig(config *Config) error {
+ // We don't actually support running as 0 in the library any more, but
+ // we do understand it.
+ protocolMin := ProtocolVersionMin
+ if protocolMin == 0 {
+ protocolMin = 1
+ }
+ if config.ProtocolVersion < protocolMin ||
+ config.ProtocolVersion > ProtocolVersionMax {
+ return fmt.Errorf("Protocol version %d must be >= %d and <= %d",
+ config.ProtocolVersion, protocolMin, ProtocolVersionMax)
+ }
+ if len(config.LocalID) == 0 {
+ return fmt.Errorf("LocalID cannot be empty")
+ }
+ if config.HeartbeatTimeout < 5*time.Millisecond {
+ return fmt.Errorf("Heartbeat timeout is too low")
+ }
+ if config.ElectionTimeout < 5*time.Millisecond {
+ return fmt.Errorf("Election timeout is too low")
+ }
+ if config.CommitTimeout < time.Millisecond {
+ return fmt.Errorf("Commit timeout is too low")
+ }
+ if config.MaxAppendEntries <= 0 {
+ return fmt.Errorf("MaxAppendEntries must be positive")
+ }
+ if config.MaxAppendEntries > 1024 {
+ return fmt.Errorf("MaxAppendEntries is too large")
+ }
+ if config.SnapshotInterval < 5*time.Millisecond {
+ return fmt.Errorf("Snapshot interval is too low")
+ }
+ if config.LeaderLeaseTimeout < 5*time.Millisecond {
+ return fmt.Errorf("Leader lease timeout is too low")
+ }
+ if config.LeaderLeaseTimeout > config.HeartbeatTimeout {
+ return fmt.Errorf("Leader lease timeout cannot be larger than heartbeat timeout")
+ }
+ if config.ElectionTimeout < config.HeartbeatTimeout {
+ return fmt.Errorf("Election timeout must be equal or greater than Heartbeat Timeout")
+ }
+ return nil
+}
diff -Naur --color b/vendor/github.com/hashicorp/raft/configuration.go a/vendor/github.com/hashicorp/raft/configuration.go
--- b/vendor/github.com/hashicorp/raft/configuration.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/configuration.go 2022-11-15 23:06:31.565391195 +0100
@@ -0,0 +1,363 @@
+package raft
+
+import "fmt"
+
+// ServerSuffrage determines whether a Server in a Configuration gets a vote.
+type ServerSuffrage int
+
+// Note: Don't renumber these, since the numbers are written into the log.
+const (
+ // Voter is a server whose vote is counted in elections and whose match index
+ // is used in advancing the leader's commit index.
+ Voter ServerSuffrage = iota
+ // Nonvoter is a server that receives log entries but is not considered for
+ // elections or commitment purposes.
+ Nonvoter
+ // Staging is a server that acts like a nonvoter with one exception: once a
+ // staging server receives enough log entries to be sufficiently caught up to
+ // the leader's log, the leader will invoke a membership change to change
+ // the Staging server to a Voter.
+ Staging
+)
+
+func (s ServerSuffrage) String() string {
+ switch s {
+ case Voter:
+ return "Voter"
+ case Nonvoter:
+ return "Nonvoter"
+ case Staging:
+ return "Staging"
+ }
+ return "ServerSuffrage"
+}
+
+// ConfigurationStore provides an interface that can optionally be implemented by FSMs
+// to store configuration updates made in the replicated log. In general this is only
+// necessary for FSMs that mutate durable state directly instead of applying changes
+// in memory and snapshotting periodically. By storing configuration changes, the
+// persistent FSM state can behave as a complete snapshot, and be able to recover
+// without an external snapshot just for persisting the raft configuration.
+type ConfigurationStore interface {
+ // ConfigurationStore is a superset of the FSM functionality
+ FSM
+
+ // StoreConfiguration is invoked once a log entry containing a configuration
+ // change is committed. It takes the index at which the configuration was
+ // written and the configuration value.
+ StoreConfiguration(index uint64, configuration Configuration)
+}
+
+type nopConfigurationStore struct{}
+
+func (s nopConfigurationStore) StoreConfiguration(_ uint64, _ Configuration) {}
+
+// ServerID is a unique string identifying a server for all time.
+type ServerID string
+
+// ServerAddress is a network address for a server that a transport can contact.
+type ServerAddress string
+
+// Server tracks the information about a single server in a configuration.
+type Server struct {
+ // Suffrage determines whether the server gets a vote.
+ Suffrage ServerSuffrage
+ // ID is a unique string identifying this server for all time.
+ ID ServerID
+ // Address is its network address that a transport can contact.
+ Address ServerAddress
+}
+
+// Configuration tracks which servers are in the cluster, and whether they have
+// votes. This should include the local server, if it's a member of the cluster.
+// The servers are listed no particular order, but each should only appear once.
+// These entries are appended to the log during membership changes.
+type Configuration struct {
+ Servers []Server
+}
+
+// Clone makes a deep copy of a Configuration.
+func (c *Configuration) Clone() (copy Configuration) {
+ copy.Servers = append(copy.Servers, c.Servers...)
+ return
+}
+
+// ConfigurationChangeCommand is the different ways to change the cluster
+// configuration.
+type ConfigurationChangeCommand uint8
+
+const (
+ // AddStaging makes a server Staging unless its Voter.
+ AddStaging ConfigurationChangeCommand = iota
+ // AddNonvoter makes a server Nonvoter unless its Staging or Voter.
+ AddNonvoter
+ // DemoteVoter makes a server Nonvoter unless its absent.
+ DemoteVoter
+ // RemoveServer removes a server entirely from the cluster membership.
+ RemoveServer
+ // Promote is created automatically by a leader; it turns a Staging server
+ // into a Voter.
+ Promote
+)
+
+func (c ConfigurationChangeCommand) String() string {
+ switch c {
+ case AddStaging:
+ return "AddStaging"
+ case AddNonvoter:
+ return "AddNonvoter"
+ case DemoteVoter:
+ return "DemoteVoter"
+ case RemoveServer:
+ return "RemoveServer"
+ case Promote:
+ return "Promote"
+ }
+ return "ConfigurationChangeCommand"
+}
+
+// configurationChangeRequest describes a change that a leader would like to
+// make to its current configuration. It's used only within a single server
+// (never serialized into the log), as part of `configurationChangeFuture`.
+type configurationChangeRequest struct {
+ command ConfigurationChangeCommand
+ serverID ServerID
+ serverAddress ServerAddress // only present for AddStaging, AddNonvoter
+ // prevIndex, if nonzero, is the index of the only configuration upon which
+ // this change may be applied; if another configuration entry has been
+ // added in the meantime, this request will fail.
+ prevIndex uint64
+}
+
+// configurations is state tracked on every server about its Configurations.
+// Note that, per Diego's dissertation, there can be at most one uncommitted
+// configuration at a time (the next configuration may not be created until the
+// prior one has been committed).
+//
+// One downside to storing just two configurations is that if you try to take a
+// snapshot when your state machine hasn't yet applied the committedIndex, we
+// have no record of the configuration that would logically fit into that
+// snapshot. We disallow snapshots in that case now. An alternative approach,
+// which LogCabin uses, is to track every configuration change in the
+// log.
+type configurations struct {
+ // committed is the latest configuration in the log/snapshot that has been
+ // committed (the one with the largest index).
+ committed Configuration
+ // committedIndex is the log index where 'committed' was written.
+ committedIndex uint64
+ // latest is the latest configuration in the log/snapshot (may be committed
+ // or uncommitted)
+ latest Configuration
+ // latestIndex is the log index where 'latest' was written.
+ latestIndex uint64
+}
+
+// Clone makes a deep copy of a configurations object.
+func (c *configurations) Clone() (copy configurations) {
+ copy.committed = c.committed.Clone()
+ copy.committedIndex = c.committedIndex
+ copy.latest = c.latest.Clone()
+ copy.latestIndex = c.latestIndex
+ return
+}
+
+// hasVote returns true if the server identified by 'id' is a Voter in the
+// provided Configuration.
+func hasVote(configuration Configuration, id ServerID) bool {
+ for _, server := range configuration.Servers {
+ if server.ID == id {
+ return server.Suffrage == Voter
+ }
+ }
+ return false
+}
+
+// checkConfiguration tests a cluster membership configuration for common
+// errors.
+func checkConfiguration(configuration Configuration) error {
+ idSet := make(map[ServerID]bool)
+ addressSet := make(map[ServerAddress]bool)
+ var voters int
+ for _, server := range configuration.Servers {
+ if server.ID == "" {
+ return fmt.Errorf("Empty ID in configuration: %v", configuration)
+ }
+ if server.Address == "" {
+ return fmt.Errorf("Empty address in configuration: %v", server)
+ }
+ if idSet[server.ID] {
+ return fmt.Errorf("Found duplicate ID in configuration: %v", server.ID)
+ }
+ idSet[server.ID] = true
+ if addressSet[server.Address] {
+ return fmt.Errorf("Found duplicate address in configuration: %v", server.Address)
+ }
+ addressSet[server.Address] = true
+ if server.Suffrage == Voter {
+ voters++
+ }
+ }
+ if voters == 0 {
+ return fmt.Errorf("Need at least one voter in configuration: %v", configuration)
+ }
+ return nil
+}
+
+// nextConfiguration generates a new Configuration from the current one and a
+// configuration change request. It's split from appendConfigurationEntry so
+// that it can be unit tested easily.
+func nextConfiguration(current Configuration, currentIndex uint64, change configurationChangeRequest) (Configuration, error) {
+ if change.prevIndex > 0 && change.prevIndex != currentIndex {
+ return Configuration{}, fmt.Errorf("Configuration changed since %v (latest is %v)", change.prevIndex, currentIndex)
+ }
+
+ configuration := current.Clone()
+ switch change.command {
+ case AddStaging:
+ // TODO: barf on new address?
+ newServer := Server{
+ // TODO: This should add the server as Staging, to be automatically
+ // promoted to Voter later. However, the promotion to Voter is not yet
+ // implemented, and doing so is not trivial with the way the leader loop
+ // coordinates with the replication goroutines today. So, for now, the
+ // server will have a vote right away, and the Promote case below is
+ // unused.
+ Suffrage: Voter,
+ ID: change.serverID,
+ Address: change.serverAddress,
+ }
+ found := false
+ for i, server := range configuration.Servers {
+ if server.ID == change.serverID {
+ if server.Suffrage == Voter {
+ configuration.Servers[i].Address = change.serverAddress
+ } else {
+ configuration.Servers[i] = newServer
+ }
+ found = true
+ break
+ }
+ }
+ if !found {
+ configuration.Servers = append(configuration.Servers, newServer)
+ }
+ case AddNonvoter:
+ newServer := Server{
+ Suffrage: Nonvoter,
+ ID: change.serverID,
+ Address: change.serverAddress,
+ }
+ found := false
+ for i, server := range configuration.Servers {
+ if server.ID == change.serverID {
+ if server.Suffrage != Nonvoter {
+ configuration.Servers[i].Address = change.serverAddress
+ } else {
+ configuration.Servers[i] = newServer
+ }
+ found = true
+ break
+ }
+ }
+ if !found {
+ configuration.Servers = append(configuration.Servers, newServer)
+ }
+ case DemoteVoter:
+ for i, server := range configuration.Servers {
+ if server.ID == change.serverID {
+ configuration.Servers[i].Suffrage = Nonvoter
+ break
+ }
+ }
+ case RemoveServer:
+ for i, server := range configuration.Servers {
+ if server.ID == change.serverID {
+ configuration.Servers = append(configuration.Servers[:i], configuration.Servers[i+1:]...)
+ break
+ }
+ }
+ case Promote:
+ for i, server := range configuration.Servers {
+ if server.ID == change.serverID && server.Suffrage == Staging {
+ configuration.Servers[i].Suffrage = Voter
+ break
+ }
+ }
+ }
+
+ // Make sure we didn't do something bad like remove the last voter
+ if err := checkConfiguration(configuration); err != nil {
+ return Configuration{}, err
+ }
+
+ return configuration, nil
+}
+
+// encodePeers is used to serialize a Configuration into the old peers format.
+// This is here for backwards compatibility when operating with a mix of old
+// servers and should be removed once we deprecate support for protocol version 1.
+func encodePeers(configuration Configuration, trans Transport) []byte {
+ // Gather up all the voters, other suffrage types are not supported by
+ // this data format.
+ var encPeers [][]byte
+ for _, server := range configuration.Servers {
+ if server.Suffrage == Voter {
+ encPeers = append(encPeers, trans.EncodePeer(server.ID, server.Address))
+ }
+ }
+
+ // Encode the entire array.
+ buf, err := encodeMsgPack(encPeers)
+ if err != nil {
+ panic(fmt.Errorf("failed to encode peers: %v", err))
+ }
+
+ return buf.Bytes()
+}
+
+// decodePeers is used to deserialize an old list of peers into a Configuration.
+// This is here for backwards compatibility with old log entries and snapshots;
+// it should be removed eventually.
+func decodePeers(buf []byte, trans Transport) Configuration {
+ // Decode the buffer first.
+ var encPeers [][]byte
+ if err := decodeMsgPack(buf, &encPeers); err != nil {
+ panic(fmt.Errorf("failed to decode peers: %v", err))
+ }
+
+ // Deserialize each peer.
+ var servers []Server
+ for _, enc := range encPeers {
+ p := trans.DecodePeer(enc)
+ servers = append(servers, Server{
+ Suffrage: Voter,
+ ID: ServerID(p),
+ Address: ServerAddress(p),
+ })
+ }
+
+ return Configuration{
+ Servers: servers,
+ }
+}
+
+// encodeConfiguration serializes a Configuration using MsgPack, or panics on
+// errors.
+func encodeConfiguration(configuration Configuration) []byte {
+ buf, err := encodeMsgPack(configuration)
+ if err != nil {
+ panic(fmt.Errorf("failed to encode configuration: %v", err))
+ }
+ return buf.Bytes()
+}
+
+// decodeConfiguration deserializes a Configuration using MsgPack, or panics on
+// errors.
+func decodeConfiguration(buf []byte) Configuration {
+ var configuration Configuration
+ if err := decodeMsgPack(buf, &configuration); err != nil {
+ panic(fmt.Errorf("failed to decode configuration: %v", err))
+ }
+ return configuration
+}
diff -Naur --color b/vendor/github.com/hashicorp/raft/discard_snapshot.go a/vendor/github.com/hashicorp/raft/discard_snapshot.go
--- b/vendor/github.com/hashicorp/raft/discard_snapshot.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/discard_snapshot.go 2022-11-15 23:06:31.565391195 +0100
@@ -0,0 +1,49 @@
+package raft
+
+import (
+ "fmt"
+ "io"
+)
+
+// DiscardSnapshotStore is used to successfully snapshot while
+// always discarding the snapshot. This is useful for when the
+// log should be truncated but no snapshot should be retained.
+// This should never be used for production use, and is only
+// suitable for testing.
+type DiscardSnapshotStore struct{}
+
+type DiscardSnapshotSink struct{}
+
+// NewDiscardSnapshotStore is used to create a new DiscardSnapshotStore.
+func NewDiscardSnapshotStore() *DiscardSnapshotStore {
+ return &DiscardSnapshotStore{}
+}
+
+func (d *DiscardSnapshotStore) Create(version SnapshotVersion, index, term uint64,
+ configuration Configuration, configurationIndex uint64, trans Transport) (SnapshotSink, error) {
+ return &DiscardSnapshotSink{}, nil
+}
+
+func (d *DiscardSnapshotStore) List() ([]*SnapshotMeta, error) {
+ return nil, nil
+}
+
+func (d *DiscardSnapshotStore) Open(id string) (*SnapshotMeta, io.ReadCloser, error) {
+ return nil, nil, fmt.Errorf("open is not supported")
+}
+
+func (d *DiscardSnapshotSink) Write(b []byte) (int, error) {
+ return len(b), nil
+}
+
+func (d *DiscardSnapshotSink) Close() error {
+ return nil
+}
+
+func (d *DiscardSnapshotSink) ID() string {
+ return "discard"
+}
+
+func (d *DiscardSnapshotSink) Cancel() error {
+ return nil
+}
diff -Naur --color b/vendor/github.com/hashicorp/raft/file_snapshot.go a/vendor/github.com/hashicorp/raft/file_snapshot.go
--- b/vendor/github.com/hashicorp/raft/file_snapshot.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/file_snapshot.go 2022-11-15 23:06:31.565391195 +0100
@@ -0,0 +1,528 @@
+package raft
+
+import (
+ "bufio"
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "hash"
+ "hash/crc64"
+ "io"
+ "io/ioutil"
+ "log"
+ "os"
+ "path/filepath"
+ "runtime"
+ "sort"
+ "strings"
+ "time"
+)
+
+const (
+ testPath = "permTest"
+ snapPath = "snapshots"
+ metaFilePath = "meta.json"
+ stateFilePath = "state.bin"
+ tmpSuffix = ".tmp"
+)
+
+// FileSnapshotStore implements the SnapshotStore interface and allows
+// snapshots to be made on the local disk.
+type FileSnapshotStore struct {
+ path string
+ retain int
+ logger *log.Logger
+}
+
+type snapMetaSlice []*fileSnapshotMeta
+
+// FileSnapshotSink implements SnapshotSink with a file.
+type FileSnapshotSink struct {
+ store *FileSnapshotStore
+ logger *log.Logger
+ dir string
+ parentDir string
+ meta fileSnapshotMeta
+
+ stateFile *os.File
+ stateHash hash.Hash64
+ buffered *bufio.Writer
+
+ closed bool
+}
+
+// fileSnapshotMeta is stored on disk. We also put a CRC
+// on disk so that we can verify the snapshot.
+type fileSnapshotMeta struct {
+ SnapshotMeta
+ CRC []byte
+}
+
+// bufferedFile is returned when we open a snapshot. This way
+// reads are buffered and the file still gets closed.
+type bufferedFile struct {
+ bh *bufio.Reader
+ fh *os.File
+}
+
+func (b *bufferedFile) Read(p []byte) (n int, err error) {
+ return b.bh.Read(p)
+}
+
+func (b *bufferedFile) Close() error {
+ return b.fh.Close()
+}
+
+// NewFileSnapshotStoreWithLogger creates a new FileSnapshotStore based
+// on a base directory. The `retain` parameter controls how many
+// snapshots are retained. Must be at least 1.
+func NewFileSnapshotStoreWithLogger(base string, retain int, logger *log.Logger) (*FileSnapshotStore, error) {
+ if retain < 1 {
+ return nil, fmt.Errorf("must retain at least one snapshot")
+ }
+ if logger == nil {
+ logger = log.New(os.Stderr, "", log.LstdFlags)
+ }
+
+ // Ensure our path exists
+ path := filepath.Join(base, snapPath)
+ if err := os.MkdirAll(path, 0755); err != nil && !os.IsExist(err) {
+ return nil, fmt.Errorf("snapshot path not accessible: %v", err)
+ }
+
+ // Setup the store
+ store := &FileSnapshotStore{
+ path: path,
+ retain: retain,
+ logger: logger,
+ }
+
+ // Do a permissions test
+ if err := store.testPermissions(); err != nil {
+ return nil, fmt.Errorf("permissions test failed: %v", err)
+ }
+ return store, nil
+}
+
+// NewFileSnapshotStore creates a new FileSnapshotStore based
+// on a base directory. The `retain` parameter controls how many
+// snapshots are retained. Must be at least 1.
+func NewFileSnapshotStore(base string, retain int, logOutput io.Writer) (*FileSnapshotStore, error) {
+ if logOutput == nil {
+ logOutput = os.Stderr
+ }
+ return NewFileSnapshotStoreWithLogger(base, retain, log.New(logOutput, "", log.LstdFlags))
+}
+
+// testPermissions tries to touch a file in our path to see if it works.
+func (f *FileSnapshotStore) testPermissions() error {
+ path := filepath.Join(f.path, testPath)
+ fh, err := os.Create(path)
+ if err != nil {
+ return err
+ }
+
+ if err = fh.Close(); err != nil {
+ return err
+ }
+
+ if err = os.Remove(path); err != nil {
+ return err
+ }
+ return nil
+}
+
+// snapshotName generates a name for the snapshot.
+func snapshotName(term, index uint64) string {
+ now := time.Now()
+ msec := now.UnixNano() / int64(time.Millisecond)
+ return fmt.Sprintf("%d-%d-%d", term, index, msec)
+}
+
+// Create is used to start a new snapshot
+func (f *FileSnapshotStore) Create(version SnapshotVersion, index, term uint64,
+ configuration Configuration, configurationIndex uint64, trans Transport) (SnapshotSink, error) {
+ // We only support version 1 snapshots at this time.
+ if version != 1 {
+ return nil, fmt.Errorf("unsupported snapshot version %d", version)
+ }
+
+ // Create a new path
+ name := snapshotName(term, index)
+ path := filepath.Join(f.path, name+tmpSuffix)
+ f.logger.Printf("[INFO] snapshot: Creating new snapshot at %s", path)
+
+ // Make the directory
+ if err := os.MkdirAll(path, 0755); err != nil {
+ f.logger.Printf("[ERR] snapshot: Failed to make snapshot directory: %v", err)
+ return nil, err
+ }
+
+ // Create the sink
+ sink := &FileSnapshotSink{
+ store: f,
+ logger: f.logger,
+ dir: path,
+ parentDir: f.path,
+ meta: fileSnapshotMeta{
+ SnapshotMeta: SnapshotMeta{
+ Version: version,
+ ID: name,
+ Index: index,
+ Term: term,
+ Peers: encodePeers(configuration, trans),
+ Configuration: configuration,
+ ConfigurationIndex: configurationIndex,
+ },
+ CRC: nil,
+ },
+ }
+
+ // Write out the meta data
+ if err := sink.writeMeta(); err != nil {
+ f.logger.Printf("[ERR] snapshot: Failed to write metadata: %v", err)
+ return nil, err
+ }
+
+ // Open the state file
+ statePath := filepath.Join(path, stateFilePath)
+ fh, err := os.Create(statePath)
+ if err != nil {
+ f.logger.Printf("[ERR] snapshot: Failed to create state file: %v", err)
+ return nil, err
+ }
+ sink.stateFile = fh
+
+ // Create a CRC64 hash
+ sink.stateHash = crc64.New(crc64.MakeTable(crc64.ECMA))
+
+ // Wrap both the hash and file in a MultiWriter with buffering
+ multi := io.MultiWriter(sink.stateFile, sink.stateHash)
+ sink.buffered = bufio.NewWriter(multi)
+
+ // Done
+ return sink, nil
+}
+
+// List returns available snapshots in the store.
+func (f *FileSnapshotStore) List() ([]*SnapshotMeta, error) {
+ // Get the eligible snapshots
+ snapshots, err := f.getSnapshots()
+ if err != nil {
+ f.logger.Printf("[ERR] snapshot: Failed to get snapshots: %v", err)
+ return nil, err
+ }
+
+ var snapMeta []*SnapshotMeta
+ for _, meta := range snapshots {
+ snapMeta = append(snapMeta, &meta.SnapshotMeta)
+ if len(snapMeta) == f.retain {
+ break
+ }
+ }
+ return snapMeta, nil
+}
+
+// getSnapshots returns all the known snapshots.
+func (f *FileSnapshotStore) getSnapshots() ([]*fileSnapshotMeta, error) {
+ // Get the eligible snapshots
+ snapshots, err := ioutil.ReadDir(f.path)
+ if err != nil {
+ f.logger.Printf("[ERR] snapshot: Failed to scan snapshot dir: %v", err)
+ return nil, err
+ }
+
+ // Populate the metadata
+ var snapMeta []*fileSnapshotMeta
+ for _, snap := range snapshots {
+ // Ignore any files
+ if !snap.IsDir() {
+ continue
+ }
+
+ // Ignore any temporary snapshots
+ dirName := snap.Name()
+ if strings.HasSuffix(dirName, tmpSuffix) {
+ f.logger.Printf("[WARN] snapshot: Found temporary snapshot: %v", dirName)
+ continue
+ }
+
+ // Try to read the meta data
+ meta, err := f.readMeta(dirName)
+ if err != nil {
+ f.logger.Printf("[WARN] snapshot: Failed to read metadata for %v: %v", dirName, err)
+ continue
+ }
+
+ // Make sure we can understand this version.
+ if meta.Version < SnapshotVersionMin || meta.Version > SnapshotVersionMax {
+ f.logger.Printf("[WARN] snapshot: Snapshot version for %v not supported: %d", dirName, meta.Version)
+ continue
+ }
+
+ // Append, but only return up to the retain count
+ snapMeta = append(snapMeta, meta)
+ }
+
+ // Sort the snapshot, reverse so we get new -> old
+ sort.Sort(sort.Reverse(snapMetaSlice(snapMeta)))
+
+ return snapMeta, nil
+}
+
+// readMeta is used to read the meta data for a given named backup
+func (f *FileSnapshotStore) readMeta(name string) (*fileSnapshotMeta, error) {
+ // Open the meta file
+ metaPath := filepath.Join(f.path, name, metaFilePath)
+ fh, err := os.Open(metaPath)
+ if err != nil {
+ return nil, err
+ }
+ defer fh.Close()
+
+ // Buffer the file IO
+ buffered := bufio.NewReader(fh)
+
+ // Read in the JSON
+ meta := &fileSnapshotMeta{}
+ dec := json.NewDecoder(buffered)
+ if err := dec.Decode(meta); err != nil {
+ return nil, err
+ }
+ return meta, nil
+}
+
+// Open takes a snapshot ID and returns a ReadCloser for that snapshot.
+func (f *FileSnapshotStore) Open(id string) (*SnapshotMeta, io.ReadCloser, error) {
+ // Get the metadata
+ meta, err := f.readMeta(id)
+ if err != nil {
+ f.logger.Printf("[ERR] snapshot: Failed to get meta data to open snapshot: %v", err)
+ return nil, nil, err
+ }
+
+ // Open the state file
+ statePath := filepath.Join(f.path, id, stateFilePath)
+ fh, err := os.Open(statePath)
+ if err != nil {
+ f.logger.Printf("[ERR] snapshot: Failed to open state file: %v", err)
+ return nil, nil, err
+ }
+
+ // Create a CRC64 hash
+ stateHash := crc64.New(crc64.MakeTable(crc64.ECMA))
+
+ // Compute the hash
+ _, err = io.Copy(stateHash, fh)
+ if err != nil {
+ f.logger.Printf("[ERR] snapshot: Failed to read state file: %v", err)
+ fh.Close()
+ return nil, nil, err
+ }
+
+ // Verify the hash
+ computed := stateHash.Sum(nil)
+ if bytes.Compare(meta.CRC, computed) != 0 {
+ f.logger.Printf("[ERR] snapshot: CRC checksum failed (stored: %v computed: %v)",
+ meta.CRC, computed)
+ fh.Close()
+ return nil, nil, fmt.Errorf("CRC mismatch")
+ }
+
+ // Seek to the start
+ if _, err := fh.Seek(0, 0); err != nil {
+ f.logger.Printf("[ERR] snapshot: State file seek failed: %v", err)
+ fh.Close()
+ return nil, nil, err
+ }
+
+ // Return a buffered file
+ buffered := &bufferedFile{
+ bh: bufio.NewReader(fh),
+ fh: fh,
+ }
+
+ return &meta.SnapshotMeta, buffered, nil
+}
+
+// ReapSnapshots reaps any snapshots beyond the retain count.
+func (f *FileSnapshotStore) ReapSnapshots() error {
+ snapshots, err := f.getSnapshots()
+ if err != nil {
+ f.logger.Printf("[ERR] snapshot: Failed to get snapshots: %v", err)
+ return err
+ }
+
+ for i := f.retain; i < len(snapshots); i++ {
+ path := filepath.Join(f.path, snapshots[i].ID)
+ f.logger.Printf("[INFO] snapshot: reaping snapshot %v", path)
+ if err := os.RemoveAll(path); err != nil {
+ f.logger.Printf("[ERR] snapshot: Failed to reap snapshot %v: %v", path, err)
+ return err
+ }
+ }
+ return nil
+}
+
+// ID returns the ID of the snapshot, can be used with Open()
+// after the snapshot is finalized.
+func (s *FileSnapshotSink) ID() string {
+ return s.meta.ID
+}
+
+// Write is used to append to the state file. We write to the
+// buffered IO object to reduce the amount of context switches.
+func (s *FileSnapshotSink) Write(b []byte) (int, error) {
+ return s.buffered.Write(b)
+}
+
+// Close is used to indicate a successful end.
+func (s *FileSnapshotSink) Close() error {
+ // Make sure close is idempotent
+ if s.closed {
+ return nil
+ }
+ s.closed = true
+
+ // Close the open handles
+ if err := s.finalize(); err != nil {
+ s.logger.Printf("[ERR] snapshot: Failed to finalize snapshot: %v", err)
+ if delErr := os.RemoveAll(s.dir); delErr != nil {
+ s.logger.Printf("[ERR] snapshot: Failed to delete temporary snapshot directory at path %v: %v", s.dir, delErr)
+ return delErr
+ }
+ return err
+ }
+
+ // Write out the meta data
+ if err := s.writeMeta(); err != nil {
+ s.logger.Printf("[ERR] snapshot: Failed to write metadata: %v", err)
+ return err
+ }
+
+ // Move the directory into place
+ newPath := strings.TrimSuffix(s.dir, tmpSuffix)
+ if err := os.Rename(s.dir, newPath); err != nil {
+ s.logger.Printf("[ERR] snapshot: Failed to move snapshot into place: %v", err)
+ return err
+ }
+
+ if runtime.GOOS != "windows" { //skipping fsync for directory entry edits on Windows, only needed for *nix style file systems
+ parentFH, err := os.Open(s.parentDir)
+ defer parentFH.Close()
+ if err != nil {
+ s.logger.Printf("[ERR] snapshot: Failed to open snapshot parent directory %v, error: %v", s.parentDir, err)
+ return err
+ }
+
+ if err = parentFH.Sync(); err != nil {
+ s.logger.Printf("[ERR] snapshot: Failed syncing parent directory %v, error: %v", s.parentDir, err)
+ return err
+ }
+ }
+
+ // Reap any old snapshots
+ if err := s.store.ReapSnapshots(); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+// Cancel is used to indicate an unsuccessful end.
+func (s *FileSnapshotSink) Cancel() error {
+ // Make sure close is idempotent
+ if s.closed {
+ return nil
+ }
+ s.closed = true
+
+ // Close the open handles
+ if err := s.finalize(); err != nil {
+ s.logger.Printf("[ERR] snapshot: Failed to finalize snapshot: %v", err)
+ return err
+ }
+
+ // Attempt to remove all artifacts
+ return os.RemoveAll(s.dir)
+}
+
+// finalize is used to close all of our resources.
+func (s *FileSnapshotSink) finalize() error {
+ // Flush any remaining data
+ if err := s.buffered.Flush(); err != nil {
+ return err
+ }
+
+ // Sync to force fsync to disk
+ if err := s.stateFile.Sync(); err != nil {
+ return err
+ }
+
+ // Get the file size
+ stat, statErr := s.stateFile.Stat()
+
+ // Close the file
+ if err := s.stateFile.Close(); err != nil {
+ return err
+ }
+
+ // Set the file size, check after we close
+ if statErr != nil {
+ return statErr
+ }
+ s.meta.Size = stat.Size()
+
+ // Set the CRC
+ s.meta.CRC = s.stateHash.Sum(nil)
+ return nil
+}
+
+// writeMeta is used to write out the metadata we have.
+func (s *FileSnapshotSink) writeMeta() error {
+ // Open the meta file
+ metaPath := filepath.Join(s.dir, metaFilePath)
+ fh, err := os.Create(metaPath)
+ if err != nil {
+ return err
+ }
+ defer fh.Close()
+
+ // Buffer the file IO
+ buffered := bufio.NewWriter(fh)
+
+ // Write out as JSON
+ enc := json.NewEncoder(buffered)
+ if err := enc.Encode(&s.meta); err != nil {
+ return err
+ }
+
+ if err = buffered.Flush(); err != nil {
+ return err
+ }
+
+ if err = fh.Sync(); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+// Implement the sort interface for []*fileSnapshotMeta.
+func (s snapMetaSlice) Len() int {
+ return len(s)
+}
+
+func (s snapMetaSlice) Less(i, j int) bool {
+ if s[i].Term != s[j].Term {
+ return s[i].Term < s[j].Term
+ }
+ if s[i].Index != s[j].Index {
+ return s[i].Index < s[j].Index
+ }
+ return s[i].ID < s[j].ID
+}
+
+func (s snapMetaSlice) Swap(i, j int) {
+ s[i], s[j] = s[j], s[i]
+}
diff -Naur --color b/vendor/github.com/hashicorp/raft/fsm.go a/vendor/github.com/hashicorp/raft/fsm.go
--- b/vendor/github.com/hashicorp/raft/fsm.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/fsm.go 2022-11-15 23:06:31.565391195 +0100
@@ -0,0 +1,152 @@
+package raft
+
+import (
+ "fmt"
+ "io"
+ "time"
+
+ "github.com/armon/go-metrics"
+)
+
+// FSM provides an interface that can be implemented by
+// clients to make use of the replicated log.
+type FSM interface {
+ // Apply log is invoked once a log entry is committed.
+ // It returns a value which will be made available in the
+ // ApplyFuture returned by Raft.Apply method if that
+ // method was called on the same Raft node as the FSM.
+ Apply(*Log) interface{}
+
+ // Snapshot is used to support log compaction. This call should
+ // return an FSMSnapshot which can be used to save a point-in-time
+ // snapshot of the FSM. Apply and Snapshot are not called in multiple
+ // threads, but Apply will be called concurrently with Persist. This means
+ // the FSM should be implemented in a fashion that allows for concurrent
+ // updates while a snapshot is happening.
+ Snapshot() (FSMSnapshot, error)
+
+ // Restore is used to restore an FSM from a snapshot. It is not called
+ // concurrently with any other command. The FSM must discard all previous
+ // state.
+ Restore(io.ReadCloser) error
+}
+
+// FSMSnapshot is returned by an FSM in response to a Snapshot
+// It must be safe to invoke FSMSnapshot methods with concurrent
+// calls to Apply.
+type FSMSnapshot interface {
+ // Persist should dump all necessary state to the WriteCloser 'sink',
+ // and call sink.Close() when finished or call sink.Cancel() on error.
+ Persist(sink SnapshotSink) error
+
+ // Release is invoked when we are finished with the snapshot.
+ Release()
+}
+
+// runFSM is a long running goroutine responsible for applying logs
+// to the FSM. This is done async of other logs since we don't want
+// the FSM to block our internal operations.
+func (r *Raft) runFSM() {
+ var lastIndex, lastTerm uint64
+
+ commit := func(req *commitTuple) {
+ // Apply the log if a command or config change
+ var resp interface{}
+ // Make sure we send a response
+ defer func() {
+ // Invoke the future if given
+ if req.future != nil {
+ req.future.response = resp
+ req.future.respond(nil)
+ }
+ }()
+
+ switch req.log.Type {
+ case LogCommand:
+ start := time.Now()
+ resp = r.fsm.Apply(req.log)
+ metrics.MeasureSince([]string{"raft", "fsm", "apply"}, start)
+
+ case LogConfiguration:
+ configStore, ok := r.fsm.(ConfigurationStore)
+ if !ok {
+ // Return early to avoid incrementing the index and term for
+ // an unimplemented operation.
+ return
+ }
+
+ start := time.Now()
+ configStore.StoreConfiguration(req.log.Index, decodeConfiguration(req.log.Data))
+ metrics.MeasureSince([]string{"raft", "fsm", "store_config"}, start)
+ }
+
+ // Update the indexes
+ lastIndex = req.log.Index
+ lastTerm = req.log.Term
+ }
+
+ restore := func(req *restoreFuture) {
+ // Open the snapshot
+ meta, source, err := r.snapshots.Open(req.ID)
+ if err != nil {
+ req.respond(fmt.Errorf("failed to open snapshot %v: %v", req.ID, err))
+ return
+ }
+
+ // Attempt to restore
+ start := time.Now()
+ if err := r.fsm.Restore(source); err != nil {
+ req.respond(fmt.Errorf("failed to restore snapshot %v: %v", req.ID, err))
+ source.Close()
+ return
+ }
+ source.Close()
+ metrics.MeasureSince([]string{"raft", "fsm", "restore"}, start)
+
+ // Update the last index and term
+ lastIndex = meta.Index
+ lastTerm = meta.Term
+ req.respond(nil)
+ }
+
+ snapshot := func(req *reqSnapshotFuture) {
+ // Is there something to snapshot?
+ if lastIndex == 0 {
+ req.respond(ErrNothingNewToSnapshot)
+ return
+ }
+
+ // Start a snapshot
+ start := time.Now()
+ snap, err := r.fsm.Snapshot()
+ metrics.MeasureSince([]string{"raft", "fsm", "snapshot"}, start)
+
+ // Respond to the request
+ req.index = lastIndex
+ req.term = lastTerm
+ req.snapshot = snap
+ req.respond(err)
+ }
+
+ for {
+ select {
+ case ptr := <-r.fsmMutateCh:
+ switch req := ptr.(type) {
+ case *commitTuple:
+ commit(req)
+
+ case *restoreFuture:
+ restore(req)
+
+ default:
+ panic(fmt.Errorf("bad type passed to fsmMutateCh: %#v", ptr))
+ }
+
+ case req := <-r.fsmSnapshotCh:
+ snapshot(req)
+
+ case <-r.shutdownCh:
+ return
+ }
+ }
+}
diff -Naur --color b/vendor/github.com/hashicorp/raft/future.go a/vendor/github.com/hashicorp/raft/future.go
--- b/vendor/github.com/hashicorp/raft/future.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/future.go 2022-11-15 23:06:31.565391195 +0100
@@ -0,0 +1,304 @@
+package raft
+
+import (
+ "fmt"
+ "io"
+ "sync"
+ "time"
+)
+
+// Future is used to represent an action that may occur in the future.
+type Future interface {
+ // Error blocks until the future arrives and then
+ // returns the error status of the future.
+ // This may be called any number of times - all
+ // calls will return the same value.
+ // Note that it is not OK to call this method
+ // twice concurrently on the same Future instance.
+ Error() error
+}
+
+// IndexFuture is used for future actions that can result in a raft log entry
+// being created.
+type IndexFuture interface {
+ Future
+
+ // Index holds the index of the newly applied log entry.
+ // This must not be called until after the Error method has returned.
+ Index() uint64
+}
+
+// ApplyFuture is used for Apply and can return the FSM response.
+type ApplyFuture interface {
+ IndexFuture
+
+ // Response returns the FSM response as returned
+ // by the FSM.Apply method. This must not be called
+ // until after the Error method has returned.
+ Response() interface{}
+}
+
+// ConfigurationFuture is used for GetConfiguration and can return the
+// latest configuration in use by Raft.
+type ConfigurationFuture interface {
+ IndexFuture
+
+ // Configuration contains the latest configuration. This must
+ // not be called until after the Error method has returned.
+ Configuration() Configuration
+}
+
+// SnapshotFuture is used for waiting on a user-triggered snapshot to complete.
+type SnapshotFuture interface {
+ Future
+
+ // Open is a function you can call to access the underlying snapshot and
+ // its metadata. This must not be called until after the Error method
+ // has returned.
+ Open() (*SnapshotMeta, io.ReadCloser, error)
+}
+
+// LeadershipTransferFuture is used for waiting on a user-triggered leadership
+// transfer to complete.
+type LeadershipTransferFuture interface {
+ Future
+}
+
+// errorFuture is used to return a static error.
+type errorFuture struct {
+ err error
+}
+
+func (e errorFuture) Error() error {
+ return e.err
+}
+
+func (e errorFuture) Response() interface{} {
+ return nil
+}
+
+func (e errorFuture) Index() uint64 {
+ return 0
+}
+
+// deferError can be embedded to allow a future
+// to provide an error in the future.
+type deferError struct {
+ err error
+ errCh chan error
+ responded bool
+}
+
+func (d *deferError) init() {
+ d.errCh = make(chan error, 1)
+}
+
+func (d *deferError) Error() error {
+ if d.err != nil {
+ // Note that when we've received a nil error, this
+ // won't trigger, but the channel is closed after
+ // send so we'll still return nil below.
+ return d.err
+ }
+ if d.errCh == nil {
+ panic("waiting for response on nil channel")
+ }
+ d.err = <-d.errCh
+ return d.err
+}
+
+func (d *deferError) respond(err error) {
+ if d.errCh == nil {
+ return
+ }
+ if d.responded {
+ return
+ }
+ d.errCh <- err
+ close(d.errCh)
+ d.responded = true
+}
+
+// There are several types of requests that cause a configuration entry to
+// be appended to the log. These are encoded here for leaderLoop() to process.
+// This is internal to a single server.
+type configurationChangeFuture struct {
+ logFuture
+ req configurationChangeRequest
+}
+
+// bootstrapFuture is used to attempt a live bootstrap of the cluster. See the
+// Raft object's BootstrapCluster member function for more details.
+type bootstrapFuture struct {
+ deferError
+
+ // configuration is the proposed bootstrap configuration to apply.
+ configuration Configuration
+}
+
+// logFuture is used to apply a log entry and waits until
+// the log is considered committed.
+type logFuture struct {
+ deferError
+ log Log
+ response interface{}
+ dispatch time.Time
+}
+
+func (l *logFuture) Response() interface{} {
+ return l.response
+}
+
+func (l *logFuture) Index() uint64 {
+ return l.log.Index
+}
+
+type shutdownFuture struct {
+ raft *Raft
+}
+
+func (s *shutdownFuture) Error() error {
+ if s.raft == nil {
+ return nil
+ }
+ s.raft.waitShutdown()
+ if closeable, ok := s.raft.trans.(WithClose); ok {
+ closeable.Close()
+ }
+ return nil
+}
+
+// userSnapshotFuture is used for waiting on a user-triggered snapshot to
+// complete.
+type userSnapshotFuture struct {
+ deferError
+
+ // opener is a function used to open the snapshot. This is filled in
+ // once the future returns with no error.
+ opener func() (*SnapshotMeta, io.ReadCloser, error)
+}
+
+// Open is a function you can call to access the underlying snapshot and its
+// metadata.
+func (u *userSnapshotFuture) Open() (*SnapshotMeta, io.ReadCloser, error) {
+ if u.opener == nil {
+ return nil, nil, fmt.Errorf("no snapshot available")
+ } else {
+ // Invalidate the opener so it can't get called multiple times,
+ // which isn't generally safe.
+ defer func() {
+ u.opener = nil
+ }()
+ return u.opener()
+ }
+}
+
+// userRestoreFuture is used for waiting on a user-triggered restore of an
+// external snapshot to complete.
+type userRestoreFuture struct {
+ deferError
+
+ // meta is the metadata that belongs with the snapshot.
+ meta *SnapshotMeta
+
+ // reader is the interface to read the snapshot contents from.
+ reader io.Reader
+}
+
+// reqSnapshotFuture is used for requesting a snapshot start.
+// It is only used internally.
+type reqSnapshotFuture struct {
+ deferError
+
+ // snapshot details provided by the FSM runner before responding
+ index uint64
+ term uint64
+ snapshot FSMSnapshot
+}
+
+// restoreFuture is used for requesting an FSM to perform a
+// snapshot restore. Used internally only.
+type restoreFuture struct {
+ deferError
+ ID string
+}
+
+// verifyFuture is used to verify the current node is still
+// the leader. This is to prevent a stale read.
+type verifyFuture struct {
+ deferError
+ notifyCh chan *verifyFuture
+ quorumSize int
+ votes int
+ voteLock sync.Mutex
+}
+
+// leadershipTransferFuture is used to track the progress of a leadership
+// transfer internally.
+type leadershipTransferFuture struct {
+ deferError
+
+ ID *ServerID
+ Address *ServerAddress
+}
+
+// configurationsFuture is used to retrieve the current configurations. This is
+// used to allow safe access to this information outside of the main thread.
+type configurationsFuture struct {
+ deferError
+ configurations configurations
+}
+
+// Configuration returns the latest configuration in use by Raft.
+func (c *configurationsFuture) Configuration() Configuration {
+ return c.configurations.latest
+}
+
+// Index returns the index of the latest configuration in use by Raft.
+func (c *configurationsFuture) Index() uint64 {
+ return c.configurations.latestIndex
+}
+
+// vote is used to respond to a verifyFuture.
+// This may block when responding on the notifyCh.
+func (v *verifyFuture) vote(leader bool) {
+ v.voteLock.Lock()
+ defer v.voteLock.Unlock()
+
+ // Guard against having notified already
+ if v.notifyCh == nil {
+ return
+ }
+
+ if leader {
+ v.votes++
+ if v.votes >= v.quorumSize {
+ v.notifyCh <- v
+ v.notifyCh = nil
+ }
+ } else {
+ v.notifyCh <- v
+ v.notifyCh = nil
+ }
+}
+
+// appendFuture is used for waiting on a pipelined append
+// entries RPC.
+type appendFuture struct {
+ deferError
+ start time.Time
+ args *AppendEntriesRequest
+ resp *AppendEntriesResponse
+}
+
+func (a *appendFuture) Start() time.Time {
+ return a.start
+}
+
+func (a *appendFuture) Request() *AppendEntriesRequest {
+ return a.args
+}
+
+func (a *appendFuture) Response() *AppendEntriesResponse {
+ return a.resp
+}
diff -Naur --color b/vendor/github.com/hashicorp/raft/.gitignore a/vendor/github.com/hashicorp/raft/.gitignore
--- b/vendor/github.com/hashicorp/raft/.gitignore 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/.gitignore 2022-11-15 23:06:31.562057797 +0100
@@ -0,0 +1,23 @@
+# Compiled Object files, Static and Dynamic libs (Shared Objects)
+*.o
+*.a
+*.so
+
+# Folders
+_obj
+_test
+
+# Architecture specific extensions/prefixes
+*.[568vq]
+[568vq].out
+
+*.cgo1.go
+*.cgo2.c
+_cgo_defun.c
+_cgo_gotypes.go
+_cgo_export.*
+
+_testmain.go
+
+*.exe
+*.test
diff -Naur --color b/vendor/github.com/hashicorp/raft/inmem_snapshot.go a/vendor/github.com/hashicorp/raft/inmem_snapshot.go
--- b/vendor/github.com/hashicorp/raft/inmem_snapshot.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/inmem_snapshot.go 2022-11-15 23:06:31.565391195 +0100
@@ -0,0 +1,109 @@
+package raft
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "sync"
+)
+
+// InmemSnapshotStore implements the SnapshotStore interface and
+// retains only the most recent snapshot
+type InmemSnapshotStore struct {
+ latest *InmemSnapshotSink
+ hasSnapshot bool
+ sync.RWMutex
+}
+
+// InmemSnapshotSink implements SnapshotSink in memory
+type InmemSnapshotSink struct {
+ meta SnapshotMeta
+ contents *bytes.Buffer
+}
+
+// NewInmemSnapshotStore creates a blank new InmemSnapshotStore
+func NewInmemSnapshotStore() *InmemSnapshotStore {
+ return &InmemSnapshotStore{
+ latest: &InmemSnapshotSink{
+ contents: &bytes.Buffer{},
+ },
+ }
+}
+
+// Create replaces the stored snapshot with a new one using the given args
+func (m *InmemSnapshotStore) Create(version SnapshotVersion, index, term uint64,
+ configuration Configuration, configurationIndex uint64, trans Transport) (SnapshotSink, error) {
+ // We only support version 1 snapshots at this time.
+ if version != 1 {
+ return nil, fmt.Errorf("unsupported snapshot version %d", version)
+ }
+
+ name := snapshotName(term, index)
+
+ m.Lock()
+ defer m.Unlock()
+
+ sink := &InmemSnapshotSink{
+ meta: SnapshotMeta{
+ Version: version,
+ ID: name,
+ Index: index,
+ Term: term,
+ Peers: encodePeers(configuration, trans),
+ Configuration: configuration,
+ ConfigurationIndex: configurationIndex,
+ },
+ contents: &bytes.Buffer{},
+ }
+ m.hasSnapshot = true
+ m.latest = sink
+
+ return sink, nil
+}
+
+// List returns the latest snapshot taken
+func (m *InmemSnapshotStore) List() ([]*SnapshotMeta, error) {
+ m.RLock()
+ defer m.RUnlock()
+
+ if !m.hasSnapshot {
+ return []*SnapshotMeta{}, nil
+ }
+ return []*SnapshotMeta{&m.latest.meta}, nil
+}
+
+// Open wraps an io.ReadCloser around the snapshot contents
+func (m *InmemSnapshotStore) Open(id string) (*SnapshotMeta, io.ReadCloser, error) {
+ m.RLock()
+ defer m.RUnlock()
+
+ if m.latest.meta.ID != id {
+ return nil, nil, fmt.Errorf("[ERR] snapshot: failed to open snapshot id: %s", id)
+ }
+
+ // Make a copy of the contents, since a bytes.Buffer can only be read
+ // once.
+ contents := bytes.NewBuffer(m.latest.contents.Bytes())
+ return &m.latest.meta, ioutil.NopCloser(contents), nil
+}
+
+// Write appends the given bytes to the snapshot contents
+func (s *InmemSnapshotSink) Write(p []byte) (n int, err error) {
+ written, err := io.Copy(s.contents, bytes.NewReader(p))
+ s.meta.Size += written
+ return int(written), err
+}
+
+// Close updates the Size and is otherwise a no-op
+func (s *InmemSnapshotSink) Close() error {
+ return nil
+}
+
+func (s *InmemSnapshotSink) ID() string {
+ return s.meta.ID
+}
+
+func (s *InmemSnapshotSink) Cancel() error {
+ return nil
+}
diff -Naur --color b/vendor/github.com/hashicorp/raft/inmem_store.go a/vendor/github.com/hashicorp/raft/inmem_store.go
--- b/vendor/github.com/hashicorp/raft/inmem_store.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/inmem_store.go 2022-11-15 23:06:31.565391195 +0100
@@ -0,0 +1,130 @@
+package raft
+
+import (
+ "errors"
+ "sync"
+)
+
+// InmemStore implements the LogStore and StableStore interface.
+// It should NOT EVER be used for production. It is used only for
+// unit tests. Use the MDBStore implementation instead.
+type InmemStore struct {
+ l sync.RWMutex
+ lowIndex uint64
+ highIndex uint64
+ logs map[uint64]*Log
+ kv map[string][]byte
+ kvInt map[string]uint64
+}
+
+// NewInmemStore returns a new in-memory backend. Do not ever
+// use for production. Only for testing.
+func NewInmemStore() *InmemStore {
+ i := &InmemStore{
+ logs: make(map[uint64]*Log),
+ kv: make(map[string][]byte),
+ kvInt: make(map[string]uint64),
+ }
+ return i
+}
+
+// FirstIndex implements the LogStore interface.
+func (i *InmemStore) FirstIndex() (uint64, error) {
+ i.l.RLock()
+ defer i.l.RUnlock()
+ return i.lowIndex, nil
+}
+
+// LastIndex implements the LogStore interface.
+func (i *InmemStore) LastIndex() (uint64, error) {
+ i.l.RLock()
+ defer i.l.RUnlock()
+ return i.highIndex, nil
+}
+
+// GetLog implements the LogStore interface.
+func (i *InmemStore) GetLog(index uint64, log *Log) error {
+ i.l.RLock()
+ defer i.l.RUnlock()
+ l, ok := i.logs[index]
+ if !ok {
+ return ErrLogNotFound
+ }
+ *log = *l
+ return nil
+}
+
+// StoreLog implements the LogStore interface.
+func (i *InmemStore) StoreLog(log *Log) error {
+ return i.StoreLogs([]*Log{log})
+}
+
+// StoreLogs implements the LogStore interface.
+func (i *InmemStore) StoreLogs(logs []*Log) error {
+ i.l.Lock()
+ defer i.l.Unlock()
+ for _, l := range logs {
+ i.logs[l.Index] = l
+ if i.lowIndex == 0 {
+ i.lowIndex = l.Index
+ }
+ if l.Index > i.highIndex {
+ i.highIndex = l.Index
+ }
+ }
+ return nil
+}
+
+// DeleteRange implements the LogStore interface.
+func (i *InmemStore) DeleteRange(min, max uint64) error {
+ i.l.Lock()
+ defer i.l.Unlock()
+ for j := min; j <= max; j++ {
+ delete(i.logs, j)
+ }
+ if min <= i.lowIndex {
+ i.lowIndex = max + 1
+ }
+ if max >= i.highIndex {
+ i.highIndex = min - 1
+ }
+ if i.lowIndex > i.highIndex {
+ i.lowIndex = 0
+ i.highIndex = 0
+ }
+ return nil
+}
+
+// Set implements the StableStore interface.
+func (i *InmemStore) Set(key []byte, val []byte) error {
+ i.l.Lock()
+ defer i.l.Unlock()
+ i.kv[string(key)] = val
+ return nil
+}
+
+// Get implements the StableStore interface.
+func (i *InmemStore) Get(key []byte) ([]byte, error) {
+ i.l.RLock()
+ defer i.l.RUnlock()
+ val := i.kv[string(key)]
+ if val == nil {
+ return nil, errors.New("not found")
+ }
+ return val, nil
+}
+
+// SetUint64 implements the StableStore interface.
+func (i *InmemStore) SetUint64(key []byte, val uint64) error {
+ i.l.Lock()
+ defer i.l.Unlock()
+ i.kvInt[string(key)] = val
+ return nil
+}
+
+// GetUint64 implements the StableStore interface.
+func (i *InmemStore) GetUint64(key []byte) (uint64, error) {
+ i.l.RLock()
+ defer i.l.RUnlock()
+ return i.kvInt[string(key)], nil
+}
diff -Naur --color b/vendor/github.com/hashicorp/raft/inmem_transport.go a/vendor/github.com/hashicorp/raft/inmem_transport.go
--- b/vendor/github.com/hashicorp/raft/inmem_transport.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/inmem_transport.go 2022-11-15 23:06:31.565391195 +0100
@@ -0,0 +1,348 @@
+package raft
+
+import (
+ "fmt"
+ "io"
+ "sync"
+ "time"
+)
+
+// NewInmemAddr returns a new in-memory addr with
+// a randomly generate UUID as the ID.
+func NewInmemAddr() ServerAddress {
+ return ServerAddress(generateUUID())
+}
+
+// inmemPipeline is used to pipeline requests for the in-mem transport.
+type inmemPipeline struct {
+ trans *InmemTransport
+ peer *InmemTransport
+ peerAddr ServerAddress
+
+ doneCh chan AppendFuture
+ inprogressCh chan *inmemPipelineInflight
+
+ shutdown bool
+ shutdownCh chan struct{}
+ shutdownLock sync.Mutex
+}
+
+type inmemPipelineInflight struct {
+ future *appendFuture
+ respCh <-chan RPCResponse
+}
+
+// InmemTransport Implements the Transport interface, to allow Raft to be
+// tested in-memory without going over a network.
+type InmemTransport struct {
+ sync.RWMutex
+ consumerCh chan RPC
+ localAddr ServerAddress
+ peers map[ServerAddress]*InmemTransport
+ pipelines []*inmemPipeline
+ timeout time.Duration
+}
+
+// NewInmemTransportWithTimeout is used to initialize a new transport and
+// generates a random local address if none is specified. The given timeout
+// will be used to decide how long to wait for a connected peer to process the
+// RPCs that we're sending it. See also Connect() and Consumer().
+func NewInmemTransportWithTimeout(addr ServerAddress, timeout time.Duration) (ServerAddress, *InmemTransport) {
+ if string(addr) == "" {
+ addr = NewInmemAddr()
+ }
+ trans := &InmemTransport{
+ consumerCh: make(chan RPC, 16),
+ localAddr: addr,
+ peers: make(map[ServerAddress]*InmemTransport),
+ timeout: timeout,
+ }
+ return addr, trans
+}
+
+// NewInmemTransport is used to initialize a new transport
+// and generates a random local address if none is specified
+func NewInmemTransport(addr ServerAddress) (ServerAddress, *InmemTransport) {
+ return NewInmemTransportWithTimeout(addr, 50*time.Millisecond)
+}
+
+// SetHeartbeatHandler is used to set optional fast-path for
+// heartbeats, not supported for this transport.
+func (i *InmemTransport) SetHeartbeatHandler(cb func(RPC)) {
+}
+
+// Consumer implements the Transport interface.
+func (i *InmemTransport) Consumer() <-chan RPC {
+ return i.consumerCh
+}
+
+// LocalAddr implements the Transport interface.
+func (i *InmemTransport) LocalAddr() ServerAddress {
+ return i.localAddr
+}
+
+// AppendEntriesPipeline returns an interface that can be used to pipeline
+// AppendEntries requests.
+func (i *InmemTransport) AppendEntriesPipeline(id ServerID, target ServerAddress) (AppendPipeline, error) {
+ i.Lock()
+ defer i.Unlock()
+
+ peer, ok := i.peers[target]
+ if !ok {
+ return nil, fmt.Errorf("failed to connect to peer: %v", target)
+ }
+ pipeline := newInmemPipeline(i, peer, target)
+ i.pipelines = append(i.pipelines, pipeline)
+ return pipeline, nil
+}
+
+// AppendEntries implements the Transport interface.
+func (i *InmemTransport) AppendEntries(id ServerID, target ServerAddress, args *AppendEntriesRequest, resp *AppendEntriesResponse) error {
+ rpcResp, err := i.makeRPC(target, args, nil, i.timeout)
+ if err != nil {
+ return err
+ }
+
+ // Copy the result back
+ out := rpcResp.Response.(*AppendEntriesResponse)
+ *resp = *out
+ return nil
+}
+
+// RequestVote implements the Transport interface.
+func (i *InmemTransport) RequestVote(id ServerID, target ServerAddress, args *RequestVoteRequest, resp *RequestVoteResponse) error {
+ rpcResp, err := i.makeRPC(target, args, nil, i.timeout)
+ if err != nil {
+ return err
+ }
+
+ // Copy the result back
+ out := rpcResp.Response.(*RequestVoteResponse)
+ *resp = *out
+ return nil
+}
+
+// InstallSnapshot implements the Transport interface.
+func (i *InmemTransport) InstallSnapshot(id ServerID, target ServerAddress, args *InstallSnapshotRequest, resp *InstallSnapshotResponse, data io.Reader) error {
+ rpcResp, err := i.makeRPC(target, args, data, 10*i.timeout)
+ if err != nil {
+ return err
+ }
+
+ // Copy the result back
+ out := rpcResp.Response.(*InstallSnapshotResponse)
+ *resp = *out
+ return nil
+}
+
+// TimeoutNow implements the Transport interface.
+func (i *InmemTransport) TimeoutNow(id ServerID, target ServerAddress, args *TimeoutNowRequest, resp *TimeoutNowResponse) error {
+ rpcResp, err := i.makeRPC(target, args, nil, 10*i.timeout)
+ if err != nil {
+ return err
+ }
+
+ // Copy the result back
+ out := rpcResp.Response.(*TimeoutNowResponse)
+ *resp = *out
+ return nil
+}
+
+func (i *InmemTransport) makeRPC(target ServerAddress, args interface{}, r io.Reader, timeout time.Duration) (rpcResp RPCResponse, err error) {
+ i.RLock()
+ peer, ok := i.peers[target]
+ i.RUnlock()
+
+ if !ok {
+ err = fmt.Errorf("failed to connect to peer: %v", target)
+ return
+ }
+
+ // Send the RPC over
+ respCh := make(chan RPCResponse)
+ req := RPC{
+ Command: args,
+ Reader: r,
+ RespChan: respCh,
+ }
+ select {
+ case peer.consumerCh <- req:
+ case <-time.After(timeout):
+ err = fmt.Errorf("send timed out")
+ return
+ }
+
+ // Wait for a response
+ select {
+ case rpcResp = <-respCh:
+ if rpcResp.Error != nil {
+ err = rpcResp.Error
+ }
+ case <-time.After(timeout):
+ err = fmt.Errorf("command timed out")
+ }
+ return
+}
+
+// EncodePeer implements the Transport interface.
+func (i *InmemTransport) EncodePeer(id ServerID, p ServerAddress) []byte {
+ return []byte(p)
+}
+
+// DecodePeer implements the Transport interface.
+func (i *InmemTransport) DecodePeer(buf []byte) ServerAddress {
+ return ServerAddress(buf)
+}
+
+// Connect is used to connect this transport to another transport for
+// a given peer name. This allows for local routing.
+func (i *InmemTransport) Connect(peer ServerAddress, t Transport) {
+ trans := t.(*InmemTransport)
+ i.Lock()
+ defer i.Unlock()
+ i.peers[peer] = trans
+}
+
+// Disconnect is used to remove the ability to route to a given peer.
+func (i *InmemTransport) Disconnect(peer ServerAddress) {
+ i.Lock()
+ defer i.Unlock()
+ delete(i.peers, peer)
+
+ // Disconnect any pipelines
+ n := len(i.pipelines)
+ for idx := 0; idx < n; idx++ {
+ if i.pipelines[idx].peerAddr == peer {
+ i.pipelines[idx].Close()
+ i.pipelines[idx], i.pipelines[n-1] = i.pipelines[n-1], nil
+ idx--
+ n--
+ }
+ }
+ i.pipelines = i.pipelines[:n]
+}
+
+// DisconnectAll is used to remove all routes to peers.
+func (i *InmemTransport) DisconnectAll() {
+ i.Lock()
+ defer i.Unlock()
+ i.peers = make(map[ServerAddress]*InmemTransport)
+
+ // Handle pipelines
+ for _, pipeline := range i.pipelines {
+ pipeline.Close()
+ }
+ i.pipelines = nil
+}
+
+// Close is used to permanently disable the transport
+func (i *InmemTransport) Close() error {
+ i.DisconnectAll()
+ return nil
+}
+
+func newInmemPipeline(trans *InmemTransport, peer *InmemTransport, addr ServerAddress) *inmemPipeline {
+ i := &inmemPipeline{
+ trans: trans,
+ peer: peer,
+ peerAddr: addr,
+ doneCh: make(chan AppendFuture, 16),
+ inprogressCh: make(chan *inmemPipelineInflight, 16),
+ shutdownCh: make(chan struct{}),
+ }
+ go i.decodeResponses()
+ return i
+}
+
+func (i *inmemPipeline) decodeResponses() {
+ timeout := i.trans.timeout
+ for {
+ select {
+ case inp := <-i.inprogressCh:
+ var timeoutCh <-chan time.Time
+ if timeout > 0 {
+ timeoutCh = time.After(timeout)
+ }
+
+ select {
+ case rpcResp := <-inp.respCh:
+ // Copy the result back
+ *inp.future.resp = *rpcResp.Response.(*AppendEntriesResponse)
+ inp.future.respond(rpcResp.Error)
+
+ select {
+ case i.doneCh <- inp.future:
+ case <-i.shutdownCh:
+ return
+ }
+
+ case <-timeoutCh:
+ inp.future.respond(fmt.Errorf("command timed out"))
+ select {
+ case i.doneCh <- inp.future:
+ case <-i.shutdownCh:
+ return
+ }
+
+ case <-i.shutdownCh:
+ return
+ }
+ case <-i.shutdownCh:
+ return
+ }
+ }
+}
+
+func (i *inmemPipeline) AppendEntries(args *AppendEntriesRequest, resp *AppendEntriesResponse) (AppendFuture, error) {
+ // Create a new future
+ future := &appendFuture{
+ start: time.Now(),
+ args: args,
+ resp: resp,
+ }
+ future.init()
+
+ // Handle a timeout
+ var timeout <-chan time.Time
+ if i.trans.timeout > 0 {
+ timeout = time.After(i.trans.timeout)
+ }
+
+ // Send the RPC over
+ respCh := make(chan RPCResponse, 1)
+ rpc := RPC{
+ Command: args,
+ RespChan: respCh,
+ }
+ select {
+ case i.peer.consumerCh <- rpc:
+ case <-timeout:
+ return nil, fmt.Errorf("command enqueue timeout")
+ case <-i.shutdownCh:
+ return nil, ErrPipelineShutdown
+ }
+
+ // Send to be decoded
+ select {
+ case i.inprogressCh <- &inmemPipelineInflight{future, respCh}:
+ return future, nil
+ case <-i.shutdownCh:
+ return nil, ErrPipelineShutdown
+ }
+}
+
+func (i *inmemPipeline) Consumer() <-chan AppendFuture {
+ return i.doneCh
+}
+
+func (i *inmemPipeline) Close() error {
+ i.shutdownLock.Lock()
+ defer i.shutdownLock.Unlock()
+ if i.shutdown {
+ return nil
+ }
+
+ i.shutdown = true
+ close(i.shutdownCh)
+ return nil
+}
diff -Naur --color b/vendor/github.com/hashicorp/raft/LICENSE a/vendor/github.com/hashicorp/raft/LICENSE
--- b/vendor/github.com/hashicorp/raft/LICENSE 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/LICENSE 2022-11-15 23:06:31.562057797 +0100
@@ -0,0 +1,354 @@
+Mozilla Public License, version 2.0
+
+1. Definitions
+
+1.1. “Contributor”
+
+ means each individual or legal entity that creates, contributes to the
+ creation of, or owns Covered Software.
+
+1.2. “Contributor Version”
+
+ means the combination of the Contributions of others (if any) used by a
+ Contributor and that particular Contributor’s Contribution.
+
+1.3. “Contribution”
+
+ means Covered Software of a particular Contributor.
+
+1.4. “Covered Software”
+
+ means Source Code Form to which the initial Contributor has attached the
+ notice in Exhibit A, the Executable Form of such Source Code Form, and
+ Modifications of such Source Code Form, in each case including portions
+ thereof.
+
+1.5. “Incompatible With Secondary Licenses”
+ means
+
+ a. that the initial Contributor has attached the notice described in
+ Exhibit B to the Covered Software; or
+
+ b. that the Covered Software was made available under the terms of version
+ 1.1 or earlier of the License, but not also under the terms of a
+ Secondary License.
+
+1.6. “Executable Form”
+
+ means any form of the work other than Source Code Form.
+
+1.7. “Larger Work”
+
+ means a work that combines Covered Software with other material, in a separate
+ file or files, that is not Covered Software.
+
+1.8. “License”
+
+ means this document.
+
+1.9. “Licensable”
+
+ means having the right to grant, to the maximum extent possible, whether at the
+ time of the initial grant or subsequently, any and all of the rights conveyed by
+ this License.
+
+1.10. “Modifications”
+
+ means any of the following:
+
+ a. any file in Source Code Form that results from an addition to, deletion
+ from, or modification of the contents of Covered Software; or
+
+ b. any new file in Source Code Form that contains any Covered Software.
+
+1.11. “Patent Claims” of a Contributor
+
+ means any patent claim(s), including without limitation, method, process,
+ and apparatus claims, in any patent Licensable by such Contributor that
+ would be infringed, but for the grant of the License, by the making,
+ using, selling, offering for sale, having made, import, or transfer of
+ either its Contributions or its Contributor Version.
+
+1.12. “Secondary License”
+
+ means either the GNU General Public License, Version 2.0, the GNU Lesser
+ General Public License, Version 2.1, the GNU Affero General Public
+ License, Version 3.0, or any later versions of those licenses.
+
+1.13. “Source Code Form”
+
+ means the form of the work preferred for making modifications.
+
+1.14. “You” (or “Your”)
+
+ means an individual or a legal entity exercising rights under this
+ License. For legal entities, “You” includes any entity that controls, is
+ controlled by, or is under common control with You. For purposes of this
+ definition, “control” means (a) the power, direct or indirect, to cause
+ the direction or management of such entity, whether by contract or
+ otherwise, or (b) ownership of more than fifty percent (50%) of the
+ outstanding shares or beneficial ownership of such entity.
+
+
+2. License Grants and Conditions
+
+2.1. Grants
+
+ Each Contributor hereby grants You a world-wide, royalty-free,
+ non-exclusive license:
+
+ a. under intellectual property rights (other than patent or trademark)
+ Licensable by such Contributor to use, reproduce, make available,
+ modify, display, perform, distribute, and otherwise exploit its
+ Contributions, either on an unmodified basis, with Modifications, or as
+ part of a Larger Work; and
+
+ b. under Patent Claims of such Contributor to make, use, sell, offer for
+ sale, have made, import, and otherwise transfer either its Contributions
+ or its Contributor Version.
+
+2.2. Effective Date
+
+ The licenses granted in Section 2.1 with respect to any Contribution become
+ effective for each Contribution on the date the Contributor first distributes
+ such Contribution.
+
+2.3. Limitations on Grant Scope
+
+ The licenses granted in this Section 2 are the only rights granted under this
+ License. No additional rights or licenses will be implied from the distribution
+ or licensing of Covered Software under this License. Notwithstanding Section
+ 2.1(b) above, no patent license is granted by a Contributor:
+
+ a. for any code that a Contributor has removed from Covered Software; or
+
+ b. for infringements caused by: (i) Your and any other third party’s
+ modifications of Covered Software, or (ii) the combination of its
+ Contributions with other software (except as part of its Contributor
+ Version); or
+
+ c. under Patent Claims infringed by Covered Software in the absence of its
+ Contributions.
+
+ This License does not grant any rights in the trademarks, service marks, or
+ logos of any Contributor (except as may be necessary to comply with the
+ notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+ No Contributor makes additional grants as a result of Your choice to
+ distribute the Covered Software under a subsequent version of this License
+ (see Section 10.2) or under the terms of a Secondary License (if permitted
+ under the terms of Section 3.3).
+
+2.5. Representation
+
+ Each Contributor represents that the Contributor believes its Contributions
+ are its original creation(s) or it has sufficient rights to grant the
+ rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+ This License is not intended to limit any rights You have under applicable
+ copyright doctrines of fair use, fair dealing, or other equivalents.
+
+2.7. Conditions
+
+ Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
+ Section 2.1.
+
+
+3. Responsibilities
+
+3.1. Distribution of Source Form
+
+ All distribution of Covered Software in Source Code Form, including any
+ Modifications that You create or to which You contribute, must be under the
+ terms of this License. You must inform recipients that the Source Code Form
+ of the Covered Software is governed by the terms of this License, and how
+ they can obtain a copy of this License. You may not attempt to alter or
+ restrict the recipients’ rights in the Source Code Form.
+
+3.2. Distribution of Executable Form
+
+ If You distribute Covered Software in Executable Form then:
+
+ a. such Covered Software must also be made available in Source Code Form,
+ as described in Section 3.1, and You must inform recipients of the
+ Executable Form how they can obtain a copy of such Source Code Form by
+ reasonable means in a timely manner, at a charge no more than the cost
+ of distribution to the recipient; and
+
+ b. You may distribute such Executable Form under the terms of this License,
+ or sublicense it under different terms, provided that the license for
+ the Executable Form does not attempt to limit or alter the recipients’
+ rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+ You may create and distribute a Larger Work under terms of Your choice,
+ provided that You also comply with the requirements of this License for the
+ Covered Software. If the Larger Work is a combination of Covered Software
+ with a work governed by one or more Secondary Licenses, and the Covered
+ Software is not Incompatible With Secondary Licenses, this License permits
+ You to additionally distribute such Covered Software under the terms of
+ such Secondary License(s), so that the recipient of the Larger Work may, at
+ their option, further distribute the Covered Software under the terms of
+ either this License or such Secondary License(s).
+
+3.4. Notices
+
+ You may not remove or alter the substance of any license notices (including
+ copyright notices, patent notices, disclaimers of warranty, or limitations
+ of liability) contained within the Source Code Form of the Covered
+ Software, except that You may alter any license notices to the extent
+ required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+ You may choose to offer, and to charge a fee for, warranty, support,
+ indemnity or liability obligations to one or more recipients of Covered
+ Software. However, You may do so only on Your own behalf, and not on behalf
+ of any Contributor. You must make it absolutely clear that any such
+ warranty, support, indemnity, or liability obligation is offered by You
+ alone, and You hereby agree to indemnify every Contributor for any
+ liability incurred by such Contributor as a result of warranty, support,
+ indemnity or liability terms You offer. You may include additional
+ disclaimers of warranty and limitations of liability specific to any
+ jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+
+ If it is impossible for You to comply with any of the terms of this License
+ with respect to some or all of the Covered Software due to statute, judicial
+ order, or regulation then You must: (a) comply with the terms of this License
+ to the maximum extent possible; and (b) describe the limitations and the code
+ they affect. Such description must be placed in a text file included with all
+ distributions of the Covered Software under this License. Except to the
+ extent prohibited by statute or regulation, such description must be
+ sufficiently detailed for a recipient of ordinary skill to be able to
+ understand it.
+
+5. Termination
+
+5.1. The rights granted under this License will terminate automatically if You
+ fail to comply with any of its terms. However, if You become compliant,
+ then the rights granted under this License from a particular Contributor
+ are reinstated (a) provisionally, unless and until such Contributor
+ explicitly and finally terminates Your grants, and (b) on an ongoing basis,
+ if such Contributor fails to notify You of the non-compliance by some
+ reasonable means prior to 60 days after You have come back into compliance.
+ Moreover, Your grants from a particular Contributor are reinstated on an
+ ongoing basis if such Contributor notifies You of the non-compliance by
+ some reasonable means, this is the first time You have received notice of
+ non-compliance with this License from such Contributor, and You become
+ compliant prior to 30 days after Your receipt of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+ infringement claim (excluding declaratory judgment actions, counter-claims,
+ and cross-claims) alleging that a Contributor Version directly or
+ indirectly infringes any patent, then the rights granted to You by any and
+ all Contributors for the Covered Software under Section 2.1 of this License
+ shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
+ license agreements (excluding distributors and resellers) which have been
+ validly granted by You or Your distributors under this License prior to
+ termination shall survive termination.
+
+6. Disclaimer of Warranty
+
+ Covered Software is provided under this License on an “as is” basis, without
+ warranty of any kind, either expressed, implied, or statutory, including,
+ without limitation, warranties that the Covered Software is free of defects,
+ merchantable, fit for a particular purpose or non-infringing. The entire
+ risk as to the quality and performance of the Covered Software is with You.
+ Should any Covered Software prove defective in any respect, You (not any
+ Contributor) assume the cost of any necessary servicing, repair, or
+ correction. This disclaimer of warranty constitutes an essential part of this
+ License. No use of any Covered Software is authorized under this License
+ except under this disclaimer.
+
+7. Limitation of Liability
+
+ Under no circumstances and under no legal theory, whether tort (including
+ negligence), contract, or otherwise, shall any Contributor, or anyone who
+ distributes Covered Software as permitted above, be liable to You for any
+ direct, indirect, special, incidental, or consequential damages of any
+ character including, without limitation, damages for lost profits, loss of
+ goodwill, work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses, even if such party shall have been
+ informed of the possibility of such damages. This limitation of liability
+ shall not apply to liability for death or personal injury resulting from such
+ party’s negligence to the extent applicable law prohibits such limitation.
+ Some jurisdictions do not allow the exclusion or limitation of incidental or
+ consequential damages, so this exclusion and limitation may not apply to You.
+
+8. Litigation
+
+ Any litigation relating to this License may be brought only in the courts of
+ a jurisdiction where the defendant maintains its principal place of business
+ and such litigation shall be governed by laws of that jurisdiction, without
+ reference to its conflict-of-law provisions. Nothing in this Section shall
+ prevent a party’s ability to bring cross-claims or counter-claims.
+
+9. Miscellaneous
+
+ This License represents the complete agreement concerning the subject matter
+ hereof. If any provision of this License is held to be unenforceable, such
+ provision shall be reformed only to the extent necessary to make it
+ enforceable. Any law or regulation which provides that the language of a
+ contract shall be construed against the drafter shall not be used to construe
+ this License against a Contributor.
+
+
+10. Versions of the License
+
+10.1. New Versions
+
+ Mozilla Foundation is the license steward. Except as provided in Section
+ 10.3, no one other than the license steward has the right to modify or
+ publish new versions of this License. Each version will be given a
+ distinguishing version number.
+
+10.2. Effect of New Versions
+
+ You may distribute the Covered Software under the terms of the version of
+ the License under which You originally received the Covered Software, or
+ under the terms of any subsequent version published by the license
+ steward.
+
+10.3. Modified Versions
+
+ If you create software not governed by this License, and you want to
+ create a new license for such software, you may create and use a modified
+ version of this License if you rename the license and remove any
+ references to the name of the license steward (except to note that such
+ modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
+ If You choose to distribute Source Code Form that is Incompatible With
+ Secondary Licenses under the terms of this version of the License, the
+ notice described in Exhibit B of this License must be attached.
+
+Exhibit A - Source Code Form License Notice
+
+ This Source Code Form is subject to the
+ terms of the Mozilla Public License, v.
+ 2.0. If a copy of the MPL was not
+ distributed with this file, You can
+ obtain one at
+ http://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular file, then
+You may include the notice in a location (such as a LICENSE file in a relevant
+directory) where a recipient would be likely to look for such a notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - “Incompatible With Secondary Licenses” Notice
+
+ This Source Code Form is “Incompatible
+ With Secondary Licenses”, as defined by
+ the Mozilla Public License, v. 2.0.
+
diff -Naur --color b/vendor/github.com/hashicorp/raft/log_cache.go a/vendor/github.com/hashicorp/raft/log_cache.go
--- b/vendor/github.com/hashicorp/raft/log_cache.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/log_cache.go 2022-11-15 23:06:31.565391195 +0100
@@ -0,0 +1,79 @@
+package raft
+
+import (
+ "fmt"
+ "sync"
+)
+
+// LogCache wraps any LogStore implementation to provide an
+// in-memory ring buffer. This is used to cache access to
+// the recently written entries. For implementations that do not
+// cache themselves, this can provide a substantial boost by
+// avoiding disk I/O on recent entries.
+type LogCache struct {
+ store LogStore
+
+ cache []*Log
+ l sync.RWMutex
+}
+
+// NewLogCache is used to create a new LogCache with the
+// given capacity and backend store.
+func NewLogCache(capacity int, store LogStore) (*LogCache, error) {
+ if capacity <= 0 {
+ return nil, fmt.Errorf("capacity must be positive")
+ }
+ c := &LogCache{
+ store: store,
+ cache: make([]*Log, capacity),
+ }
+ return c, nil
+}
+
+func (c *LogCache) GetLog(idx uint64, log *Log) error {
+ // Check the buffer for an entry
+ c.l.RLock()
+ cached := c.cache[idx%uint64(len(c.cache))]
+ c.l.RUnlock()
+
+ // Check if entry is valid
+ if cached != nil && cached.Index == idx {
+ *log = *cached
+ return nil
+ }
+
+ // Forward request on cache miss
+ return c.store.GetLog(idx, log)
+}
+
+func (c *LogCache) StoreLog(log *Log) error {
+ return c.StoreLogs([]*Log{log})
+}
+
+func (c *LogCache) StoreLogs(logs []*Log) error {
+ // Insert the logs into the ring buffer
+ c.l.Lock()
+ for _, l := range logs {
+ c.cache[l.Index%uint64(len(c.cache))] = l
+ }
+ c.l.Unlock()
+
+ return c.store.StoreLogs(logs)
+}
+
+func (c *LogCache) FirstIndex() (uint64, error) {
+ return c.store.FirstIndex()
+}
+
+func (c *LogCache) LastIndex() (uint64, error) {
+ return c.store.LastIndex()
+}
+
+func (c *LogCache) DeleteRange(min, max uint64) error {
+ // Invalidate the cache on deletes
+ c.l.Lock()
+ c.cache = make([]*Log, len(c.cache))
+ c.l.Unlock()
+
+ return c.store.DeleteRange(min, max)
+}
diff -Naur --color b/vendor/github.com/hashicorp/raft/log.go a/vendor/github.com/hashicorp/raft/log.go
--- b/vendor/github.com/hashicorp/raft/log.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/log.go 2022-11-15 23:06:31.565391195 +0100
@@ -0,0 +1,87 @@
+package raft
+
+// LogType describes various types of log entries.
+type LogType uint8
+
+const (
+ // LogCommand is applied to a user FSM.
+ LogCommand LogType = iota
+
+ // LogNoop is used to assert leadership.
+ LogNoop
+
+ // LogAddPeer is used to add a new peer. This should only be used with
+ // older protocol versions designed to be compatible with unversioned
+ // Raft servers. See comments in config.go for details.
+ LogAddPeerDeprecated
+
+ // LogRemovePeer is used to remove an existing peer. This should only be
+ // used with older protocol versions designed to be compatible with
+ // unversioned Raft servers. See comments in config.go for details.
+ LogRemovePeerDeprecated
+
+ // LogBarrier is used to ensure all preceding operations have been
+ // applied to the FSM. It is similar to LogNoop, but instead of returning
+ // once committed, it only returns once the FSM manager acks it. Otherwise
+ // it is possible there are operations committed but not yet applied to
+ // the FSM.
+ LogBarrier
+
+ // LogConfiguration establishes a membership change configuration. It is
+ // created when a server is added, removed, promoted, etc. Only used
+ // when protocol version 1 or greater is in use.
+ LogConfiguration
+)
+
+// Log entries are replicated to all members of the Raft cluster
+// and form the heart of the replicated state machine.
+type Log struct {
+ // Index holds the index of the log entry.
+ Index uint64
+
+ // Term holds the election term of the log entry.
+ Term uint64
+
+ // Type holds the type of the log entry.
+ Type LogType
+
+ // Data holds the log entry's type-specific data.
+ Data []byte
+
+ // Extensions holds an opaque byte slice of information for middleware. It
+ // is up to the client of the library to properly modify this as it adds
+ // layers and remove those layers when appropriate. This value is a part of
+ // the log, so very large values could cause timing issues.
+ //
+ // N.B. It is _up to the client_ to handle upgrade paths. For instance if
+ // using this with go-raftchunking, the client should ensure that all Raft
+ // peers are using a version that can handle that extension before ever
+ // actually triggering chunking behavior. It is sometimes sufficient to
+ // ensure that non-leaders are upgraded first, then the current leader is
+ // upgraded, but a leader changeover during this process could lead to
+ // trouble, so gating extension behavior via some flag in the client
+ // program is also a good idea.
+ Extensions []byte
+}
+
+// LogStore is used to provide an interface for storing
+// and retrieving logs in a durable fashion.
+type LogStore interface {
+ // FirstIndex returns the first index written. 0 for no entries.
+ FirstIndex() (uint64, error)
+
+ // LastIndex returns the last index written. 0 for no entries.
+ LastIndex() (uint64, error)
+
+ // GetLog gets a log entry at a given index.
+ GetLog(index uint64, log *Log) error
+
+ // StoreLog stores a log entry.
+ StoreLog(log *Log) error
+
+ // StoreLogs stores multiple log entries.
+ StoreLogs(logs []*Log) error
+
+ // DeleteRange deletes a range of log entries. The range is inclusive.
+ DeleteRange(min, max uint64) error
+}
diff -Naur --color b/vendor/github.com/hashicorp/raft/Makefile a/vendor/github.com/hashicorp/raft/Makefile
--- b/vendor/github.com/hashicorp/raft/Makefile 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/Makefile 2022-11-15 23:06:31.562057797 +0100
@@ -0,0 +1,30 @@
+DEPS = $(go list -f '{{range .TestImports}}{{.}} {{end}}' ./...)
+TEST_RESULTS_DIR?=/tmp/test-results
+
+test:
+ go test -timeout=60s -race .
+
+integ: test
+ INTEG_TESTS=yes go test -timeout=25s -run=Integ .
+
+ci.test-norace:
+ gotestsum --format=short-verbose --junitfile $(TEST_RESULTS_DIR)/gotestsum-report-test.xml -- -timeout=60s
+
+ci.test:
+ gotestsum --format=short-verbose --junitfile $(TEST_RESULTS_DIR)/gotestsum-report-test.xml -- -timeout=60s -race .
+
+ci.integ: ci.test
+ INTEG_TESTS=yes gotestsum --format=short-verbose --junitfile $(TEST_RESULTS_DIR)/gotestsum-report-integ.xml -- -timeout=25s -run=Integ .
+
+fuzz:
+ go test -timeout=300s ./fuzzy
+
+deps:
+ go get -t -d -v ./...
+ echo $(DEPS) | xargs -n1 go get -d
+
+cov:
+ INTEG_TESTS=yes gocov test github.com/hashicorp/raft | gocov-html > /tmp/coverage.html
+ open /tmp/coverage.html
+
+.PHONY: test cov integ deps
diff -Naur --color b/vendor/github.com/hashicorp/raft/membership.md a/vendor/github.com/hashicorp/raft/membership.md
--- b/vendor/github.com/hashicorp/raft/membership.md 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/membership.md 2022-11-15 23:06:31.565391195 +0100
@@ -0,0 +1,83 @@
+Simon (@superfell) and I (@ongardie) talked through reworking this library's cluster membership changes last Friday. We don't see a way to split this into independent patches, so we're taking the next best approach: submitting the plan here for review, then working on an enormous PR. Your feedback would be appreciated. (@superfell is out this week, however, so don't expect him to respond quickly.)
+
+These are the main goals:
+ - Bringing things in line with the description in my PhD dissertation;
+ - Catching up new servers prior to granting them a vote, as well as allowing permanent non-voting members; and
+ - Eliminating the `peers.json` file, to avoid issues of consistency between that and the log/snapshot.
+
+## Data-centric view
+
+We propose to re-define a *configuration* as a set of servers, where each server includes an address (as it does today) and a mode that is either:
+ - *Voter*: a server whose vote is counted in elections and whose match index is used in advancing the leader's commit index.
+ - *Nonvoter*: a server that receives log entries but is not considered for elections or commitment purposes.
+ - *Staging*: a server that acts like a nonvoter with one exception: once a staging server receives enough log entries to catch up sufficiently to the leader's log, the leader will invoke a membership change to change the staging server to a voter.
+
+All changes to the configuration will be done by writing a new configuration to the log. The new configuration will be in affect as soon as it is appended to the log (not when it is committed like a normal state machine command). Note that, per my dissertation, there can be at most one uncommitted configuration at a time (the next configuration may not be created until the prior one has been committed). It's not strictly necessary to follow these same rules for the nonvoter/staging servers, but we think its best to treat all changes uniformly.
+
+Each server will track two configurations:
+ 1. its *committed configuration*: the latest configuration in the log/snapshot that has been committed, along with its index.
+ 2. its *latest configuration*: the latest configuration in the log/snapshot (may be committed or uncommitted), along with its index.
+
+When there's no membership change happening, these two will be the same. The latest configuration is almost always the one used, except:
+ - When followers truncate the suffix of their logs, they may need to fall back to the committed configuration.
+ - When snapshotting, the committed configuration is written, to correspond with the committed log prefix that is being snapshotted.
+
+
+## Application API
+
+We propose the following operations for clients to manipulate the cluster configuration:
+ - AddVoter: server becomes staging unless voter,
+ - AddNonvoter: server becomes nonvoter unless staging or voter,
+ - DemoteVoter: server becomes nonvoter unless absent,
+ - RemovePeer: server removed from configuration,
+ - GetConfiguration: waits for latest config to commit, returns committed config.
+
+This diagram, of which I'm quite proud, shows the possible transitions:
+```
++-----------------------------------------------------------------------------+
+| |
+| Start -> +--------+ |
+| ,------<------------| | |
+| / | absent | |
+| / RemovePeer--> | | <---RemovePeer |
+| / | +--------+ \ |
+| / | | \ |
+| AddNonvoter | AddVoter \ |
+| | ,->---' `--<-. | \ |
+| v / \ v \ |
+| +----------+ +----------+ +----------+ |
+| | | ---AddVoter--> | | -log caught up --> | | |
+| | nonvoter | | staging | | voter | |
+| | | <-DemoteVoter- | | ,- | | |
+| +----------+ \ +----------+ / +----------+ |
+| \ / |
+| `--------------<---------------' |
+| |
++-----------------------------------------------------------------------------+
+```
+
+While these operations aren't quite symmetric, we think they're a good set to capture
+the possible intent of the user. For example, if I want to make sure a server doesn't have a vote, but the server isn't part of the configuration at all, it probably shouldn't be added as a nonvoting server.
+
+Each of these application-level operations will be interpreted by the leader and, if it has an effect, will cause the leader to write a new configuration entry to its log. Which particular application-level operation caused the log entry to be written need not be part of the log entry.
+
+## Code implications
+
+This is a non-exhaustive list, but we came up with a few things:
+- Remove the PeerStore: the `peers.json` file introduces the possibility of getting out of sync with the log and snapshot, and it's hard to maintain this atomically as the log changes. It's not clear whether it's meant to track the committed or latest configuration, either.
+- Servers will have to search their snapshot and log to find the committed configuration and the latest configuration on startup.
+- Bootstrap will no longer use `peers.json` but should initialize the log or snapshot with an application-provided configuration entry.
+- Snapshots should store the index of their configuration along with the configuration itself. In my experience with LogCabin, the original log index of the configuration is very useful to include in debug log messages.
+- As noted in hashicorp/raft#84, configuration change requests should come in via a separate channel, and one may not proceed until the last has been committed.
+- As to deciding when a log is sufficiently caught up, implementing a sophisticated algorithm *is* something that can be done in a separate PR. An easy and decent placeholder is: once the staging server has reached 95% of the leader's commit index, promote it.
+
+## Feedback
+
+Again, we're looking for feedback here before we start working on this. Here are some questions to think about:
+ - Does this seem like where we want things to go?
+ - Is there anything here that should be left out?
+ - Is there anything else we're forgetting about?
+ - Is there a good way to break this up?
+ - What do we need to worry about in terms of backwards compatibility?
+ - What implication will this have on current tests?
+ - What's the best way to test this code, in particular the small changes that will be sprinkled all over the library?
diff -Naur --color b/vendor/github.com/hashicorp/raft/net_transport.go a/vendor/github.com/hashicorp/raft/net_transport.go
--- b/vendor/github.com/hashicorp/raft/net_transport.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/net_transport.go 2022-11-15 23:06:31.565391195 +0100
@@ -0,0 +1,770 @@
+package raft
+
+import (
+ "bufio"
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+ "net"
+ "os"
+ "sync"
+ "time"
+
+ "github.com/hashicorp/go-msgpack/codec"
+)
+
+const (
+ rpcAppendEntries uint8 = iota
+ rpcRequestVote
+ rpcInstallSnapshot
+ rpcTimeoutNow
+
+ // DefaultTimeoutScale is the default TimeoutScale in a NetworkTransport.
+ DefaultTimeoutScale = 256 * 1024 // 256KB
+
+ // rpcMaxPipeline controls the maximum number of outstanding
+ // AppendEntries RPC calls.
+ rpcMaxPipeline = 128
+)
+
+var (
+ // ErrTransportShutdown is returned when operations on a transport are
+ // invoked after it's been terminated.
+ ErrTransportShutdown = errors.New("transport shutdown")
+
+ // ErrPipelineShutdown is returned when the pipeline is closed.
+ ErrPipelineShutdown = errors.New("append pipeline closed")
+)
+
+/*
+
+NetworkTransport provides a network based transport that can be
+used to communicate with Raft on remote machines. It requires
+an underlying stream layer to provide a stream abstraction, which can
+be simple TCP, TLS, etc.
+
+This transport is very simple and lightweight. Each RPC request is
+framed by sending a byte that indicates the message type, followed
+by the MsgPack encoded request.
+
+The response is an error string followed by the response object,
+both are encoded using MsgPack.
+
+InstallSnapshot is special, in that after the RPC request we stream
+the entire state. That socket is not re-used as the connection state
+is not known if there is an error.
+
+*/
+type NetworkTransport struct {
+ connPool map[ServerAddress][]*netConn
+ connPoolLock sync.Mutex
+
+ consumeCh chan RPC
+
+ heartbeatFn func(RPC)
+ heartbeatFnLock sync.Mutex
+
+ logger *log.Logger
+
+ maxPool int
+
+ serverAddressProvider ServerAddressProvider
+
+ shutdown bool
+ shutdownCh chan struct{}
+ shutdownLock sync.Mutex
+
+ stream StreamLayer
+
+ // streamCtx is used to cancel existing connection handlers.
+ streamCtx context.Context
+ streamCancel context.CancelFunc
+ streamCtxLock sync.RWMutex
+
+ timeout time.Duration
+ TimeoutScale int
+}
+
+// NetworkTransportConfig encapsulates configuration for the network transport layer.
+type NetworkTransportConfig struct {
+ // ServerAddressProvider is used to override the target address when establishing a connection to invoke an RPC
+ ServerAddressProvider ServerAddressProvider
+
+ Logger *log.Logger
+
+ // Dialer
+ Stream StreamLayer
+
+ // MaxPool controls how many connections we will pool
+ MaxPool int
+
+ // Timeout is used to apply I/O deadlines. For InstallSnapshot, we multiply
+ // the timeout by (SnapshotSize / TimeoutScale).
+ Timeout time.Duration
+}
+
+type ServerAddressProvider interface {
+ ServerAddr(id ServerID) (ServerAddress, error)
+}
+
+// StreamLayer is used with the NetworkTransport to provide
+// the low level stream abstraction.
+type StreamLayer interface {
+ net.Listener
+
+ // Dial is used to create a new outgoing connection
+ Dial(address ServerAddress, timeout time.Duration) (net.Conn, error)
+}
+
+type netConn struct {
+ target ServerAddress
+ conn net.Conn
+ r *bufio.Reader
+ w *bufio.Writer
+ dec *codec.Decoder
+ enc *codec.Encoder
+}
+
+func (n *netConn) Release() error {
+ return n.conn.Close()
+}
+
+type netPipeline struct {
+ conn *netConn
+ trans *NetworkTransport
+
+ doneCh chan AppendFuture
+ inprogressCh chan *appendFuture
+
+ shutdown bool
+ shutdownCh chan struct{}
+ shutdownLock sync.Mutex
+}
+
+// NewNetworkTransportWithConfig creates a new network transport with the given config struct
+func NewNetworkTransportWithConfig(
+ config *NetworkTransportConfig,
+) *NetworkTransport {
+ if config.Logger == nil {
+ config.Logger = log.New(os.Stderr, "", log.LstdFlags)
+ }
+ trans := &NetworkTransport{
+ connPool: make(map[ServerAddress][]*netConn),
+ consumeCh: make(chan RPC),
+ logger: config.Logger,
+ maxPool: config.MaxPool,
+ shutdownCh: make(chan struct{}),
+ stream: config.Stream,
+ timeout: config.Timeout,
+ TimeoutScale: DefaultTimeoutScale,
+ serverAddressProvider: config.ServerAddressProvider,
+ }
+
+ // Create the connection context and then start our listener.
+ trans.setupStreamContext()
+ go trans.listen()
+
+ return trans
+}
+
+// NewNetworkTransport creates a new network transport with the given dialer
+// and listener. The maxPool controls how many connections we will pool. The
+// timeout is used to apply I/O deadlines. For InstallSnapshot, we multiply
+// the timeout by (SnapshotSize / TimeoutScale).
+func NewNetworkTransport(
+ stream StreamLayer,
+ maxPool int,
+ timeout time.Duration,
+ logOutput io.Writer,
+) *NetworkTransport {
+ if logOutput == nil {
+ logOutput = os.Stderr
+ }
+ logger := log.New(logOutput, "", log.LstdFlags)
+ config := &NetworkTransportConfig{Stream: stream, MaxPool: maxPool, Timeout: timeout, Logger: logger}
+ return NewNetworkTransportWithConfig(config)
+}
+
+// NewNetworkTransportWithLogger creates a new network transport with the given logger, dialer
+// and listener. The maxPool controls how many connections we will pool. The
+// timeout is used to apply I/O deadlines. For InstallSnapshot, we multiply
+// the timeout by (SnapshotSize / TimeoutScale).
+func NewNetworkTransportWithLogger(
+ stream StreamLayer,
+ maxPool int,
+ timeout time.Duration,
+ logger *log.Logger,
+) *NetworkTransport {
+ config := &NetworkTransportConfig{Stream: stream, MaxPool: maxPool, Timeout: timeout, Logger: logger}
+ return NewNetworkTransportWithConfig(config)
+}
+
+// setupStreamContext is used to create a new stream context. This should be
+// called with the stream lock held.
+func (n *NetworkTransport) setupStreamContext() {
+ ctx, cancel := context.WithCancel(context.Background())
+ n.streamCtx = ctx
+ n.streamCancel = cancel
+}
+
+// getStreamContext is used retrieve the current stream context.
+func (n *NetworkTransport) getStreamContext() context.Context {
+ n.streamCtxLock.RLock()
+ defer n.streamCtxLock.RUnlock()
+ return n.streamCtx
+}
+
+// SetHeartbeatHandler is used to setup a heartbeat handler
+// as a fast-pass. This is to avoid head-of-line blocking from
+// disk IO.
+func (n *NetworkTransport) SetHeartbeatHandler(cb func(rpc RPC)) {
+ n.heartbeatFnLock.Lock()
+ defer n.heartbeatFnLock.Unlock()
+ n.heartbeatFn = cb
+}
+
+// CloseStreams closes the current streams.
+func (n *NetworkTransport) CloseStreams() {
+ n.connPoolLock.Lock()
+ defer n.connPoolLock.Unlock()
+
+ // Close all the connections in the connection pool and then remove their
+ // entry.
+ for k, e := range n.connPool {
+ for _, conn := range e {
+ conn.Release()
+ }
+
+ delete(n.connPool, k)
+ }
+
+ // Cancel the existing connections and create a new context. Both these
+ // operations must always be done with the lock held otherwise we can create
+ // connection handlers that are holding a context that will never be
+ // cancelable.
+ n.streamCtxLock.Lock()
+ n.streamCancel()
+ n.setupStreamContext()
+ n.streamCtxLock.Unlock()
+}
+
+// Close is used to stop the network transport.
+func (n *NetworkTransport) Close() error {
+ n.shutdownLock.Lock()
+ defer n.shutdownLock.Unlock()
+
+ if !n.shutdown {
+ close(n.shutdownCh)
+ n.stream.Close()
+ n.shutdown = true
+ }
+ return nil
+}
+
+// Consumer implements the Transport interface.
+func (n *NetworkTransport) Consumer() <-chan RPC {
+ return n.consumeCh
+}
+
+// LocalAddr implements the Transport interface.
+func (n *NetworkTransport) LocalAddr() ServerAddress {
+ return ServerAddress(n.stream.Addr().String())
+}
+
+// IsShutdown is used to check if the transport is shutdown.
+func (n *NetworkTransport) IsShutdown() bool {
+ select {
+ case <-n.shutdownCh:
+ return true
+ default:
+ return false
+ }
+}
+
+// getExistingConn is used to grab a pooled connection.
+func (n *NetworkTransport) getPooledConn(target ServerAddress) *netConn {
+ n.connPoolLock.Lock()
+ defer n.connPoolLock.Unlock()
+
+ conns, ok := n.connPool[target]
+ if !ok || len(conns) == 0 {
+ return nil
+ }
+
+ var conn *netConn
+ num := len(conns)
+ conn, conns[num-1] = conns[num-1], nil
+ n.connPool[target] = conns[:num-1]
+ return conn
+}
+
+// getConnFromAddressProvider returns a connection from the server address provider if available, or defaults to a connection using the target server address
+func (n *NetworkTransport) getConnFromAddressProvider(id ServerID, target ServerAddress) (*netConn, error) {
+ address := n.getProviderAddressOrFallback(id, target)
+ return n.getConn(address)
+}
+
+func (n *NetworkTransport) getProviderAddressOrFallback(id ServerID, target ServerAddress) ServerAddress {
+ if n.serverAddressProvider != nil {
+ serverAddressOverride, err := n.serverAddressProvider.ServerAddr(id)
+ if err != nil {
+ n.logger.Printf("[WARN] raft: Unable to get address for server id %v, using fallback address %v: %v", id, target, err)
+ } else {
+ return serverAddressOverride
+ }
+ }
+ return target
+}
+
+// getConn is used to get a connection from the pool.
+func (n *NetworkTransport) getConn(target ServerAddress) (*netConn, error) {
+ // Check for a pooled conn
+ if conn := n.getPooledConn(target); conn != nil {
+ return conn, nil
+ }
+
+ // Dial a new connection
+ conn, err := n.stream.Dial(target, n.timeout)
+ if err != nil {
+ return nil, err
+ }
+
+ // Wrap the conn
+ netConn := &netConn{
+ target: target,
+ conn: conn,
+ r: bufio.NewReader(conn),
+ w: bufio.NewWriter(conn),
+ }
+
+ // Setup encoder/decoders
+ netConn.dec = codec.NewDecoder(netConn.r, &codec.MsgpackHandle{})
+ netConn.enc = codec.NewEncoder(netConn.w, &codec.MsgpackHandle{})
+
+ // Done
+ return netConn, nil
+}
+
+// returnConn returns a connection back to the pool.
+func (n *NetworkTransport) returnConn(conn *netConn) {
+ n.connPoolLock.Lock()
+ defer n.connPoolLock.Unlock()
+
+ key := conn.target
+ conns, _ := n.connPool[key]
+
+ if !n.IsShutdown() && len(conns) < n.maxPool {
+ n.connPool[key] = append(conns, conn)
+ } else {
+ conn.Release()
+ }
+}
+
+// AppendEntriesPipeline returns an interface that can be used to pipeline
+// AppendEntries requests.
+func (n *NetworkTransport) AppendEntriesPipeline(id ServerID, target ServerAddress) (AppendPipeline, error) {
+ // Get a connection
+ conn, err := n.getConnFromAddressProvider(id, target)
+ if err != nil {
+ return nil, err
+ }
+
+ // Create the pipeline
+ return newNetPipeline(n, conn), nil
+}
+
+// AppendEntries implements the Transport interface.
+func (n *NetworkTransport) AppendEntries(id ServerID, target ServerAddress, args *AppendEntriesRequest, resp *AppendEntriesResponse) error {
+ return n.genericRPC(id, target, rpcAppendEntries, args, resp)
+}
+
+// RequestVote implements the Transport interface.
+func (n *NetworkTransport) RequestVote(id ServerID, target ServerAddress, args *RequestVoteRequest, resp *RequestVoteResponse) error {
+ return n.genericRPC(id, target, rpcRequestVote, args, resp)
+}
+
+// genericRPC handles a simple request/response RPC.
+func (n *NetworkTransport) genericRPC(id ServerID, target ServerAddress, rpcType uint8, args interface{}, resp interface{}) error {
+ // Get a conn
+ conn, err := n.getConnFromAddressProvider(id, target)
+ if err != nil {
+ return err
+ }
+
+ // Set a deadline
+ if n.timeout > 0 {
+ conn.conn.SetDeadline(time.Now().Add(n.timeout))
+ }
+
+ // Send the RPC
+ if err = sendRPC(conn, rpcType, args); err != nil {
+ return err
+ }
+
+ // Decode the response
+ canReturn, err := decodeResponse(conn, resp)
+ if canReturn {
+ n.returnConn(conn)
+ }
+ return err
+}
+
+// InstallSnapshot implements the Transport interface.
+func (n *NetworkTransport) InstallSnapshot(id ServerID, target ServerAddress, args *InstallSnapshotRequest, resp *InstallSnapshotResponse, data io.Reader) error {
+ // Get a conn, always close for InstallSnapshot
+ conn, err := n.getConnFromAddressProvider(id, target)
+ if err != nil {
+ return err
+ }
+ defer conn.Release()
+
+ // Set a deadline, scaled by request size
+ if n.timeout > 0 {
+ timeout := n.timeout * time.Duration(args.Size/int64(n.TimeoutScale))
+ if timeout < n.timeout {
+ timeout = n.timeout
+ }
+ conn.conn.SetDeadline(time.Now().Add(timeout))
+ }
+
+ // Send the RPC
+ if err = sendRPC(conn, rpcInstallSnapshot, args); err != nil {
+ return err
+ }
+
+ // Stream the state
+ if _, err = io.Copy(conn.w, data); err != nil {
+ return err
+ }
+
+ // Flush
+ if err = conn.w.Flush(); err != nil {
+ return err
+ }
+
+ // Decode the response, do not return conn
+ _, err = decodeResponse(conn, resp)
+ return err
+}
+
+// EncodePeer implements the Transport interface.
+func (n *NetworkTransport) EncodePeer(id ServerID, p ServerAddress) []byte {
+ address := n.getProviderAddressOrFallback(id, p)
+ return []byte(address)
+}
+
+// DecodePeer implements the Transport interface.
+func (n *NetworkTransport) DecodePeer(buf []byte) ServerAddress {
+ return ServerAddress(buf)
+}
+
+// TimeoutNow implements the Transport interface.
+func (n *NetworkTransport) TimeoutNow(id ServerID, target ServerAddress, args *TimeoutNowRequest, resp *TimeoutNowResponse) error {
+ return n.genericRPC(id, target, rpcTimeoutNow, args, resp)
+}
+
+// listen is used to handling incoming connections.
+func (n *NetworkTransport) listen() {
+ const baseDelay = 5 * time.Millisecond
+ const maxDelay = 1 * time.Second
+
+ var loopDelay time.Duration
+ for {
+ // Accept incoming connections
+ conn, err := n.stream.Accept()
+ if err != nil {
+ if loopDelay == 0 {
+ loopDelay = baseDelay
+ } else {
+ loopDelay *= 2
+ }
+
+ if loopDelay > maxDelay {
+ loopDelay = maxDelay
+ }
+
+ if !n.IsShutdown() {
+ n.logger.Printf("[ERR] raft-net: Failed to accept connection: %v", err)
+ }
+
+ select {
+ case <-n.shutdownCh:
+ return
+ case <-time.After(loopDelay):
+ continue
+ }
+ }
+ // No error, reset loop delay
+ loopDelay = 0
+
+ n.logger.Printf("[DEBUG] raft-net: %v accepted connection from: %v", n.LocalAddr(), conn.RemoteAddr())
+
+ // Handle the connection in dedicated routine
+ go n.handleConn(n.getStreamContext(), conn)
+ }
+}
+
+// handleConn is used to handle an inbound connection for its lifespan. The
+// handler will exit when the passed context is cancelled or the connection is
+// closed.
+func (n *NetworkTransport) handleConn(connCtx context.Context, conn net.Conn) {
+ defer conn.Close()
+ r := bufio.NewReader(conn)
+ w := bufio.NewWriter(conn)
+ dec := codec.NewDecoder(r, &codec.MsgpackHandle{})
+ enc := codec.NewEncoder(w, &codec.MsgpackHandle{})
+
+ for {
+ select {
+ case <-connCtx.Done():
+ n.logger.Println("[DEBUG] raft-net: stream layer is closed")
+ return
+ default:
+ }
+
+ if err := n.handleCommand(r, dec, enc); err != nil {
+ if err != io.EOF {
+ n.logger.Printf("[ERR] raft-net: Failed to decode incoming command: %v", err)
+ }
+ return
+ }
+ if err := w.Flush(); err != nil {
+ n.logger.Printf("[ERR] raft-net: Failed to flush response: %v", err)
+ return
+ }
+ }
+}
+
+// handleCommand is used to decode and dispatch a single command.
+func (n *NetworkTransport) handleCommand(r *bufio.Reader, dec *codec.Decoder, enc *codec.Encoder) error {
+ // Get the rpc type
+ rpcType, err := r.ReadByte()
+ if err != nil {
+ return err
+ }
+
+ // Create the RPC object
+ respCh := make(chan RPCResponse, 1)
+ rpc := RPC{
+ RespChan: respCh,
+ }
+
+ // Decode the command
+ isHeartbeat := false
+ switch rpcType {
+ case rpcAppendEntries:
+ var req AppendEntriesRequest
+ if err := dec.Decode(&req); err != nil {
+ return err
+ }
+ rpc.Command = &req
+
+ // Check if this is a heartbeat
+ if req.Term != 0 && req.Leader != nil &&
+ req.PrevLogEntry == 0 && req.PrevLogTerm == 0 &&
+ len(req.Entries) == 0 && req.LeaderCommitIndex == 0 {
+ isHeartbeat = true
+ }
+
+ case rpcRequestVote:
+ var req RequestVoteRequest
+ if err := dec.Decode(&req); err != nil {
+ return err
+ }
+ rpc.Command = &req
+
+ case rpcInstallSnapshot:
+ var req InstallSnapshotRequest
+ if err := dec.Decode(&req); err != nil {
+ return err
+ }
+ rpc.Command = &req
+ rpc.Reader = io.LimitReader(r, req.Size)
+
+ case rpcTimeoutNow:
+ var req TimeoutNowRequest
+ if err := dec.Decode(&req); err != nil {
+ return err
+ }
+ rpc.Command = &req
+
+ default:
+ return fmt.Errorf("unknown rpc type %d", rpcType)
+ }
+
+ // Check for heartbeat fast-path
+ if isHeartbeat {
+ n.heartbeatFnLock.Lock()
+ fn := n.heartbeatFn
+ n.heartbeatFnLock.Unlock()
+ if fn != nil {
+ fn(rpc)
+ goto RESP
+ }
+ }
+
+ // Dispatch the RPC
+ select {
+ case n.consumeCh <- rpc:
+ case <-n.shutdownCh:
+ return ErrTransportShutdown
+ }
+
+ // Wait for response
+RESP:
+ select {
+ case resp := <-respCh:
+ // Send the error first
+ respErr := ""
+ if resp.Error != nil {
+ respErr = resp.Error.Error()
+ }
+ if err := enc.Encode(respErr); err != nil {
+ return err
+ }
+
+ // Send the response
+ if err := enc.Encode(resp.Response); err != nil {
+ return err
+ }
+ case <-n.shutdownCh:
+ return ErrTransportShutdown
+ }
+ return nil
+}
+
+// decodeResponse is used to decode an RPC response and reports whether
+// the connection can be reused.
+func decodeResponse(conn *netConn, resp interface{}) (bool, error) {
+ // Decode the error if any
+ var rpcError string
+ if err := conn.dec.Decode(&rpcError); err != nil {
+ conn.Release()
+ return false, err
+ }
+
+ // Decode the response
+ if err := conn.dec.Decode(resp); err != nil {
+ conn.Release()
+ return false, err
+ }
+
+ // Format an error if any
+ if rpcError != "" {
+ return true, fmt.Errorf(rpcError)
+ }
+ return true, nil
+}
+
+// sendRPC is used to encode and send the RPC.
+func sendRPC(conn *netConn, rpcType uint8, args interface{}) error {
+ // Write the request type
+ if err := conn.w.WriteByte(rpcType); err != nil {
+ conn.Release()
+ return err
+ }
+
+ // Send the request
+ if err := conn.enc.Encode(args); err != nil {
+ conn.Release()
+ return err
+ }
+
+ // Flush
+ if err := conn.w.Flush(); err != nil {
+ conn.Release()
+ return err
+ }
+ return nil
+}
+
+// newNetPipeline is used to construct a netPipeline from a given
+// transport and connection.
+func newNetPipeline(trans *NetworkTransport, conn *netConn) *netPipeline {
+ n := &netPipeline{
+ conn: conn,
+ trans: trans,
+ doneCh: make(chan AppendFuture, rpcMaxPipeline),
+ inprogressCh: make(chan *appendFuture, rpcMaxPipeline),
+ shutdownCh: make(chan struct{}),
+ }
+ go n.decodeResponses()
+ return n
+}
+
+// decodeResponses is a long running routine that decodes the responses
+// sent on the connection.
+func (n *netPipeline) decodeResponses() {
+ timeout := n.trans.timeout
+ for {
+ select {
+ case future := <-n.inprogressCh:
+ if timeout > 0 {
+ n.conn.conn.SetReadDeadline(time.Now().Add(timeout))
+ }
+
+ _, err := decodeResponse(n.conn, future.resp)
+ future.respond(err)
+ select {
+ case n.doneCh <- future:
+ case <-n.shutdownCh:
+ return
+ }
+ case <-n.shutdownCh:
+ return
+ }
+ }
+}
+
+// AppendEntries is used to pipeline a new append entries request.
+func (n *netPipeline) AppendEntries(args *AppendEntriesRequest, resp *AppendEntriesResponse) (AppendFuture, error) {
+ // Create a new future
+ future := &appendFuture{
+ start: time.Now(),
+ args: args,
+ resp: resp,
+ }
+ future.init()
+
+ // Add a send timeout
+ if timeout := n.trans.timeout; timeout > 0 {
+ n.conn.conn.SetWriteDeadline(time.Now().Add(timeout))
+ }
+
+ // Send the RPC
+ if err := sendRPC(n.conn, rpcAppendEntries, future.args); err != nil {
+ return nil, err
+ }
+
+ // Hand-off for decoding, this can also cause back-pressure
+ // to prevent too many inflight requests
+ select {
+ case n.inprogressCh <- future:
+ return future, nil
+ case <-n.shutdownCh:
+ return nil, ErrPipelineShutdown
+ }
+}
+
+// Consumer returns a channel that can be used to consume complete futures.
+func (n *netPipeline) Consumer() <-chan AppendFuture {
+ return n.doneCh
+}
+
+// Closed is used to shutdown the pipeline connection.
+func (n *netPipeline) Close() error {
+ n.shutdownLock.Lock()
+ defer n.shutdownLock.Unlock()
+ if n.shutdown {
+ return nil
+ }
+
+ // Release the connection
+ n.conn.Release()
+
+ n.shutdown = true
+ close(n.shutdownCh)
+ return nil
+}
diff -Naur --color b/vendor/github.com/hashicorp/raft/observer.go a/vendor/github.com/hashicorp/raft/observer.go
--- b/vendor/github.com/hashicorp/raft/observer.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/observer.go 2022-11-15 23:06:31.565391195 +0100
@@ -0,0 +1,131 @@
+package raft
+
+import (
+ "sync/atomic"
+)
+
+// Observation is sent along the given channel to observers when an event occurs.
+type Observation struct {
+ // Raft holds the Raft instance generating the observation.
+ Raft *Raft
+ // Data holds observation-specific data. Possible types are
+ // *RequestVoteRequest
+ // RaftState
+ // PeerObservation
+ // LeaderObservation
+ Data interface{}
+}
+
+// LeaderObservation is used for the data when leadership changes.
+type LeaderObservation struct {
+ leader ServerAddress
+}
+
+// PeerObservation is sent to observers when peers change.
+type PeerObservation struct {
+ Removed bool
+ Peer Server
+}
+
+// nextObserverId is used to provide a unique ID for each observer to aid in
+// deregistration.
+var nextObserverID uint64
+
+// FilterFn is a function that can be registered in order to filter observations.
+// The function reports whether the observation should be included - if
+// it returns false, the observation will be filtered out.
+type FilterFn func(o *Observation) bool
+
+// Observer describes what to do with a given observation.
+type Observer struct {
+ // numObserved and numDropped are performance counters for this observer.
+ // 64 bit types must be 64 bit aligned to use with atomic operations on
+ // 32 bit platforms, so keep them at the top of the struct.
+ numObserved uint64
+ numDropped uint64
+
+ // channel receives observations.
+ channel chan Observation
+
+ // blocking, if true, will cause Raft to block when sending an observation
+ // to this observer. This should generally be set to false.
+ blocking bool
+
+ // filter will be called to determine if an observation should be sent to
+ // the channel.
+ filter FilterFn
+
+ // id is the ID of this observer in the Raft map.
+ id uint64
+}
+
+// NewObserver creates a new observer that can be registered
+// to make observations on a Raft instance. Observations
+// will be sent on the given channel if they satisfy the
+// given filter.
+//
+// If blocking is true, the observer will block when it can't
+// send on the channel, otherwise it may discard events.
+func NewObserver(channel chan Observation, blocking bool, filter FilterFn) *Observer {
+ return &Observer{
+ channel: channel,
+ blocking: blocking,
+ filter: filter,
+ id: atomic.AddUint64(&nextObserverID, 1),
+ }
+}
+
+// GetNumObserved returns the number of observations.
+func (or *Observer) GetNumObserved() uint64 {
+ return atomic.LoadUint64(&or.numObserved)
+}
+
+// GetNumDropped returns the number of dropped observations due to blocking.
+func (or *Observer) GetNumDropped() uint64 {
+ return atomic.LoadUint64(&or.numDropped)
+}
+
+// RegisterObserver registers a new observer.
+func (r *Raft) RegisterObserver(or *Observer) {
+ r.observersLock.Lock()
+ defer r.observersLock.Unlock()
+ r.observers[or.id] = or
+}
+
+// DeregisterObserver deregisters an observer.
+func (r *Raft) DeregisterObserver(or *Observer) {
+ r.observersLock.Lock()
+ defer r.observersLock.Unlock()
+ delete(r.observers, or.id)
+}
+
+// observe sends an observation to every observer.
+func (r *Raft) observe(o interface{}) {
+ // In general observers should not block. But in any case this isn't
+ // disastrous as we only hold a read lock, which merely prevents
+ // registration / deregistration of observers.
+ r.observersLock.RLock()
+ defer r.observersLock.RUnlock()
+ for _, or := range r.observers {
+ // It's wasteful to do this in the loop, but for the common case
+ // where there are no observers we won't create any objects.
+ ob := Observation{Raft: r, Data: o}
+ if or.filter != nil && !or.filter(&ob) {
+ continue
+ }
+ if or.channel == nil {
+ continue
+ }
+ if or.blocking {
+ or.channel <- ob
+ atomic.AddUint64(&or.numObserved, 1)
+ } else {
+ select {
+ case or.channel <- ob:
+ atomic.AddUint64(&or.numObserved, 1)
+ default:
+ atomic.AddUint64(&or.numDropped, 1)
+ }
+ }
+ }
+}
diff -Naur --color b/vendor/github.com/hashicorp/raft/peersjson.go a/vendor/github.com/hashicorp/raft/peersjson.go
--- b/vendor/github.com/hashicorp/raft/peersjson.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/peersjson.go 2022-11-15 23:06:31.565391195 +0100
@@ -0,0 +1,98 @@
+package raft
+
+import (
+ "bytes"
+ "encoding/json"
+ "io/ioutil"
+)
+
+// ReadPeersJSON consumes a legacy peers.json file in the format of the old JSON
+// peer store and creates a new-style configuration structure. This can be used
+// to migrate this data or perform manual recovery when running protocol versions
+// that can interoperate with older, unversioned Raft servers. This should not be
+// used once server IDs are in use, because the old peers.json file didn't have
+// support for these, nor non-voter suffrage types.
+func ReadPeersJSON(path string) (Configuration, error) {
+ // Read in the file.
+ buf, err := ioutil.ReadFile(path)
+ if err != nil {
+ return Configuration{}, err
+ }
+
+ // Parse it as JSON.
+ var peers []string
+ dec := json.NewDecoder(bytes.NewReader(buf))
+ if err := dec.Decode(&peers); err != nil {
+ return Configuration{}, err
+ }
+
+ // Map it into the new-style configuration structure. We can only specify
+ // voter roles here, and the ID has to be the same as the address.
+ var configuration Configuration
+ for _, peer := range peers {
+ server := Server{
+ Suffrage: Voter,
+ ID: ServerID(peer),
+ Address: ServerAddress(peer),
+ }
+ configuration.Servers = append(configuration.Servers, server)
+ }
+
+ // We should only ingest valid configurations.
+ if err := checkConfiguration(configuration); err != nil {
+ return Configuration{}, err
+ }
+ return configuration, nil
+}
+
+// configEntry is used when decoding a new-style peers.json.
+type configEntry struct {
+ // ID is the ID of the server (a UUID, usually).
+ ID ServerID `json:"id"`
+
+ // Address is the host:port of the server.
+ Address ServerAddress `json:"address"`
+
+ // NonVoter controls the suffrage. We choose this sense so people
+ // can leave this out and get a Voter by default.
+ NonVoter bool `json:"non_voter"`
+}
+
+// ReadConfigJSON reads a new-style peers.json and returns a configuration
+// structure. This can be used to perform manual recovery when running protocol
+// versions that use server IDs.
+func ReadConfigJSON(path string) (Configuration, error) {
+ // Read in the file.
+ buf, err := ioutil.ReadFile(path)
+ if err != nil {
+ return Configuration{}, err
+ }
+
+ // Parse it as JSON.
+ var peers []configEntry
+ dec := json.NewDecoder(bytes.NewReader(buf))
+ if err := dec.Decode(&peers); err != nil {
+ return Configuration{}, err
+ }
+
+ // Map it into the new-style configuration structure.
+ var configuration Configuration
+ for _, peer := range peers {
+ suffrage := Voter
+ if peer.NonVoter {
+ suffrage = Nonvoter
+ }
+ server := Server{
+ Suffrage: suffrage,
+ ID: peer.ID,
+ Address: peer.Address,
+ }
+ configuration.Servers = append(configuration.Servers, server)
+ }
+
+ // We should only ingest valid configurations.
+ if err := checkConfiguration(configuration); err != nil {
+ return Configuration{}, err
+ }
+ return configuration, nil
+}
diff -Naur --color b/vendor/github.com/hashicorp/raft/raft.go a/vendor/github.com/hashicorp/raft/raft.go
--- b/vendor/github.com/hashicorp/raft/raft.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/raft.go 2022-11-15 23:06:31.565391195 +0100
@@ -0,0 +1,1755 @@
+package raft
+
+import (
+ "bytes"
+ "container/list"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "sync/atomic"
+ "time"
+
+ "github.com/armon/go-metrics"
+)
+
+const (
+ minCheckInterval = 10 * time.Millisecond
+)
+
+var (
+ keyCurrentTerm = []byte("CurrentTerm")
+ keyLastVoteTerm = []byte("LastVoteTerm")
+ keyLastVoteCand = []byte("LastVoteCand")
+)
+
+// getRPCHeader returns an initialized RPCHeader struct for the given
+// Raft instance. This structure is sent along with RPC requests and
+// responses.
+func (r *Raft) getRPCHeader() RPCHeader {
+ return RPCHeader{
+ ProtocolVersion: r.conf.ProtocolVersion,
+ }
+}
+
+// checkRPCHeader houses logic about whether this instance of Raft can process
+// the given RPC message.
+func (r *Raft) checkRPCHeader(rpc RPC) error {
+ // Get the header off the RPC message.
+ wh, ok := rpc.Command.(WithRPCHeader)
+ if !ok {
+ return fmt.Errorf("RPC does not have a header")
+ }
+ header := wh.GetRPCHeader()
+
+ // First check is to just make sure the code can understand the
+ // protocol at all.
+ if header.ProtocolVersion < ProtocolVersionMin ||
+ header.ProtocolVersion > ProtocolVersionMax {
+ return ErrUnsupportedProtocol
+ }
+
+ // Second check is whether we should support this message, given the
+ // current protocol we are configured to run. This will drop support
+ // for protocol version 0 starting at protocol version 2, which is
+ // currently what we want, and in general support one version back. We
+ // may need to revisit this policy depending on how future protocol
+ // changes evolve.
+ if header.ProtocolVersion < r.conf.ProtocolVersion-1 {
+ return ErrUnsupportedProtocol
+ }
+
+ return nil
+}
+
+// getSnapshotVersion returns the snapshot version that should be used when
+// creating snapshots, given the protocol version in use.
+func getSnapshotVersion(protocolVersion ProtocolVersion) SnapshotVersion {
+ // Right now we only have two versions and they are backwards compatible
+ // so we don't need to look at the protocol version.
+ return 1
+}
+
+// commitTuple is used to send an index that was committed,
+// with an optional associated future that should be invoked.
+type commitTuple struct {
+ log *Log
+ future *logFuture
+}
+
+// leaderState is state that is used while we are a leader.
+type leaderState struct {
+ leadershipTransferInProgress int32 // indicates that a leadership transfer is in progress.
+ commitCh chan struct{}
+ commitment *commitment
+ inflight *list.List // list of logFuture in log index order
+ replState map[ServerID]*followerReplication
+ notify map[*verifyFuture]struct{}
+ stepDown chan struct{}
+}
+
+// setLeader is used to modify the current leader of the cluster
+func (r *Raft) setLeader(leader ServerAddress) {
+ r.leaderLock.Lock()
+ oldLeader := r.leader
+ r.leader = leader
+ r.leaderLock.Unlock()
+ if oldLeader != leader {
+ r.observe(LeaderObservation{leader: leader})
+ }
+}
+
+// requestConfigChange is a helper for the above functions that make
+// configuration change requests. 'req' describes the change. For timeout,
+// see AddVoter.
+func (r *Raft) requestConfigChange(req configurationChangeRequest, timeout time.Duration) IndexFuture {
+ var timer <-chan time.Time
+ if timeout > 0 {
+ timer = time.After(timeout)
+ }
+ future := &configurationChangeFuture{
+ req: req,
+ }
+ future.init()
+ select {
+ case <-timer:
+ return errorFuture{ErrEnqueueTimeout}
+ case r.configurationChangeCh <- future:
+ return future
+ case <-r.shutdownCh:
+ return errorFuture{ErrRaftShutdown}
+ }
+}
+
+// run is a long running goroutine that runs the Raft FSM.
+func (r *Raft) run() {
+ for {
+ // Check if we are doing a shutdown
+ select {
+ case <-r.shutdownCh:
+ // Clear the leader to prevent forwarding
+ r.setLeader("")
+ return
+ default:
+ }
+
+ // Enter into a sub-FSM
+ switch r.getState() {
+ case Follower:
+ r.runFollower()
+ case Candidate:
+ r.runCandidate()
+ case Leader:
+ r.runLeader()
+ }
+ }
+}
+
+// runFollower runs the FSM for a follower.
+func (r *Raft) runFollower() {
+ didWarn := false
+ r.logger.Info(fmt.Sprintf("%v entering Follower state (Leader: %q)", r, r.Leader()))
+ metrics.IncrCounter([]string{"raft", "state", "follower"}, 1)
+ heartbeatTimer := randomTimeout(r.conf.HeartbeatTimeout)
+
+ for r.getState() == Follower {
+ select {
+ case rpc := <-r.rpcCh:
+ r.processRPC(rpc)
+
+ case c := <-r.configurationChangeCh:
+ // Reject any operations since we are not the leader
+ c.respond(ErrNotLeader)
+
+ case a := <-r.applyCh:
+ // Reject any operations since we are not the leader
+ a.respond(ErrNotLeader)
+
+ case v := <-r.verifyCh:
+ // Reject any operations since we are not the leader
+ v.respond(ErrNotLeader)
+
+ case r := <-r.userRestoreCh:
+ // Reject any restores since we are not the leader
+ r.respond(ErrNotLeader)
+
+ case r := <-r.leadershipTransferCh:
+ // Reject any operations since we are not the leader
+ r.respond(ErrNotLeader)
+
+ case c := <-r.configurationsCh:
+ c.configurations = r.configurations.Clone()
+ c.respond(nil)
+
+ case b := <-r.bootstrapCh:
+ b.respond(r.liveBootstrap(b.configuration))
+
+ case <-heartbeatTimer:
+ // Restart the heartbeat timer
+ heartbeatTimer = randomTimeout(r.conf.HeartbeatTimeout)
+
+ // Check if we have had a successful contact
+ lastContact := r.LastContact()
+ if time.Now().Sub(lastContact) < r.conf.HeartbeatTimeout {
+ continue
+ }
+
+ // Heartbeat failed! Transition to the candidate state
+ lastLeader := r.Leader()
+ r.setLeader("")
+
+ if r.configurations.latestIndex == 0 {
+ if !didWarn {
+ r.logger.Warn("no known peers, aborting election")
+ didWarn = true
+ }
+ } else if r.configurations.latestIndex == r.configurations.committedIndex &&
+ !hasVote(r.configurations.latest, r.localID) {
+ if !didWarn {
+ r.logger.Warn("not part of stable configuration, aborting election")
+ didWarn = true
+ }
+ } else {
+ r.logger.Warn(fmt.Sprintf("Heartbeat timeout from %q reached, starting election", lastLeader))
+ metrics.IncrCounter([]string{"raft", "transition", "heartbeat_timeout"}, 1)
+ r.setState(Candidate)
+ return
+ }
+
+ case <-r.shutdownCh:
+ return
+ }
+ }
+}
+
+// liveBootstrap attempts to seed an initial configuration for the cluster. See
+// the Raft object's member BootstrapCluster for more details. This must only be
+// called on the main thread, and only makes sense in the follower state.
+func (r *Raft) liveBootstrap(configuration Configuration) error {
+ // Use the pre-init API to make the static updates.
+ err := BootstrapCluster(&r.conf, r.logs, r.stable, r.snapshots,
+ r.trans, configuration)
+ if err != nil {
+ return err
+ }
+
+ // Make the configuration live.
+ var entry Log
+ if err := r.logs.GetLog(1, &entry); err != nil {
+ panic(err)
+ }
+ r.setCurrentTerm(1)
+ r.setLastLog(entry.Index, entry.Term)
+ r.processConfigurationLogEntry(&entry)
+ return nil
+}
+
+// runCandidate runs the FSM for a candidate.
+func (r *Raft) runCandidate() {
+ r.logger.Info(fmt.Sprintf("%v entering Candidate state in term %v", r, r.getCurrentTerm()+1))
+ metrics.IncrCounter([]string{"raft", "state", "candidate"}, 1)
+
+ // Start vote for us, and set a timeout
+ voteCh := r.electSelf()
+
+ // Make sure the leadership transfer flag is reset after each run. Having this
+ // flag will set the field LeadershipTransfer in a RequestVoteRequst to true,
+ // which will make other servers vote even though they have a leader already.
+ // It is important to reset that flag, because this priviledge could be abused
+ // otherwise.
+ defer func() { r.candidateFromLeadershipTransfer = false }()
+
+ electionTimer := randomTimeout(r.conf.ElectionTimeout)
+
+ // Tally the votes, need a simple majority
+ grantedVotes := 0
+ votesNeeded := r.quorumSize()
+ r.logger.Debug(fmt.Sprintf("Votes needed: %d", votesNeeded))
+
+ for r.getState() == Candidate {
+ select {
+ case rpc := <-r.rpcCh:
+ r.processRPC(rpc)
+
+ case vote := <-voteCh:
+ // Check if the term is greater than ours, bail
+ if vote.Term > r.getCurrentTerm() {
+ r.logger.Debug("Newer term discovered, fallback to follower")
+ r.setState(Follower)
+ r.setCurrentTerm(vote.Term)
+ return
+ }
+
+ // Check if the vote is granted
+ if vote.Granted {
+ grantedVotes++
+ r.logger.Debug(fmt.Sprintf("Vote granted from %s in term %v. Tally: %d",
+ vote.voterID, vote.Term, grantedVotes))
+ }
+
+ // Check if we've become the leader
+ if grantedVotes >= votesNeeded {
+ r.logger.Info(fmt.Sprintf("Election won. Tally: %d", grantedVotes))
+ r.setState(Leader)
+ r.setLeader(r.localAddr)
+ return
+ }
+
+ case c := <-r.configurationChangeCh:
+ // Reject any operations since we are not the leader
+ c.respond(ErrNotLeader)
+
+ case a := <-r.applyCh:
+ // Reject any operations since we are not the leader
+ a.respond(ErrNotLeader)
+
+ case v := <-r.verifyCh:
+ // Reject any operations since we are not the leader
+ v.respond(ErrNotLeader)
+
+ case r := <-r.userRestoreCh:
+ // Reject any restores since we are not the leader
+ r.respond(ErrNotLeader)
+
+ case c := <-r.configurationsCh:
+ c.configurations = r.configurations.Clone()
+ c.respond(nil)
+
+ case b := <-r.bootstrapCh:
+ b.respond(ErrCantBootstrap)
+
+ case <-electionTimer:
+ // Election failed! Restart the election. We simply return,
+ // which will kick us back into runCandidate
+ r.logger.Warn("Election timeout reached, restarting election")
+ return
+
+ case <-r.shutdownCh:
+ return
+ }
+ }
+}
+
+func (r *Raft) setLeadershipTransferInProgress(v bool) {
+ if v {
+ atomic.StoreInt32(&r.leaderState.leadershipTransferInProgress, 1)
+ } else {
+ atomic.StoreInt32(&r.leaderState.leadershipTransferInProgress, 0)
+ }
+}
+
+func (r *Raft) getLeadershipTransferInProgress() bool {
+ v := atomic.LoadInt32(&r.leaderState.leadershipTransferInProgress)
+ if v == 1 {
+ return true
+ }
+ return false
+}
+
+func (r *Raft) setupLeaderState() {
+ r.leaderState.commitCh = make(chan struct{}, 1)
+ r.leaderState.commitment = newCommitment(r.leaderState.commitCh,
+ r.configurations.latest,
+ r.getLastIndex()+1 /* first index that may be committed in this term */)
+ r.leaderState.inflight = list.New()
+ r.leaderState.replState = make(map[ServerID]*followerReplication)
+ r.leaderState.notify = make(map[*verifyFuture]struct{})
+ r.leaderState.stepDown = make(chan struct{}, 1)
+}
+
+// runLeader runs the FSM for a leader. Do the setup here and drop into
+// the leaderLoop for the hot loop.
+func (r *Raft) runLeader() {
+ r.logger.Info(fmt.Sprintf("%v entering Leader state", r))
+ metrics.IncrCounter([]string{"raft", "state", "leader"}, 1)
+
+ // Notify that we are the leader
+ asyncNotifyBool(r.leaderCh, true)
+
+ // Push to the notify channel if given
+ if notify := r.conf.NotifyCh; notify != nil {
+ select {
+ case notify <- true:
+ case <-r.shutdownCh:
+ }
+ }
+
+ // setup leader state. This is only supposed to be accessed within the
+ // leaderloop.
+ r.setupLeaderState()
+
+ // Cleanup state on step down
+ defer func() {
+ // Since we were the leader previously, we update our
+ // last contact time when we step down, so that we are not
+ // reporting a last contact time from before we were the
+ // leader. Otherwise, to a client it would seem our data
+ // is extremely stale.
+ r.setLastContact()
+
+ // Stop replication
+ for _, p := range r.leaderState.replState {
+ close(p.stopCh)
+ }
+
+ // Respond to all inflight operations
+ for e := r.leaderState.inflight.Front(); e != nil; e = e.Next() {
+ e.Value.(*logFuture).respond(ErrLeadershipLost)
+ }
+
+ // Respond to any pending verify requests
+ for future := range r.leaderState.notify {
+ future.respond(ErrLeadershipLost)
+ }
+
+ // Clear all the state
+ r.leaderState.commitCh = nil
+ r.leaderState.commitment = nil
+ r.leaderState.inflight = nil
+ r.leaderState.replState = nil
+ r.leaderState.notify = nil
+ r.leaderState.stepDown = nil
+
+ // If we are stepping down for some reason, no known leader.
+ // We may have stepped down due to an RPC call, which would
+ // provide the leader, so we cannot always blank this out.
+ r.leaderLock.Lock()
+ if r.leader == r.localAddr {
+ r.leader = ""
+ }
+ r.leaderLock.Unlock()
+
+ // Notify that we are not the leader
+ asyncNotifyBool(r.leaderCh, false)
+
+ // Push to the notify channel if given
+ if notify := r.conf.NotifyCh; notify != nil {
+ select {
+ case notify <- false:
+ case <-r.shutdownCh:
+ // On shutdown, make a best effort but do not block
+ select {
+ case notify <- false:
+ default:
+ }
+ }
+ }
+ }()
+
+ // Start a replication routine for each peer
+ r.startStopReplication()
+
+ // Dispatch a no-op log entry first. This gets this leader up to the latest
+ // possible commit index, even in the absence of client commands. This used
+ // to append a configuration entry instead of a noop. However, that permits
+ // an unbounded number of uncommitted configurations in the log. We now
+ // maintain that there exists at most one uncommitted configuration entry in
+ // any log, so we have to do proper no-ops here.
+ noop := &logFuture{
+ log: Log{
+ Type: LogNoop,
+ },
+ }
+ r.dispatchLogs([]*logFuture{noop})
+
+ // Sit in the leader loop until we step down
+ r.leaderLoop()
+}
+
+// startStopReplication will set up state and start asynchronous replication to
+// new peers, and stop replication to removed peers. Before removing a peer,
+// it'll instruct the replication routines to try to replicate to the current
+// index. This must only be called from the main thread.
+func (r *Raft) startStopReplication() {
+ inConfig := make(map[ServerID]bool, len(r.configurations.latest.Servers))
+ lastIdx := r.getLastIndex()
+
+ // Start replication goroutines that need starting
+ for _, server := range r.configurations.latest.Servers {
+ if server.ID == r.localID {
+ continue
+ }
+ inConfig[server.ID] = true
+ if _, ok := r.leaderState.replState[server.ID]; !ok {
+ r.logger.Info(fmt.Sprintf("Added peer %v, starting replication", server.ID))
+ s := &followerReplication{
+ peer: server,
+ commitment: r.leaderState.commitment,
+ stopCh: make(chan uint64, 1),
+ triggerCh: make(chan struct{}, 1),
+ triggerDeferErrorCh: make(chan *deferError, 1),
+ currentTerm: r.getCurrentTerm(),
+ nextIndex: lastIdx + 1,
+ lastContact: time.Now(),
+ notify: make(map[*verifyFuture]struct{}),
+ notifyCh: make(chan struct{}, 1),
+ stepDown: r.leaderState.stepDown,
+ }
+ r.leaderState.replState[server.ID] = s
+ r.goFunc(func() { r.replicate(s) })
+ asyncNotifyCh(s.triggerCh)
+ r.observe(PeerObservation{Peer: server, Removed: false})
+ }
+ }
+
+ // Stop replication goroutines that need stopping
+ for serverID, repl := range r.leaderState.replState {
+ if inConfig[serverID] {
+ continue
+ }
+ // Replicate up to lastIdx and stop
+ r.logger.Info(fmt.Sprintf("Removed peer %v, stopping replication after %v", serverID, lastIdx))
+ repl.stopCh <- lastIdx
+ close(repl.stopCh)
+ delete(r.leaderState.replState, serverID)
+ r.observe(PeerObservation{Peer: repl.peer, Removed: true})
+ }
+}
+
+// configurationChangeChIfStable returns r.configurationChangeCh if it's safe
+// to process requests from it, or nil otherwise. This must only be called
+// from the main thread.
+//
+// Note that if the conditions here were to change outside of leaderLoop to take
+// this from nil to non-nil, we would need leaderLoop to be kicked.
+func (r *Raft) configurationChangeChIfStable() chan *configurationChangeFuture {
+ // Have to wait until:
+ // 1. The latest configuration is committed, and
+ // 2. This leader has committed some entry (the noop) in this term
+ // https://groups.google.com/forum/#!msg/raft-dev/t4xj6dJTP6E/d2D9LrWRza8J
+ if r.configurations.latestIndex == r.configurations.committedIndex &&
+ r.getCommitIndex() >= r.leaderState.commitment.startIndex {
+ return r.configurationChangeCh
+ }
+ return nil
+}
+
+// leaderLoop is the hot loop for a leader. It is invoked
+// after all the various leader setup is done.
+func (r *Raft) leaderLoop() {
+ // stepDown is used to track if there is an inflight log that
+ // would cause us to lose leadership (specifically a RemovePeer of
+ // ourselves). If this is the case, we must not allow any logs to
+ // be processed in parallel, otherwise we are basing commit on
+ // only a single peer (ourself) and replicating to an undefined set
+ // of peers.
+ stepDown := false
+ lease := time.After(r.conf.LeaderLeaseTimeout)
+
+ for r.getState() == Leader {
+ select {
+ case rpc := <-r.rpcCh:
+ r.processRPC(rpc)
+
+ case <-r.leaderState.stepDown:
+ r.setState(Follower)
+
+ case future := <-r.leadershipTransferCh:
+ if r.getLeadershipTransferInProgress() {
+ r.logger.Debug(ErrLeadershipTransferInProgress.Error())
+ future.respond(ErrLeadershipTransferInProgress)
+ continue
+ }
+
+ r.logger.Debug("starting leadership transfer", "id", future.ID, "address", future.Address)
+
+ // When we are leaving leaderLoop, we are no longer
+ // leader, so we should stop transferring.
+ leftLeaderLoop := make(chan struct{})
+ defer func() { close(leftLeaderLoop) }()
+
+ stopCh := make(chan struct{})
+ doneCh := make(chan error, 1)
+
+ // This is intentionally being setup outside of the
+ // leadershipTransfer function. Because the TimeoutNow
+ // call is blocking and there is no way to abort that
+ // in case eg the timer expires.
+ // The leadershipTransfer function is controlled with
+ // the stopCh and doneCh.
+ go func() {
+ select {
+ case <-time.After(r.conf.ElectionTimeout):
+ close(stopCh)
+ err := fmt.Errorf("leadership transfer timeout")
+ r.logger.Debug(err.Error())
+ future.respond(err)
+ <-doneCh
+ case <-leftLeaderLoop:
+ close(stopCh)
+ err := fmt.Errorf("lost leadership during transfer (expected)")
+ r.logger.Debug(err.Error())
+ future.respond(nil)
+ <-doneCh
+ case err := <-doneCh:
+ if err != nil {
+ r.logger.Debug(err.Error())
+ }
+ future.respond(err)
+ }
+ }()
+
+ // leaderState.replState is accessed here before
+ // starting leadership transfer asynchronously because
+ // leaderState is only supposed to be accessed in the
+ // leaderloop.
+ id := future.ID
+ address := future.Address
+ if id == nil {
+ s := r.pickServer()
+ if s != nil {
+ id = &s.ID
+ address = &s.Address
+ } else {
+ doneCh <- fmt.Errorf("cannot find peer")
+ continue
+ }
+ }
+ state, ok := r.leaderState.replState[*id]
+ if !ok {
+ doneCh <- fmt.Errorf("cannot find replication state for %v", id)
+ continue
+ }
+
+ go r.leadershipTransfer(*id, *address, state, stopCh, doneCh)
+
+ case <-r.leaderState.commitCh:
+ // Process the newly committed entries
+ oldCommitIndex := r.getCommitIndex()
+ commitIndex := r.leaderState.commitment.getCommitIndex()
+ r.setCommitIndex(commitIndex)
+
+ if r.configurations.latestIndex > oldCommitIndex &&
+ r.configurations.latestIndex <= commitIndex {
+ r.configurations.committed = r.configurations.latest
+ r.configurations.committedIndex = r.configurations.latestIndex
+ if !hasVote(r.configurations.committed, r.localID) {
+ stepDown = true
+ }
+ }
+
+ var numProcessed int
+ start := time.Now()
+
+ for {
+ e := r.leaderState.inflight.Front()
+ if e == nil {
+ break
+ }
+ commitLog := e.Value.(*logFuture)
+ idx := commitLog.log.Index
+ if idx > commitIndex {
+ break
+ }
+ // Measure the commit time
+ metrics.MeasureSince([]string{"raft", "commitTime"}, commitLog.dispatch)
+
+ r.processLogs(idx, commitLog)
+
+ r.leaderState.inflight.Remove(e)
+ numProcessed++
+ }
+
+ // Measure the time to enqueue batch of logs for FSM to apply
+ metrics.MeasureSince([]string{"raft", "fsm", "enqueue"}, start)
+
+ // Count the number of logs enqueued
+ metrics.SetGauge([]string{"raft", "commitNumLogs"}, float32(numProcessed))
+
+ if stepDown {
+ if r.conf.ShutdownOnRemove {
+ r.logger.Info("Removed ourself, shutting down")
+ r.Shutdown()
+ } else {
+ r.logger.Info("Removed ourself, transitioning to follower")
+ r.setState(Follower)
+ }
+ }
+
+ case v := <-r.verifyCh:
+ if v.quorumSize == 0 {
+ // Just dispatched, start the verification
+ r.verifyLeader(v)
+
+ } else if v.votes < v.quorumSize {
+ // Early return, means there must be a new leader
+ r.logger.Warn("New leader elected, stepping down")
+ r.setState(Follower)
+ delete(r.leaderState.notify, v)
+ for _, repl := range r.leaderState.replState {
+ repl.cleanNotify(v)
+ }
+ v.respond(ErrNotLeader)
+
+ } else {
+ // Quorum of members agree, we are still leader
+ delete(r.leaderState.notify, v)
+ for _, repl := range r.leaderState.replState {
+ repl.cleanNotify(v)
+ }
+ v.respond(nil)
+ }
+
+ case future := <-r.userRestoreCh:
+ if r.getLeadershipTransferInProgress() {
+ r.logger.Debug(ErrLeadershipTransferInProgress.Error())
+ future.respond(ErrLeadershipTransferInProgress)
+ continue
+ }
+ err := r.restoreUserSnapshot(future.meta, future.reader)
+ future.respond(err)
+
+ case future := <-r.configurationsCh:
+ if r.getLeadershipTransferInProgress() {
+ r.logger.Debug(ErrLeadershipTransferInProgress.Error())
+ future.respond(ErrLeadershipTransferInProgress)
+ continue
+ }
+ future.configurations = r.configurations.Clone()
+ future.respond(nil)
+
+ case future := <-r.configurationChangeChIfStable():
+ if r.getLeadershipTransferInProgress() {
+ r.logger.Debug(ErrLeadershipTransferInProgress.Error())
+ future.respond(ErrLeadershipTransferInProgress)
+ continue
+ }
+ r.appendConfigurationEntry(future)
+
+ case b := <-r.bootstrapCh:
+ b.respond(ErrCantBootstrap)
+
+ case newLog := <-r.applyCh:
+ if r.getLeadershipTransferInProgress() {
+ r.logger.Debug(ErrLeadershipTransferInProgress.Error())
+ newLog.respond(ErrLeadershipTransferInProgress)
+ continue
+ }
+ // Group commit, gather all the ready commits
+ ready := []*logFuture{newLog}
+ GROUP_COMMIT_LOOP:
+ for i := 0; i < r.conf.MaxAppendEntries; i++ {
+ select {
+ case newLog := <-r.applyCh:
+ ready = append(ready, newLog)
+ default:
+ break GROUP_COMMIT_LOOP
+ }
+ }
+
+ // Dispatch the logs
+ if stepDown {
+ // we're in the process of stepping down as leader, don't process anything new
+ for i := range ready {
+ ready[i].respond(ErrNotLeader)
+ }
+ } else {
+ r.dispatchLogs(ready)
+ }
+
+ case <-lease:
+ // Check if we've exceeded the lease, potentially stepping down
+ maxDiff := r.checkLeaderLease()
+
+ // Next check interval should adjust for the last node we've
+ // contacted, without going negative
+ checkInterval := r.conf.LeaderLeaseTimeout - maxDiff
+ if checkInterval < minCheckInterval {
+ checkInterval = minCheckInterval
+ }
+
+ // Renew the lease timer
+ lease = time.After(checkInterval)
+
+ case <-r.shutdownCh:
+ return
+ }
+ }
+}
+
+// verifyLeader must be called from the main thread for safety.
+// Causes the followers to attempt an immediate heartbeat.
+func (r *Raft) verifyLeader(v *verifyFuture) {
+ // Current leader always votes for self
+ v.votes = 1
+
+ // Set the quorum size, hot-path for single node
+ v.quorumSize = r.quorumSize()
+ if v.quorumSize == 1 {
+ v.respond(nil)
+ return
+ }
+
+ // Track this request
+ v.notifyCh = r.verifyCh
+ r.leaderState.notify[v] = struct{}{}
+
+ // Trigger immediate heartbeats
+ for _, repl := range r.leaderState.replState {
+ repl.notifyLock.Lock()
+ repl.notify[v] = struct{}{}
+ repl.notifyLock.Unlock()
+ asyncNotifyCh(repl.notifyCh)
+ }
+}
+
+// leadershipTransfer is doing the heavy lifting for the leadership transfer.
+func (r *Raft) leadershipTransfer(id ServerID, address ServerAddress, repl *followerReplication, stopCh chan struct{}, doneCh chan error) {
+
+ // make sure we are not already stopped
+ select {
+ case <-stopCh:
+ doneCh <- nil
+ return
+ default:
+ }
+
+ // Step 1: set this field which stops this leader from responding to any client requests.
+ r.setLeadershipTransferInProgress(true)
+ defer func() { r.setLeadershipTransferInProgress(false) }()
+
+ for atomic.LoadUint64(&repl.nextIndex) <= r.getLastIndex() {
+ err := &deferError{}
+ err.init()
+ repl.triggerDeferErrorCh <- err
+ select {
+ case err := <-err.errCh:
+ if err != nil {
+ doneCh <- err
+ return
+ }
+ case <-stopCh:
+ doneCh <- nil
+ return
+ }
+ }
+
+ // Step ?: the thesis describes in chap 6.4.1: Using clocks to reduce
+ // messaging for read-only queries. If this is implemented, the lease
+ // has to be reset as well, in case leadership is transferred. This
+ // implementation also has a lease, but it serves another purpose and
+ // doesn't need to be reset. The lease mechanism in our raft lib, is
+ // setup in a similar way to the one in the thesis, but in practice
+ // it's a timer that just tells the leader how often to check
+ // heartbeats are still coming in.
+
+ // Step 3: send TimeoutNow message to target server.
+ err := r.trans.TimeoutNow(id, address, &TimeoutNowRequest{RPCHeader: r.getRPCHeader()}, &TimeoutNowResponse{})
+ if err != nil {
+ err = fmt.Errorf("failed to make TimeoutNow RPC to %v: %v", id, err)
+ }
+ doneCh <- err
+}
+
+// checkLeaderLease is used to check if we can contact a quorum of nodes
+// within the last leader lease interval. If not, we need to step down,
+// as we may have lost connectivity. Returns the maximum duration without
+// contact. This must only be called from the main thread.
+func (r *Raft) checkLeaderLease() time.Duration {
+ // Track contacted nodes, we can always contact ourself
+ contacted := 0
+
+ // Check each follower
+ var maxDiff time.Duration
+ now := time.Now()
+ for _, server := range r.configurations.latest.Servers {
+ if server.Suffrage == Voter {
+ if server.ID == r.localID {
+ contacted++
+ continue
+ }
+ f := r.leaderState.replState[server.ID]
+ diff := now.Sub(f.LastContact())
+ if diff <= r.conf.LeaderLeaseTimeout {
+ contacted++
+ if diff > maxDiff {
+ maxDiff = diff
+ }
+ } else {
+ // Log at least once at high value, then debug. Otherwise it gets very verbose.
+ if diff <= 3*r.conf.LeaderLeaseTimeout {
+ r.logger.Warn(fmt.Sprintf("Failed to contact %v in %v", server.ID, diff))
+ } else {
+ r.logger.Debug(fmt.Sprintf("Failed to contact %v in %v", server.ID, diff))
+ }
+ }
+ metrics.AddSample([]string{"raft", "leader", "lastContact"}, float32(diff/time.Millisecond))
+ }
+ }
+
+ // Verify we can contact a quorum
+ quorum := r.quorumSize()
+ if contacted < quorum {
+ r.logger.Warn("Failed to contact quorum of nodes, stepping down")
+ r.setState(Follower)
+ metrics.IncrCounter([]string{"raft", "transition", "leader_lease_timeout"}, 1)
+ }
+ return maxDiff
+}
+
+// quorumSize is used to return the quorum size. This must only be called on
+// the main thread.
+// TODO: revisit usage
+func (r *Raft) quorumSize() int {
+ voters := 0
+ for _, server := range r.configurations.latest.Servers {
+ if server.Suffrage == Voter {
+ voters++
+ }
+ }
+ return voters/2 + 1
+}
+
+// restoreUserSnapshot is used to manually consume an external snapshot, such
+// as if restoring from a backup. We will use the current Raft configuration,
+// not the one from the snapshot, so that we can restore into a new cluster. We
+// will also use the higher of the index of the snapshot, or the current index,
+// and then add 1 to that, so we force a new state with a hole in the Raft log,
+// so that the snapshot will be sent to followers and used for any new joiners.
+// This can only be run on the leader, and returns a future that can be used to
+// block until complete.
+func (r *Raft) restoreUserSnapshot(meta *SnapshotMeta, reader io.Reader) error {
+ defer metrics.MeasureSince([]string{"raft", "restoreUserSnapshot"}, time.Now())
+
+ // Sanity check the version.
+ version := meta.Version
+ if version < SnapshotVersionMin || version > SnapshotVersionMax {
+ return fmt.Errorf("unsupported snapshot version %d", version)
+ }
+
+ // We don't support snapshots while there's a config change
+ // outstanding since the snapshot doesn't have a means to
+ // represent this state.
+ committedIndex := r.configurations.committedIndex
+ latestIndex := r.configurations.latestIndex
+ if committedIndex != latestIndex {
+ return fmt.Errorf("cannot restore snapshot now, wait until the configuration entry at %v has been applied (have applied %v)",
+ latestIndex, committedIndex)
+ }
+
+ // Cancel any inflight requests.
+ for {
+ e := r.leaderState.inflight.Front()
+ if e == nil {
+ break
+ }
+ e.Value.(*logFuture).respond(ErrAbortedByRestore)
+ r.leaderState.inflight.Remove(e)
+ }
+
+ // We will overwrite the snapshot metadata with the current term,
+ // an index that's greater than the current index, or the last
+ // index in the snapshot. It's important that we leave a hole in
+ // the index so we know there's nothing in the Raft log there and
+ // replication will fault and send the snapshot.
+ term := r.getCurrentTerm()
+ lastIndex := r.getLastIndex()
+ if meta.Index > lastIndex {
+ lastIndex = meta.Index
+ }
+ lastIndex++
+
+ // Dump the snapshot. Note that we use the latest configuration,
+ // not the one that came with the snapshot.
+ sink, err := r.snapshots.Create(version, lastIndex, term,
+ r.configurations.latest, r.configurations.latestIndex, r.trans)
+ if err != nil {
+ return fmt.Errorf("failed to create snapshot: %v", err)
+ }
+ n, err := io.Copy(sink, reader)
+ if err != nil {
+ sink.Cancel()
+ return fmt.Errorf("failed to write snapshot: %v", err)
+ }
+ if n != meta.Size {
+ sink.Cancel()
+ return fmt.Errorf("failed to write snapshot, size didn't match (%d != %d)", n, meta.Size)
+ }
+ if err := sink.Close(); err != nil {
+ return fmt.Errorf("failed to close snapshot: %v", err)
+ }
+ r.logger.Info(fmt.Sprintf("Copied %d bytes to local snapshot", n))
+
+ // Restore the snapshot into the FSM. If this fails we are in a
+ // bad state so we panic to take ourselves out.
+ fsm := &restoreFuture{ID: sink.ID()}
+ fsm.init()
+ select {
+ case r.fsmMutateCh <- fsm:
+ case <-r.shutdownCh:
+ return ErrRaftShutdown
+ }
+ if err := fsm.Error(); err != nil {
+ panic(fmt.Errorf("failed to restore snapshot: %v", err))
+ }
+
+ // We set the last log so it looks like we've stored the empty
+ // index we burned. The last applied is set because we made the
+ // FSM take the snapshot state, and we store the last snapshot
+ // in the stable store since we created a snapshot as part of
+ // this process.
+ r.setLastLog(lastIndex, term)
+ r.setLastApplied(lastIndex)
+ r.setLastSnapshot(lastIndex, term)
+
+ r.logger.Info(fmt.Sprintf("Restored user snapshot (index %d)", lastIndex))
+ return nil
+}
+
+// appendConfigurationEntry changes the configuration and adds a new
+// configuration entry to the log. This must only be called from the
+// main thread.
+func (r *Raft) appendConfigurationEntry(future *configurationChangeFuture) {
+ configuration, err := nextConfiguration(r.configurations.latest, r.configurations.latestIndex, future.req)
+ if err != nil {
+ future.respond(err)
+ return
+ }
+
+ r.logger.Info(fmt.Sprintf("Updating configuration with %s (%v, %v) to %+v",
+ future.req.command, future.req.serverID, future.req.serverAddress, configuration.Servers))
+
+ // In pre-ID compatibility mode we translate all configuration changes
+ // in to an old remove peer message, which can handle all supported
+ // cases for peer changes in the pre-ID world (adding and removing
+ // voters). Both add peer and remove peer log entries are handled
+ // similarly on old Raft servers, but remove peer does extra checks to
+ // see if a leader needs to step down. Since they both assert the full
+ // configuration, then we can safely call remove peer for everything.
+ if r.protocolVersion < 2 {
+ future.log = Log{
+ Type: LogRemovePeerDeprecated,
+ Data: encodePeers(configuration, r.trans),
+ }
+ } else {
+ future.log = Log{
+ Type: LogConfiguration,
+ Data: encodeConfiguration(configuration),
+ }
+ }
+
+ r.dispatchLogs([]*logFuture{&future.logFuture})
+ index := future.Index()
+ r.configurations.latest = configuration
+ r.configurations.latestIndex = index
+ r.leaderState.commitment.setConfiguration(configuration)
+ r.startStopReplication()
+}
+
+// dispatchLog is called on the leader to push a log to disk, mark it
+// as inflight and begin replication of it.
+func (r *Raft) dispatchLogs(applyLogs []*logFuture) {
+ now := time.Now()
+ defer metrics.MeasureSince([]string{"raft", "leader", "dispatchLog"}, now)
+
+ term := r.getCurrentTerm()
+ lastIndex := r.getLastIndex()
+
+ n := len(applyLogs)
+ logs := make([]*Log, n)
+ metrics.SetGauge([]string{"raft", "leader", "dispatchNumLogs"}, float32(n))
+
+ for idx, applyLog := range applyLogs {
+ applyLog.dispatch = now
+ lastIndex++
+ applyLog.log.Index = lastIndex
+ applyLog.log.Term = term
+ logs[idx] = &applyLog.log
+ r.leaderState.inflight.PushBack(applyLog)
+ }
+
+ // Write the log entry locally
+ if err := r.logs.StoreLogs(logs); err != nil {
+ r.logger.Error(fmt.Sprintf("Failed to commit logs: %v", err))
+ for _, applyLog := range applyLogs {
+ applyLog.respond(err)
+ }
+ r.setState(Follower)
+ return
+ }
+ r.leaderState.commitment.match(r.localID, lastIndex)
+
+ // Update the last log since it's on disk now
+ r.setLastLog(lastIndex, term)
+
+ // Notify the replicators of the new log
+ for _, f := range r.leaderState.replState {
+ asyncNotifyCh(f.triggerCh)
+ }
+}
+
+// processLogs is used to apply all the committed entries that haven't been
+// applied up to the given index limit.
+// This can be called from both leaders and followers.
+// Followers call this from AppendEntries, for n entries at a time, and always
+// pass future=nil.
+// Leaders call this once per inflight when entries are committed. They pass
+// the future from inflights.
+func (r *Raft) processLogs(index uint64, future *logFuture) {
+ // Reject logs we've applied already
+ lastApplied := r.getLastApplied()
+ if index <= lastApplied {
+ r.logger.Warn(fmt.Sprintf("Skipping application of old log: %d", index))
+ return
+ }
+
+ // Apply all the preceding logs
+ for idx := r.getLastApplied() + 1; idx <= index; idx++ {
+ // Get the log, either from the future or from our log store
+ if future != nil && future.log.Index == idx {
+ r.processLog(&future.log, future)
+ } else {
+ l := new(Log)
+ if err := r.logs.GetLog(idx, l); err != nil {
+ r.logger.Error(fmt.Sprintf("Failed to get log at %d: %v", idx, err))
+ panic(err)
+ }
+ r.processLog(l, nil)
+ }
+
+ // Update the lastApplied index and term
+ r.setLastApplied(idx)
+ }
+}
+
+// processLog is invoked to process the application of a single committed log entry.
+func (r *Raft) processLog(l *Log, future *logFuture) {
+ switch l.Type {
+ case LogBarrier:
+ // Barrier is handled by the FSM
+ fallthrough
+
+ case LogCommand:
+ // Forward to the fsm handler
+ select {
+ case r.fsmMutateCh <- &commitTuple{l, future}:
+ case <-r.shutdownCh:
+ if future != nil {
+ future.respond(ErrRaftShutdown)
+ }
+ }
+
+ // Return so that the future is only responded to
+ // by the FSM handler when the application is done
+ return
+
+ case LogConfiguration:
+ // Only support this with the v2 configuration format
+ if r.protocolVersion > 2 {
+ // Forward to the fsm handler
+ select {
+ case r.fsmMutateCh <- &commitTuple{l, future}:
+ case <-r.shutdownCh:
+ if future != nil {
+ future.respond(ErrRaftShutdown)
+ }
+ }
+
+ // Return so that the future is only responded to
+ // by the FSM handler when the application is done
+ return
+ }
+ case LogAddPeerDeprecated:
+ case LogRemovePeerDeprecated:
+ case LogNoop:
+ // Ignore the no-op
+
+ default:
+ panic(fmt.Errorf("unrecognized log type: %#v", l))
+ }
+
+ // Invoke the future if given
+ if future != nil {
+ future.respond(nil)
+ }
+}
+
+// processRPC is called to handle an incoming RPC request. This must only be
+// called from the main thread.
+func (r *Raft) processRPC(rpc RPC) {
+ if err := r.checkRPCHeader(rpc); err != nil {
+ rpc.Respond(nil, err)
+ return
+ }
+
+ switch cmd := rpc.Command.(type) {
+ case *AppendEntriesRequest:
+ r.appendEntries(rpc, cmd)
+ case *RequestVoteRequest:
+ r.requestVote(rpc, cmd)
+ case *InstallSnapshotRequest:
+ r.installSnapshot(rpc, cmd)
+ case *TimeoutNowRequest:
+ r.timeoutNow(rpc, cmd)
+ default:
+ r.logger.Error(fmt.Sprintf("Got unexpected command: %#v", rpc.Command))
+ rpc.Respond(nil, fmt.Errorf("unexpected command"))
+ }
+}
+
+// processHeartbeat is a special handler used just for heartbeat requests
+// so that they can be fast-pathed if a transport supports it. This must only
+// be called from the main thread.
+func (r *Raft) processHeartbeat(rpc RPC) {
+ defer metrics.MeasureSince([]string{"raft", "rpc", "processHeartbeat"}, time.Now())
+
+ // Check if we are shutdown, just ignore the RPC
+ select {
+ case <-r.shutdownCh:
+ return
+ default:
+ }
+
+ // Ensure we are only handling a heartbeat
+ switch cmd := rpc.Command.(type) {
+ case *AppendEntriesRequest:
+ r.appendEntries(rpc, cmd)
+ default:
+ r.logger.Error(fmt.Sprintf("Expected heartbeat, got command: %#v", rpc.Command))
+ rpc.Respond(nil, fmt.Errorf("unexpected command"))
+ }
+}
+
+// appendEntries is invoked when we get an append entries RPC call. This must
+// only be called from the main thread.
+func (r *Raft) appendEntries(rpc RPC, a *AppendEntriesRequest) {
+ defer metrics.MeasureSince([]string{"raft", "rpc", "appendEntries"}, time.Now())
+ // Setup a response
+ resp := &AppendEntriesResponse{
+ RPCHeader: r.getRPCHeader(),
+ Term: r.getCurrentTerm(),
+ LastLog: r.getLastIndex(),
+ Success: false,
+ NoRetryBackoff: false,
+ }
+ var rpcErr error
+ defer func() {
+ rpc.Respond(resp, rpcErr)
+ }()
+
+ // Ignore an older term
+ if a.Term < r.getCurrentTerm() {
+ return
+ }
+
+ // Increase the term if we see a newer one, also transition to follower
+ // if we ever get an appendEntries call
+ if a.Term > r.getCurrentTerm() || r.getState() != Follower {
+ // Ensure transition to follower
+ r.setState(Follower)
+ r.setCurrentTerm(a.Term)
+ resp.Term = a.Term
+ }
+
+ // Save the current leader
+ r.setLeader(ServerAddress(r.trans.DecodePeer(a.Leader)))
+
+ // Verify the last log entry
+ if a.PrevLogEntry > 0 {
+ lastIdx, lastTerm := r.getLastEntry()
+
+ var prevLogTerm uint64
+ if a.PrevLogEntry == lastIdx {
+ prevLogTerm = lastTerm
+
+ } else {
+ var prevLog Log
+ if err := r.logs.GetLog(a.PrevLogEntry, &prevLog); err != nil {
+ r.logger.Warn(fmt.Sprintf("Failed to get previous log: %d %v (last: %d)",
+ a.PrevLogEntry, err, lastIdx))
+ resp.NoRetryBackoff = true
+ return
+ }
+ prevLogTerm = prevLog.Term
+ }
+
+ if a.PrevLogTerm != prevLogTerm {
+ r.logger.Warn(fmt.Sprintf("Previous log term mis-match: ours: %d remote: %d",
+ prevLogTerm, a.PrevLogTerm))
+ resp.NoRetryBackoff = true
+ return
+ }
+ }
+
+ // Process any new entries
+ if len(a.Entries) > 0 {
+ start := time.Now()
+
+ // Delete any conflicting entries, skip any duplicates
+ lastLogIdx, _ := r.getLastLog()
+ var newEntries []*Log
+ for i, entry := range a.Entries {
+ if entry.Index > lastLogIdx {
+ newEntries = a.Entries[i:]
+ break
+ }
+ var storeEntry Log
+ if err := r.logs.GetLog(entry.Index, &storeEntry); err != nil {
+ r.logger.Warn(fmt.Sprintf("Failed to get log entry %d: %v",
+ entry.Index, err))
+ return
+ }
+ if entry.Term != storeEntry.Term {
+ r.logger.Warn(fmt.Sprintf("Clearing log suffix from %d to %d", entry.Index, lastLogIdx))
+ if err := r.logs.DeleteRange(entry.Index, lastLogIdx); err != nil {
+ r.logger.Error(fmt.Sprintf("Failed to clear log suffix: %v", err))
+ return
+ }
+ if entry.Index <= r.configurations.latestIndex {
+ r.configurations.latest = r.configurations.committed
+ r.configurations.latestIndex = r.configurations.committedIndex
+ }
+ newEntries = a.Entries[i:]
+ break
+ }
+ }
+
+ if n := len(newEntries); n > 0 {
+ // Append the new entries
+ if err := r.logs.StoreLogs(newEntries); err != nil {
+ r.logger.Error(fmt.Sprintf("Failed to append to logs: %v", err))
+ // TODO: leaving r.getLastLog() in the wrong
+ // state if there was a truncation above
+ return
+ }
+
+ // Handle any new configuration changes
+ for _, newEntry := range newEntries {
+ r.processConfigurationLogEntry(newEntry)
+ }
+
+ // Update the lastLog
+ last := newEntries[n-1]
+ r.setLastLog(last.Index, last.Term)
+ }
+
+ metrics.MeasureSince([]string{"raft", "rpc", "appendEntries", "storeLogs"}, start)
+ }
+
+ // Update the commit index
+ if a.LeaderCommitIndex > 0 && a.LeaderCommitIndex > r.getCommitIndex() {
+ start := time.Now()
+ idx := min(a.LeaderCommitIndex, r.getLastIndex())
+ r.setCommitIndex(idx)
+ if r.configurations.latestIndex <= idx {
+ r.configurations.committed = r.configurations.latest
+ r.configurations.committedIndex = r.configurations.latestIndex
+ }
+ r.processLogs(idx, nil)
+ metrics.MeasureSince([]string{"raft", "rpc", "appendEntries", "processLogs"}, start)
+ }
+
+ // Everything went well, set success
+ resp.Success = true
+ r.setLastContact()
+ return
+}
+
+// processConfigurationLogEntry takes a log entry and updates the latest
+// configuration if the entry results in a new configuration. This must only be
+// called from the main thread, or from NewRaft() before any threads have begun.
+func (r *Raft) processConfigurationLogEntry(entry *Log) {
+ if entry.Type == LogConfiguration {
+ r.configurations.committed = r.configurations.latest
+ r.configurations.committedIndex = r.configurations.latestIndex
+ r.configurations.latest = decodeConfiguration(entry.Data)
+ r.configurations.latestIndex = entry.Index
+ } else if entry.Type == LogAddPeerDeprecated || entry.Type == LogRemovePeerDeprecated {
+ r.configurations.committed = r.configurations.latest
+ r.configurations.committedIndex = r.configurations.latestIndex
+ r.configurations.latest = decodePeers(entry.Data, r.trans)
+ r.configurations.latestIndex = entry.Index
+ }
+}
+
+// requestVote is invoked when we get an request vote RPC call.
+func (r *Raft) requestVote(rpc RPC, req *RequestVoteRequest) {
+ defer metrics.MeasureSince([]string{"raft", "rpc", "requestVote"}, time.Now())
+ r.observe(*req)
+
+ // Setup a response
+ resp := &RequestVoteResponse{
+ RPCHeader: r.getRPCHeader(),
+ Term: r.getCurrentTerm(),
+ Granted: false,
+ }
+ var rpcErr error
+ defer func() {
+ rpc.Respond(resp, rpcErr)
+ }()
+
+ // Version 0 servers will panic unless the peers is present. It's only
+ // used on them to produce a warning message.
+ if r.protocolVersion < 2 {
+ resp.Peers = encodePeers(r.configurations.latest, r.trans)
+ }
+
+ // Check if we have an existing leader [who's not the candidate] and also
+ // check the LeadershipTransfer flag is set. Usually votes are rejected if
+ // there is a known leader. But if the leader initiated a leadership transfer,
+ // vote!
+ candidate := r.trans.DecodePeer(req.Candidate)
+ if leader := r.Leader(); leader != "" && leader != candidate && !req.LeadershipTransfer {
+ r.logger.Warn(fmt.Sprintf("Rejecting vote request from %v since we have a leader: %v",
+ candidate, leader))
+ return
+ }
+
+ // Ignore an older term
+ if req.Term < r.getCurrentTerm() {
+ return
+ }
+
+ // Increase the term if we see a newer one
+ if req.Term > r.getCurrentTerm() {
+ // Ensure transition to follower
+ r.logger.Debug("lost leadership because received a requestvote with newer term")
+ r.setState(Follower)
+ r.setCurrentTerm(req.Term)
+ resp.Term = req.Term
+ }
+
+ // Check if we have voted yet
+ lastVoteTerm, err := r.stable.GetUint64(keyLastVoteTerm)
+ if err != nil && err.Error() != "not found" {
+ r.logger.Error(fmt.Sprintf("Failed to get last vote term: %v", err))
+ return
+ }
+ lastVoteCandBytes, err := r.stable.Get(keyLastVoteCand)
+ if err != nil && err.Error() != "not found" {
+ r.logger.Error(fmt.Sprintf("Failed to get last vote candidate: %v", err))
+ return
+ }
+
+ // Check if we've voted in this election before
+ if lastVoteTerm == req.Term && lastVoteCandBytes != nil {
+ r.logger.Info(fmt.Sprintf("Duplicate RequestVote for same term: %d", req.Term))
+ if bytes.Compare(lastVoteCandBytes, req.Candidate) == 0 {
+ r.logger.Warn(fmt.Sprintf("Duplicate RequestVote from candidate: %s", req.Candidate))
+ resp.Granted = true
+ }
+ return
+ }
+
+ // Reject if their term is older
+ lastIdx, lastTerm := r.getLastEntry()
+ if lastTerm > req.LastLogTerm {
+ r.logger.Warn(fmt.Sprintf("Rejecting vote request from %v since our last term is greater (%d, %d)",
+ candidate, lastTerm, req.LastLogTerm))
+ return
+ }
+
+ if lastTerm == req.LastLogTerm && lastIdx > req.LastLogIndex {
+ r.logger.Warn(fmt.Sprintf("Rejecting vote request from %v since our last index is greater (%d, %d)",
+ candidate, lastIdx, req.LastLogIndex))
+ return
+ }
+
+ // Persist a vote for safety
+ if err := r.persistVote(req.Term, req.Candidate); err != nil {
+ r.logger.Error(fmt.Sprintf("Failed to persist vote: %v", err))
+ return
+ }
+
+ resp.Granted = true
+ r.setLastContact()
+ return
+}
+
+// installSnapshot is invoked when we get a InstallSnapshot RPC call.
+// We must be in the follower state for this, since it means we are
+// too far behind a leader for log replay. This must only be called
+// from the main thread.
+func (r *Raft) installSnapshot(rpc RPC, req *InstallSnapshotRequest) {
+ defer metrics.MeasureSince([]string{"raft", "rpc", "installSnapshot"}, time.Now())
+ // Setup a response
+ resp := &InstallSnapshotResponse{
+ Term: r.getCurrentTerm(),
+ Success: false,
+ }
+ var rpcErr error
+ defer func() {
+ io.Copy(ioutil.Discard, rpc.Reader) // ensure we always consume all the snapshot data from the stream [see issue #212]
+ rpc.Respond(resp, rpcErr)
+ }()
+
+ // Sanity check the version
+ if req.SnapshotVersion < SnapshotVersionMin ||
+ req.SnapshotVersion > SnapshotVersionMax {
+ rpcErr = fmt.Errorf("unsupported snapshot version %d", req.SnapshotVersion)
+ return
+ }
+
+ // Ignore an older term
+ if req.Term < r.getCurrentTerm() {
+ r.logger.Info(fmt.Sprintf("Ignoring installSnapshot request with older term of %d vs currentTerm %d",
+ req.Term, r.getCurrentTerm()))
+ return
+ }
+
+ // Increase the term if we see a newer one
+ if req.Term > r.getCurrentTerm() {
+ // Ensure transition to follower
+ r.setState(Follower)
+ r.setCurrentTerm(req.Term)
+ resp.Term = req.Term
+ }
+
+ // Save the current leader
+ r.setLeader(ServerAddress(r.trans.DecodePeer(req.Leader)))
+
+ // Create a new snapshot
+ var reqConfiguration Configuration
+ var reqConfigurationIndex uint64
+ if req.SnapshotVersion > 0 {
+ reqConfiguration = decodeConfiguration(req.Configuration)
+ reqConfigurationIndex = req.ConfigurationIndex
+ } else {
+ reqConfiguration = decodePeers(req.Peers, r.trans)
+ reqConfigurationIndex = req.LastLogIndex
+ }
+ version := getSnapshotVersion(r.protocolVersion)
+ sink, err := r.snapshots.Create(version, req.LastLogIndex, req.LastLogTerm,
+ reqConfiguration, reqConfigurationIndex, r.trans)
+ if err != nil {
+ r.logger.Error(fmt.Sprintf("Failed to create snapshot to install: %v", err))
+ rpcErr = fmt.Errorf("failed to create snapshot: %v", err)
+ return
+ }
+
+ // Spill the remote snapshot to disk
+ n, err := io.Copy(sink, rpc.Reader)
+ if err != nil {
+ sink.Cancel()
+ r.logger.Error(fmt.Sprintf("Failed to copy snapshot: %v", err))
+ rpcErr = err
+ return
+ }
+
+ // Check that we received it all
+ if n != req.Size {
+ sink.Cancel()
+ r.logger.Error(fmt.Sprintf("Failed to receive whole snapshot: %d / %d", n, req.Size))
+ rpcErr = fmt.Errorf("short read")
+ return
+ }
+
+ // Finalize the snapshot
+ if err := sink.Close(); err != nil {
+ r.logger.Error(fmt.Sprintf("Failed to finalize snapshot: %v", err))
+ rpcErr = err
+ return
+ }
+ r.logger.Info(fmt.Sprintf("Copied %d bytes to local snapshot", n))
+
+ // Restore snapshot
+ future := &restoreFuture{ID: sink.ID()}
+ future.init()
+ select {
+ case r.fsmMutateCh <- future:
+ case <-r.shutdownCh:
+ future.respond(ErrRaftShutdown)
+ return
+ }
+
+ // Wait for the restore to happen
+ if err := future.Error(); err != nil {
+ r.logger.Error(fmt.Sprintf("Failed to restore snapshot: %v", err))
+ rpcErr = err
+ return
+ }
+
+ // Update the lastApplied so we don't replay old logs
+ r.setLastApplied(req.LastLogIndex)
+
+ // Update the last stable snapshot info
+ r.setLastSnapshot(req.LastLogIndex, req.LastLogTerm)
+
+ // Restore the peer set
+ r.configurations.latest = reqConfiguration
+ r.configurations.latestIndex = reqConfigurationIndex
+ r.configurations.committed = reqConfiguration
+ r.configurations.committedIndex = reqConfigurationIndex
+
+ // Compact logs, continue even if this fails
+ if err := r.compactLogs(req.LastLogIndex); err != nil {
+ r.logger.Error(fmt.Sprintf("Failed to compact logs: %v", err))
+ }
+
+ r.logger.Info("Installed remote snapshot")
+ resp.Success = true
+ r.setLastContact()
+ return
+}
+
+// setLastContact is used to set the last contact time to now
+func (r *Raft) setLastContact() {
+ r.lastContactLock.Lock()
+ r.lastContact = time.Now()
+ r.lastContactLock.Unlock()
+}
+
+type voteResult struct {
+ RequestVoteResponse
+ voterID ServerID
+}
+
+// electSelf is used to send a RequestVote RPC to all peers, and vote for
+// ourself. This has the side affecting of incrementing the current term. The
+// response channel returned is used to wait for all the responses (including a
+// vote for ourself). This must only be called from the main thread.
+func (r *Raft) electSelf() <-chan *voteResult {
+ // Create a response channel
+ respCh := make(chan *voteResult, len(r.configurations.latest.Servers))
+
+ // Increment the term
+ r.setCurrentTerm(r.getCurrentTerm() + 1)
+
+ // Construct the request
+ lastIdx, lastTerm := r.getLastEntry()
+ req := &RequestVoteRequest{
+ RPCHeader: r.getRPCHeader(),
+ Term: r.getCurrentTerm(),
+ Candidate: r.trans.EncodePeer(r.localID, r.localAddr),
+ LastLogIndex: lastIdx,
+ LastLogTerm: lastTerm,
+ LeadershipTransfer: r.candidateFromLeadershipTransfer,
+ }
+
+ // Construct a function to ask for a vote
+ askPeer := func(peer Server) {
+ r.goFunc(func() {
+ defer metrics.MeasureSince([]string{"raft", "candidate", "electSelf"}, time.Now())
+ resp := &voteResult{voterID: peer.ID}
+ err := r.trans.RequestVote(peer.ID, peer.Address, req, &resp.RequestVoteResponse)
+ if err != nil {
+ r.logger.Error(fmt.Sprintf("Failed to make RequestVote RPC to %v: %v", peer, err))
+ resp.Term = req.Term
+ resp.Granted = false
+ }
+ respCh <- resp
+ })
+ }
+
+ // For each peer, request a vote
+ for _, server := range r.configurations.latest.Servers {
+ if server.Suffrage == Voter {
+ if server.ID == r.localID {
+ // Persist a vote for ourselves
+ if err := r.persistVote(req.Term, req.Candidate); err != nil {
+ r.logger.Error(fmt.Sprintf("Failed to persist vote : %v", err))
+ return nil
+ }
+ // Include our own vote
+ respCh <- &voteResult{
+ RequestVoteResponse: RequestVoteResponse{
+ RPCHeader: r.getRPCHeader(),
+ Term: req.Term,
+ Granted: true,
+ },
+ voterID: r.localID,
+ }
+ } else {
+ askPeer(server)
+ }
+ }
+ }
+
+ return respCh
+}
+
+// persistVote is used to persist our vote for safety.
+func (r *Raft) persistVote(term uint64, candidate []byte) error {
+ if err := r.stable.SetUint64(keyLastVoteTerm, term); err != nil {
+ return err
+ }
+ if err := r.stable.Set(keyLastVoteCand, candidate); err != nil {
+ return err
+ }
+ return nil
+}
+
+// setCurrentTerm is used to set the current term in a durable manner.
+func (r *Raft) setCurrentTerm(t uint64) {
+ // Persist to disk first
+ if err := r.stable.SetUint64(keyCurrentTerm, t); err != nil {
+ panic(fmt.Errorf("failed to save current term: %v", err))
+ }
+ r.raftState.setCurrentTerm(t)
+}
+
+// setState is used to update the current state. Any state
+// transition causes the known leader to be cleared. This means
+// that leader should be set only after updating the state.
+func (r *Raft) setState(state RaftState) {
+ r.setLeader("")
+ oldState := r.raftState.getState()
+ r.raftState.setState(state)
+ if oldState != state {
+ r.observe(state)
+ }
+}
+
+// LookupServer looks up a server by ServerID.
+func (r *Raft) lookupServer(id ServerID) *Server {
+ for _, server := range r.configurations.latest.Servers {
+ if server.ID != r.localID {
+ return &server
+ }
+ }
+ return nil
+}
+
+// pickServer returns the follower that is most up to date. Because it accesses
+// leaderstate, it should only be called from the leaderloop.
+func (r *Raft) pickServer() *Server {
+ var pick *Server
+ var current uint64
+ for _, server := range r.configurations.latest.Servers {
+ if server.ID == r.localID {
+ continue
+ }
+ state, ok := r.leaderState.replState[server.ID]
+ if !ok {
+ continue
+ }
+ nextIdx := atomic.LoadUint64(&state.nextIndex)
+ if nextIdx > current {
+ current = nextIdx
+ tmp := server
+ pick = &tmp
+ }
+ }
+ return pick
+}
+
+// initiateLeadershipTransfer starts the leadership on the leader side, by
+// sending a message to the leadershipTransferCh, to make sure it runs in the
+// mainloop.
+func (r *Raft) initiateLeadershipTransfer(id *ServerID, address *ServerAddress) LeadershipTransferFuture {
+ future := &leadershipTransferFuture{ID: id, Address: address}
+ future.init()
+
+ if id != nil && *id == r.localID {
+ err := fmt.Errorf("cannot transfer leadership to itself")
+ r.logger.Info(err.Error())
+ future.respond(err)
+ return future
+ }
+
+ select {
+ case r.leadershipTransferCh <- future:
+ return future
+ case <-r.shutdownCh:
+ return errorFuture{ErrRaftShutdown}
+ default:
+ return errorFuture{ErrEnqueueTimeout}
+ }
+}
+
+// timeoutNow is what happens when a server receives a TimeoutNowRequest.
+func (r *Raft) timeoutNow(rpc RPC, req *TimeoutNowRequest) {
+ r.setLeader("")
+ r.setState(Candidate)
+ r.candidateFromLeadershipTransfer = true
+ rpc.Respond(&TimeoutNowResponse{}, nil)
+}
diff -Naur --color b/vendor/github.com/hashicorp/raft/README.md a/vendor/github.com/hashicorp/raft/README.md
--- b/vendor/github.com/hashicorp/raft/README.md 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/README.md 2022-11-15 23:06:31.562057797 +0100
@@ -0,0 +1,107 @@
+raft [![Build Status](https://travis-ci.org/hashicorp/raft.png)](https://travis-ci.org/hashicorp/raft) [![CircleCI](https://circleci.com/gh/hashicorp/raft.svg?style=svg)](https://circleci.com/gh/hashicorp/raft)
+====
+
+raft is a [Go](http://www.golang.org) library that manages a replicated
+log and can be used with an FSM to manage replicated state machines. It
+is a library for providing [consensus](http://en.wikipedia.org/wiki/Consensus_(computer_science)).
+
+The use cases for such a library are far-reaching, such as replicated state
+machines which are a key component of many distributed systems. They enable
+building Consistent, Partition Tolerant (CP) systems, with limited
+fault tolerance as well.
+
+## Building
+
+If you wish to build raft you'll need Go version 1.2+ installed.
+
+Please check your installation with:
+
+```
+go version
+```
+
+## Documentation
+
+For complete documentation, see the associated [Godoc](http://godoc.org/github.com/hashicorp/raft).
+
+To prevent complications with cgo, the primary backend `MDBStore` is in a separate repository,
+called [raft-mdb](http://github.com/hashicorp/raft-mdb). That is the recommended implementation
+for the `LogStore` and `StableStore`.
+
+A pure Go backend using [BoltDB](https://github.com/boltdb/bolt) is also available called
+[raft-boltdb](https://github.com/hashicorp/raft-boltdb). It can also be used as a `LogStore`
+and `StableStore`.
+
+## Tagged Releases
+
+As of September 2017, HashiCorp will start using tags for this library to clearly indicate
+major version updates. We recommend you vendor your application's dependency on this library.
+
+* v0.1.0 is the original stable version of the library that was in master and has been maintained
+with no breaking API changes. This was in use by Consul prior to version 0.7.0.
+
+* v1.0.0 takes the changes that were staged in the library-v2-stage-one branch. This version
+manages server identities using a UUID, so introduces some breaking API changes. It also versions
+the Raft protocol, and requires some special steps when interoperating with Raft servers running
+older versions of the library (see the detailed comment in config.go about version compatibility).
+You can reference https://github.com/hashicorp/consul/pull/2222 for an idea of what was required
+to port Consul to these new interfaces.
+
+ This version includes some new features as well, including non voting servers, a new address
+ provider abstraction in the transport layer, and more resilient snapshots.
+
+## Protocol
+
+raft is based on ["Raft: In Search of an Understandable Consensus Algorithm"](https://raft.github.io/raft.pdf)
+
+A high level overview of the Raft protocol is described below, but for details please read the full
+[Raft paper](https://raft.github.io/raft.pdf)
+followed by the raft source. Any questions about the raft protocol should be sent to the
+[raft-dev mailing list](https://groups.google.com/forum/#!forum/raft-dev).
+
+### Protocol Description
+
+Raft nodes are always in one of three states: follower, candidate or leader. All
+nodes initially start out as a follower. In this state, nodes can accept log entries
+from a leader and cast votes. If no entries are received for some time, nodes
+self-promote to the candidate state. In the candidate state nodes request votes from
+their peers. If a candidate receives a quorum of votes, then it is promoted to a leader.
+The leader must accept new log entries and replicate to all the other followers.
+In addition, if stale reads are not acceptable, all queries must also be performed on
+the leader.
+
+Once a cluster has a leader, it is able to accept new log entries. A client can
+request that a leader append a new log entry, which is an opaque binary blob to
+Raft. The leader then writes the entry to durable storage and attempts to replicate
+to a quorum of followers. Once the log entry is considered *committed*, it can be
+*applied* to a finite state machine. The finite state machine is application specific,
+and is implemented using an interface.
+
+An obvious question relates to the unbounded nature of a replicated log. Raft provides
+a mechanism by which the current state is snapshotted, and the log is compacted. Because
+of the FSM abstraction, restoring the state of the FSM must result in the same state
+as a replay of old logs. This allows Raft to capture the FSM state at a point in time,
+and then remove all the logs that were used to reach that state. This is performed automatically
+without user intervention, and prevents unbounded disk usage as well as minimizing
+time spent replaying logs.
+
+Lastly, there is the issue of updating the peer set when new servers are joining
+or existing servers are leaving. As long as a quorum of nodes is available, this
+is not an issue as Raft provides mechanisms to dynamically update the peer set.
+If a quorum of nodes is unavailable, then this becomes a very challenging issue.
+For example, suppose there are only 2 peers, A and B. The quorum size is also
+2, meaning both nodes must agree to commit a log entry. If either A or B fails,
+it is now impossible to reach quorum. This means the cluster is unable to add,
+or remove a node, or commit any additional log entries. This results in *unavailability*.
+At this point, manual intervention would be required to remove either A or B,
+and to restart the remaining node in bootstrap mode.
+
+A Raft cluster of 3 nodes can tolerate a single node failure, while a cluster
+of 5 can tolerate 2 node failures. The recommended configuration is to either
+run 3 or 5 raft servers. This maximizes availability without
+greatly sacrificing performance.
+
+In terms of performance, Raft is comparable to Paxos. Assuming stable leadership,
+committing a log entry requires a single round trip to half of the cluster.
+Thus performance is bound by disk I/O and network latency.
+
diff -Naur --color b/vendor/github.com/hashicorp/raft/replication.go a/vendor/github.com/hashicorp/raft/replication.go
--- b/vendor/github.com/hashicorp/raft/replication.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/replication.go 2022-11-15 23:06:31.568724593 +0100
@@ -0,0 +1,599 @@
+package raft
+
+import (
+ "errors"
+ "fmt"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/armon/go-metrics"
+)
+
+const (
+ maxFailureScale = 12
+ failureWait = 10 * time.Millisecond
+)
+
+var (
+ // ErrLogNotFound indicates a given log entry is not available.
+ ErrLogNotFound = errors.New("log not found")
+
+ // ErrPipelineReplicationNotSupported can be returned by the transport to
+ // signal that pipeline replication is not supported in general, and that
+ // no error message should be produced.
+ ErrPipelineReplicationNotSupported = errors.New("pipeline replication not supported")
+)
+
+// followerReplication is in charge of sending snapshots and log entries from
+// this leader during this particular term to a remote follower.
+type followerReplication struct {
+ // currentTerm and nextIndex must be kept at the top of the struct so
+ // they're 64 bit aligned which is a requirement for atomic ops on 32 bit
+ // platforms.
+
+ // currentTerm is the term of this leader, to be included in AppendEntries
+ // requests.
+ currentTerm uint64
+
+ // nextIndex is the index of the next log entry to send to the follower,
+ // which may fall past the end of the log.
+ nextIndex uint64
+
+ // peer contains the network address and ID of the remote follower.
+ peer Server
+
+ // commitment tracks the entries acknowledged by followers so that the
+ // leader's commit index can advance. It is updated on successful
+ // AppendEntries responses.
+ commitment *commitment
+
+ // stopCh is notified/closed when this leader steps down or the follower is
+ // removed from the cluster. In the follower removed case, it carries a log
+ // index; replication should be attempted with a best effort up through that
+ // index, before exiting.
+ stopCh chan uint64
+
+ // triggerCh is notified every time new entries are appended to the log.
+ triggerCh chan struct{}
+
+ // triggerDeferErrorCh is used to provide a backchannel. By sending a
+ // deferErr, the sender can be notifed when the replication is done.
+ triggerDeferErrorCh chan *deferError
+
+ // lastContact is updated to the current time whenever any response is
+ // received from the follower (successful or not). This is used to check
+ // whether the leader should step down (Raft.checkLeaderLease()).
+ lastContact time.Time
+ // lastContactLock protects 'lastContact'.
+ lastContactLock sync.RWMutex
+
+ // failures counts the number of failed RPCs since the last success, which is
+ // used to apply backoff.
+ failures uint64
+
+ // notifyCh is notified to send out a heartbeat, which is used to check that
+ // this server is still leader.
+ notifyCh chan struct{}
+ // notify is a map of futures to be resolved upon receipt of an
+ // acknowledgement, then cleared from this map.
+ notify map[*verifyFuture]struct{}
+ // notifyLock protects 'notify'.
+ notifyLock sync.Mutex
+
+ // stepDown is used to indicate to the leader that we
+ // should step down based on information from a follower.
+ stepDown chan struct{}
+
+ // allowPipeline is used to determine when to pipeline the AppendEntries RPCs.
+ // It is private to this replication goroutine.
+ allowPipeline bool
+}
+
+// notifyAll is used to notify all the waiting verify futures
+// if the follower believes we are still the leader.
+func (s *followerReplication) notifyAll(leader bool) {
+ // Clear the waiting notifies minimizing lock time
+ s.notifyLock.Lock()
+ n := s.notify
+ s.notify = make(map[*verifyFuture]struct{})
+ s.notifyLock.Unlock()
+
+ // Submit our votes
+ for v, _ := range n {
+ v.vote(leader)
+ }
+}
+
+// cleanNotify is used to delete notify, .
+func (s *followerReplication) cleanNotify(v *verifyFuture) {
+ s.notifyLock.Lock()
+ delete(s.notify, v)
+ s.notifyLock.Unlock()
+}
+
+// LastContact returns the time of last contact.
+func (s *followerReplication) LastContact() time.Time {
+ s.lastContactLock.RLock()
+ last := s.lastContact
+ s.lastContactLock.RUnlock()
+ return last
+}
+
+// setLastContact sets the last contact to the current time.
+func (s *followerReplication) setLastContact() {
+ s.lastContactLock.Lock()
+ s.lastContact = time.Now()
+ s.lastContactLock.Unlock()
+}
+
+// replicate is a long running routine that replicates log entries to a single
+// follower.
+func (r *Raft) replicate(s *followerReplication) {
+ // Start an async heartbeating routing
+ stopHeartbeat := make(chan struct{})
+ defer close(stopHeartbeat)
+ r.goFunc(func() { r.heartbeat(s, stopHeartbeat) })
+
+RPC:
+ shouldStop := false
+ for !shouldStop {
+ select {
+ case maxIndex := <-s.stopCh:
+ // Make a best effort to replicate up to this index
+ if maxIndex > 0 {
+ r.replicateTo(s, maxIndex)
+ }
+ return
+ case deferErr := <-s.triggerDeferErrorCh:
+ lastLogIdx, _ := r.getLastLog()
+ shouldStop = r.replicateTo(s, lastLogIdx)
+ if !shouldStop {
+ deferErr.respond(nil)
+ } else {
+ deferErr.respond(fmt.Errorf("replication failed"))
+ }
+ case <-s.triggerCh:
+ lastLogIdx, _ := r.getLastLog()
+ shouldStop = r.replicateTo(s, lastLogIdx)
+ // This is _not_ our heartbeat mechanism but is to ensure
+ // followers quickly learn the leader's commit index when
+ // raft commits stop flowing naturally. The actual heartbeats
+ // can't do this to keep them unblocked by disk IO on the
+ // follower. See https://github.com/hashicorp/raft/issues/282.
+ case <-randomTimeout(r.conf.CommitTimeout):
+ lastLogIdx, _ := r.getLastLog()
+ shouldStop = r.replicateTo(s, lastLogIdx)
+ }
+
+ // If things looks healthy, switch to pipeline mode
+ if !shouldStop && s.allowPipeline {
+ goto PIPELINE
+ }
+ }
+ return
+
+PIPELINE:
+ // Disable until re-enabled
+ s.allowPipeline = false
+
+ // Replicates using a pipeline for high performance. This method
+ // is not able to gracefully recover from errors, and so we fall back
+ // to standard mode on failure.
+ if err := r.pipelineReplicate(s); err != nil {
+ if err != ErrPipelineReplicationNotSupported {
+ r.logger.Error(fmt.Sprintf("Failed to start pipeline replication to %s: %s", s.peer, err))
+ }
+ }
+ goto RPC
+}
+
+// replicateTo is a helper to replicate(), used to replicate the logs up to a
+// given last index.
+// If the follower log is behind, we take care to bring them up to date.
+func (r *Raft) replicateTo(s *followerReplication, lastIndex uint64) (shouldStop bool) {
+ // Create the base request
+ var req AppendEntriesRequest
+ var resp AppendEntriesResponse
+ var start time.Time
+START:
+ // Prevent an excessive retry rate on errors
+ if s.failures > 0 {
+ select {
+ case <-time.After(backoff(failureWait, s.failures, maxFailureScale)):
+ case <-r.shutdownCh:
+ }
+ }
+
+ // Setup the request
+ if err := r.setupAppendEntries(s, &req, atomic.LoadUint64(&s.nextIndex), lastIndex); err == ErrLogNotFound {
+ goto SEND_SNAP
+ } else if err != nil {
+ return
+ }
+
+ // Make the RPC call
+ start = time.Now()
+ if err := r.trans.AppendEntries(s.peer.ID, s.peer.Address, &req, &resp); err != nil {
+ r.logger.Error(fmt.Sprintf("Failed to AppendEntries to %v: %v", s.peer, err))
+ s.failures++
+ return
+ }
+ appendStats(string(s.peer.ID), start, float32(len(req.Entries)))
+
+ // Check for a newer term, stop running
+ if resp.Term > req.Term {
+ r.handleStaleTerm(s)
+ return true
+ }
+
+ // Update the last contact
+ s.setLastContact()
+
+ // Update s based on success
+ if resp.Success {
+ // Update our replication state
+ updateLastAppended(s, &req)
+
+ // Clear any failures, allow pipelining
+ s.failures = 0
+ s.allowPipeline = true
+ } else {
+ atomic.StoreUint64(&s.nextIndex, max(min(s.nextIndex-1, resp.LastLog+1), 1))
+ if resp.NoRetryBackoff {
+ s.failures = 0
+ } else {
+ s.failures++
+ }
+ r.logger.Warn(fmt.Sprintf("AppendEntries to %v rejected, sending older logs (next: %d)", s.peer, atomic.LoadUint64(&s.nextIndex)))
+ }
+
+CHECK_MORE:
+ // Poll the stop channel here in case we are looping and have been asked
+ // to stop, or have stepped down as leader. Even for the best effort case
+ // where we are asked to replicate to a given index and then shutdown,
+ // it's better to not loop in here to send lots of entries to a straggler
+ // that's leaving the cluster anyways.
+ select {
+ case <-s.stopCh:
+ return true
+ default:
+ }
+
+ // Check if there are more logs to replicate
+ if atomic.LoadUint64(&s.nextIndex) <= lastIndex {
+ goto START
+ }
+ return
+
+ // SEND_SNAP is used when we fail to get a log, usually because the follower
+ // is too far behind, and we must ship a snapshot down instead
+SEND_SNAP:
+ if stop, err := r.sendLatestSnapshot(s); stop {
+ return true
+ } else if err != nil {
+ r.logger.Error(fmt.Sprintf("Failed to send snapshot to %v: %v", s.peer, err))
+ return
+ }
+
+ // Check if there is more to replicate
+ goto CHECK_MORE
+}
+
+// sendLatestSnapshot is used to send the latest snapshot we have
+// down to our follower.
+func (r *Raft) sendLatestSnapshot(s *followerReplication) (bool, error) {
+ // Get the snapshots
+ snapshots, err := r.snapshots.List()
+ if err != nil {
+ r.logger.Error(fmt.Sprintf("Failed to list snapshots: %v", err))
+ return false, err
+ }
+
+ // Check we have at least a single snapshot
+ if len(snapshots) == 0 {
+ return false, fmt.Errorf("no snapshots found")
+ }
+
+ // Open the most recent snapshot
+ snapID := snapshots[0].ID
+ meta, snapshot, err := r.snapshots.Open(snapID)
+ if err != nil {
+ r.logger.Error(fmt.Sprintf("Failed to open snapshot %v: %v", snapID, err))
+ return false, err
+ }
+ defer snapshot.Close()
+
+ // Setup the request
+ req := InstallSnapshotRequest{
+ RPCHeader: r.getRPCHeader(),
+ SnapshotVersion: meta.Version,
+ Term: s.currentTerm,
+ Leader: r.trans.EncodePeer(r.localID, r.localAddr),
+ LastLogIndex: meta.Index,
+ LastLogTerm: meta.Term,
+ Peers: meta.Peers,
+ Size: meta.Size,
+ Configuration: encodeConfiguration(meta.Configuration),
+ ConfigurationIndex: meta.ConfigurationIndex,
+ }
+
+ // Make the call
+ start := time.Now()
+ var resp InstallSnapshotResponse
+ if err := r.trans.InstallSnapshot(s.peer.ID, s.peer.Address, &req, &resp, snapshot); err != nil {
+ r.logger.Error(fmt.Sprintf("Failed to install snapshot %v: %v", snapID, err))
+ s.failures++
+ return false, err
+ }
+ metrics.MeasureSince([]string{"raft", "replication", "installSnapshot", string(s.peer.ID)}, start)
+
+ // Check for a newer term, stop running
+ if resp.Term > req.Term {
+ r.handleStaleTerm(s)
+ return true, nil
+ }
+
+ // Update the last contact
+ s.setLastContact()
+
+ // Check for success
+ if resp.Success {
+ // Update the indexes
+ atomic.StoreUint64(&s.nextIndex, meta.Index+1)
+ s.commitment.match(s.peer.ID, meta.Index)
+
+ // Clear any failures
+ s.failures = 0
+
+ // Notify we are still leader
+ s.notifyAll(true)
+ } else {
+ s.failures++
+ r.logger.Warn(fmt.Sprintf("InstallSnapshot to %v rejected", s.peer))
+ }
+ return false, nil
+}
+
+// heartbeat is used to periodically invoke AppendEntries on a peer
+// to ensure they don't time out. This is done async of replicate(),
+// since that routine could potentially be blocked on disk IO.
+func (r *Raft) heartbeat(s *followerReplication, stopCh chan struct{}) {
+ var failures uint64
+ req := AppendEntriesRequest{
+ RPCHeader: r.getRPCHeader(),
+ Term: s.currentTerm,
+ Leader: r.trans.EncodePeer(r.localID, r.localAddr),
+ }
+ var resp AppendEntriesResponse
+ for {
+ // Wait for the next heartbeat interval or forced notify
+ select {
+ case <-s.notifyCh:
+ case <-randomTimeout(r.conf.HeartbeatTimeout / 10):
+ case <-stopCh:
+ return
+ }
+
+ start := time.Now()
+ if err := r.trans.AppendEntries(s.peer.ID, s.peer.Address, &req, &resp); err != nil {
+ r.logger.Error(fmt.Sprintf("Failed to heartbeat to %v: %v", s.peer.Address, err))
+ failures++
+ select {
+ case <-time.After(backoff(failureWait, failures, maxFailureScale)):
+ case <-stopCh:
+ }
+ } else {
+ s.setLastContact()
+ failures = 0
+ metrics.MeasureSince([]string{"raft", "replication", "heartbeat", string(s.peer.ID)}, start)
+ s.notifyAll(resp.Success)
+ }
+ }
+}
+
+// pipelineReplicate is used when we have synchronized our state with the follower,
+// and want to switch to a higher performance pipeline mode of replication.
+// We only pipeline AppendEntries commands, and if we ever hit an error, we fall
+// back to the standard replication which can handle more complex situations.
+func (r *Raft) pipelineReplicate(s *followerReplication) error {
+ // Create a new pipeline
+ pipeline, err := r.trans.AppendEntriesPipeline(s.peer.ID, s.peer.Address)
+ if err != nil {
+ return err
+ }
+ defer pipeline.Close()
+
+ // Log start and stop of pipeline
+ r.logger.Info(fmt.Sprintf("pipelining replication to peer %v", s.peer))
+ defer r.logger.Info(fmt.Sprintf("aborting pipeline replication to peer %v", s.peer))
+
+ // Create a shutdown and finish channel
+ stopCh := make(chan struct{})
+ finishCh := make(chan struct{})
+
+ // Start a dedicated decoder
+ r.goFunc(func() { r.pipelineDecode(s, pipeline, stopCh, finishCh) })
+
+ // Start pipeline sends at the last good nextIndex
+ nextIndex := atomic.LoadUint64(&s.nextIndex)
+
+ shouldStop := false
+SEND:
+ for !shouldStop {
+ select {
+ case <-finishCh:
+ break SEND
+ case maxIndex := <-s.stopCh:
+ // Make a best effort to replicate up to this index
+ if maxIndex > 0 {
+ r.pipelineSend(s, pipeline, &nextIndex, maxIndex)
+ }
+ break SEND
+ case deferErr := <-s.triggerDeferErrorCh:
+ lastLogIdx, _ := r.getLastLog()
+ shouldStop = r.pipelineSend(s, pipeline, &nextIndex, lastLogIdx)
+ if !shouldStop {
+ deferErr.respond(nil)
+ } else {
+ deferErr.respond(fmt.Errorf("replication failed"))
+ }
+ case <-s.triggerCh:
+ lastLogIdx, _ := r.getLastLog()
+ shouldStop = r.pipelineSend(s, pipeline, &nextIndex, lastLogIdx)
+ case <-randomTimeout(r.conf.CommitTimeout):
+ lastLogIdx, _ := r.getLastLog()
+ shouldStop = r.pipelineSend(s, pipeline, &nextIndex, lastLogIdx)
+ }
+ }
+
+ // Stop our decoder, and wait for it to finish
+ close(stopCh)
+ select {
+ case <-finishCh:
+ case <-r.shutdownCh:
+ }
+ return nil
+}
+
+// pipelineSend is used to send data over a pipeline. It is a helper to
+// pipelineReplicate.
+func (r *Raft) pipelineSend(s *followerReplication, p AppendPipeline, nextIdx *uint64, lastIndex uint64) (shouldStop bool) {
+ // Create a new append request
+ req := new(AppendEntriesRequest)
+ if err := r.setupAppendEntries(s, req, *nextIdx, lastIndex); err != nil {
+ return true
+ }
+
+ // Pipeline the append entries
+ if _, err := p.AppendEntries(req, new(AppendEntriesResponse)); err != nil {
+ r.logger.Error(fmt.Sprintf("Failed to pipeline AppendEntries to %v: %v", s.peer, err))
+ return true
+ }
+
+ // Increase the next send log to avoid re-sending old logs
+ if n := len(req.Entries); n > 0 {
+ last := req.Entries[n-1]
+ atomic.StoreUint64(nextIdx, last.Index+1)
+ }
+ return false
+}
+
+// pipelineDecode is used to decode the responses of pipelined requests.
+func (r *Raft) pipelineDecode(s *followerReplication, p AppendPipeline, stopCh, finishCh chan struct{}) {
+ defer close(finishCh)
+ respCh := p.Consumer()
+ for {
+ select {
+ case ready := <-respCh:
+ req, resp := ready.Request(), ready.Response()
+ appendStats(string(s.peer.ID), ready.Start(), float32(len(req.Entries)))
+
+ // Check for a newer term, stop running
+ if resp.Term > req.Term {
+ r.handleStaleTerm(s)
+ return
+ }
+
+ // Update the last contact
+ s.setLastContact()
+
+ // Abort pipeline if not successful
+ if !resp.Success {
+ return
+ }
+
+ // Update our replication state
+ updateLastAppended(s, req)
+ case <-stopCh:
+ return
+ }
+ }
+}
+
+// setupAppendEntries is used to setup an append entries request.
+func (r *Raft) setupAppendEntries(s *followerReplication, req *AppendEntriesRequest, nextIndex, lastIndex uint64) error {
+ req.RPCHeader = r.getRPCHeader()
+ req.Term = s.currentTerm
+ req.Leader = r.trans.EncodePeer(r.localID, r.localAddr)
+ req.LeaderCommitIndex = r.getCommitIndex()
+ if err := r.setPreviousLog(req, nextIndex); err != nil {
+ return err
+ }
+ if err := r.setNewLogs(req, nextIndex, lastIndex); err != nil {
+ return err
+ }
+ return nil
+}
+
+// setPreviousLog is used to setup the PrevLogEntry and PrevLogTerm for an
+// AppendEntriesRequest given the next index to replicate.
+func (r *Raft) setPreviousLog(req *AppendEntriesRequest, nextIndex uint64) error {
+ // Guard for the first index, since there is no 0 log entry
+ // Guard against the previous index being a snapshot as well
+ lastSnapIdx, lastSnapTerm := r.getLastSnapshot()
+ if nextIndex == 1 {
+ req.PrevLogEntry = 0
+ req.PrevLogTerm = 0
+
+ } else if (nextIndex - 1) == lastSnapIdx {
+ req.PrevLogEntry = lastSnapIdx
+ req.PrevLogTerm = lastSnapTerm
+
+ } else {
+ var l Log
+ if err := r.logs.GetLog(nextIndex-1, &l); err != nil {
+ r.logger.Error(fmt.Sprintf("Failed to get log at index %d: %v", nextIndex-1, err))
+ return err
+ }
+
+ // Set the previous index and term (0 if nextIndex is 1)
+ req.PrevLogEntry = l.Index
+ req.PrevLogTerm = l.Term
+ }
+ return nil
+}
+
+// setNewLogs is used to setup the logs which should be appended for a request.
+func (r *Raft) setNewLogs(req *AppendEntriesRequest, nextIndex, lastIndex uint64) error {
+ // Append up to MaxAppendEntries or up to the lastIndex
+ req.Entries = make([]*Log, 0, r.conf.MaxAppendEntries)
+ maxIndex := min(nextIndex+uint64(r.conf.MaxAppendEntries)-1, lastIndex)
+ for i := nextIndex; i <= maxIndex; i++ {
+ oldLog := new(Log)
+ if err := r.logs.GetLog(i, oldLog); err != nil {
+ r.logger.Error(fmt.Sprintf("Failed to get log at index %d: %v", i, err))
+ return err
+ }
+ req.Entries = append(req.Entries, oldLog)
+ }
+ return nil
+}
+
+// appendStats is used to emit stats about an AppendEntries invocation.
+func appendStats(peer string, start time.Time, logs float32) {
+ metrics.MeasureSince([]string{"raft", "replication", "appendEntries", "rpc", peer}, start)
+ metrics.IncrCounter([]string{"raft", "replication", "appendEntries", "logs", peer}, logs)
+}
+
+// handleStaleTerm is used when a follower indicates that we have a stale term.
+func (r *Raft) handleStaleTerm(s *followerReplication) {
+ r.logger.Error(fmt.Sprintf("peer %v has newer term, stopping replication", s.peer))
+ s.notifyAll(false) // No longer leader
+ asyncNotifyCh(s.stepDown)
+}
+
+// updateLastAppended is used to update follower replication state after a
+// successful AppendEntries RPC.
+// TODO: This isn't used during InstallSnapshot, but the code there is similar.
+func updateLastAppended(s *followerReplication, req *AppendEntriesRequest) {
+ // Mark any inflight logs as committed
+ if logs := req.Entries; len(logs) > 0 {
+ last := logs[len(logs)-1]
+ atomic.StoreUint64(&s.nextIndex, last.Index+1)
+ s.commitment.match(s.peer.ID, last.Index)
+ }
+
+ // Notify still leader
+ s.notifyAll(true)
+}
diff -Naur --color b/vendor/github.com/hashicorp/raft/snapshot.go a/vendor/github.com/hashicorp/raft/snapshot.go
--- b/vendor/github.com/hashicorp/raft/snapshot.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/snapshot.go 2022-11-15 23:06:31.568724593 +0100
@@ -0,0 +1,239 @@
+package raft
+
+import (
+ "fmt"
+ "io"
+ "time"
+
+ "github.com/armon/go-metrics"
+)
+
+// SnapshotMeta is for metadata of a snapshot.
+type SnapshotMeta struct {
+ // Version is the version number of the snapshot metadata. This does not cover
+ // the application's data in the snapshot, that should be versioned
+ // separately.
+ Version SnapshotVersion
+
+ // ID is opaque to the store, and is used for opening.
+ ID string
+
+ // Index and Term store when the snapshot was taken.
+ Index uint64
+ Term uint64
+
+ // Peers is deprecated and used to support version 0 snapshots, but will
+ // be populated in version 1 snapshots as well to help with upgrades.
+ Peers []byte
+
+ // Configuration and ConfigurationIndex are present in version 1
+ // snapshots and later.
+ Configuration Configuration
+ ConfigurationIndex uint64
+
+ // Size is the size of the snapshot in bytes.
+ Size int64
+}
+
+// SnapshotStore interface is used to allow for flexible implementations
+// of snapshot storage and retrieval. For example, a client could implement
+// a shared state store such as S3, allowing new nodes to restore snapshots
+// without streaming from the leader.
+type SnapshotStore interface {
+ // Create is used to begin a snapshot at a given index and term, and with
+ // the given committed configuration. The version parameter controls
+ // which snapshot version to create.
+ Create(version SnapshotVersion, index, term uint64, configuration Configuration,
+ configurationIndex uint64, trans Transport) (SnapshotSink, error)
+
+ // List is used to list the available snapshots in the store.
+ // It should return then in descending order, with the highest index first.
+ List() ([]*SnapshotMeta, error)
+
+ // Open takes a snapshot ID and provides a ReadCloser. Once close is
+ // called it is assumed the snapshot is no longer needed.
+ Open(id string) (*SnapshotMeta, io.ReadCloser, error)
+}
+
+// SnapshotSink is returned by StartSnapshot. The FSM will Write state
+// to the sink and call Close on completion. On error, Cancel will be invoked.
+type SnapshotSink interface {
+ io.WriteCloser
+ ID() string
+ Cancel() error
+}
+
+// runSnapshots is a long running goroutine used to manage taking
+// new snapshots of the FSM. It runs in parallel to the FSM and
+// main goroutines, so that snapshots do not block normal operation.
+func (r *Raft) runSnapshots() {
+ for {
+ select {
+ case <-randomTimeout(r.conf.SnapshotInterval):
+ // Check if we should snapshot
+ if !r.shouldSnapshot() {
+ continue
+ }
+
+ // Trigger a snapshot
+ if _, err := r.takeSnapshot(); err != nil {
+ r.logger.Error(fmt.Sprintf("Failed to take snapshot: %v", err))
+ }
+
+ case future := <-r.userSnapshotCh:
+ // User-triggered, run immediately
+ id, err := r.takeSnapshot()
+ if err != nil {
+ r.logger.Error(fmt.Sprintf("Failed to take snapshot: %v", err))
+ } else {
+ future.opener = func() (*SnapshotMeta, io.ReadCloser, error) {
+ return r.snapshots.Open(id)
+ }
+ }
+ future.respond(err)
+
+ case <-r.shutdownCh:
+ return
+ }
+ }
+}
+
+// shouldSnapshot checks if we meet the conditions to take
+// a new snapshot.
+func (r *Raft) shouldSnapshot() bool {
+ // Check the last snapshot index
+ lastSnap, _ := r.getLastSnapshot()
+
+ // Check the last log index
+ lastIdx, err := r.logs.LastIndex()
+ if err != nil {
+ r.logger.Error(fmt.Sprintf("Failed to get last log index: %v", err))
+ return false
+ }
+
+ // Compare the delta to the threshold
+ delta := lastIdx - lastSnap
+ return delta >= r.conf.SnapshotThreshold
+}
+
+// takeSnapshot is used to take a new snapshot. This must only be called from
+// the snapshot thread, never the main thread. This returns the ID of the new
+// snapshot, along with an error.
+func (r *Raft) takeSnapshot() (string, error) {
+ defer metrics.MeasureSince([]string{"raft", "snapshot", "takeSnapshot"}, time.Now())
+
+ // Create a request for the FSM to perform a snapshot.
+ snapReq := &reqSnapshotFuture{}
+ snapReq.init()
+
+ // Wait for dispatch or shutdown.
+ select {
+ case r.fsmSnapshotCh <- snapReq:
+ case <-r.shutdownCh:
+ return "", ErrRaftShutdown
+ }
+
+ // Wait until we get a response
+ if err := snapReq.Error(); err != nil {
+ if err != ErrNothingNewToSnapshot {
+ err = fmt.Errorf("failed to start snapshot: %v", err)
+ }
+ return "", err
+ }
+ defer snapReq.snapshot.Release()
+
+ // Make a request for the configurations and extract the committed info.
+ // We have to use the future here to safely get this information since
+ // it is owned by the main thread.
+ configReq := &configurationsFuture{}
+ configReq.init()
+ select {
+ case r.configurationsCh <- configReq:
+ case <-r.shutdownCh:
+ return "", ErrRaftShutdown
+ }
+ if err := configReq.Error(); err != nil {
+ return "", err
+ }
+ committed := configReq.configurations.committed
+ committedIndex := configReq.configurations.committedIndex
+
+ // We don't support snapshots while there's a config change outstanding
+ // since the snapshot doesn't have a means to represent this state. This
+ // is a little weird because we need the FSM to apply an index that's
+ // past the configuration change, even though the FSM itself doesn't see
+ // the configuration changes. It should be ok in practice with normal
+ // application traffic flowing through the FSM. If there's none of that
+ // then it's not crucial that we snapshot, since there's not much going
+ // on Raft-wise.
+ if snapReq.index < committedIndex {
+ return "", fmt.Errorf("cannot take snapshot now, wait until the configuration entry at %v has been applied (have applied %v)",
+ committedIndex, snapReq.index)
+ }
+
+ // Create a new snapshot.
+ r.logger.Info(fmt.Sprintf("Starting snapshot up to %d", snapReq.index))
+ start := time.Now()
+ version := getSnapshotVersion(r.protocolVersion)
+ sink, err := r.snapshots.Create(version, snapReq.index, snapReq.term, committed, committedIndex, r.trans)
+ if err != nil {
+ return "", fmt.Errorf("failed to create snapshot: %v", err)
+ }
+ metrics.MeasureSince([]string{"raft", "snapshot", "create"}, start)
+
+ // Try to persist the snapshot.
+ start = time.Now()
+ if err := snapReq.snapshot.Persist(sink); err != nil {
+ sink.Cancel()
+ return "", fmt.Errorf("failed to persist snapshot: %v", err)
+ }
+ metrics.MeasureSince([]string{"raft", "snapshot", "persist"}, start)
+
+ // Close and check for error.
+ if err := sink.Close(); err != nil {
+ return "", fmt.Errorf("failed to close snapshot: %v", err)
+ }
+
+ // Update the last stable snapshot info.
+ r.setLastSnapshot(snapReq.index, snapReq.term)
+
+ // Compact the logs.
+ if err := r.compactLogs(snapReq.index); err != nil {
+ return "", err
+ }
+
+ r.logger.Info(fmt.Sprintf("Snapshot to %d complete", snapReq.index))
+ return sink.ID(), nil
+}
+
+// compactLogs takes the last inclusive index of a snapshot
+// and trims the logs that are no longer needed.
+func (r *Raft) compactLogs(snapIdx uint64) error {
+ defer metrics.MeasureSince([]string{"raft", "compactLogs"}, time.Now())
+ // Determine log ranges to compact
+ minLog, err := r.logs.FirstIndex()
+ if err != nil {
+ return fmt.Errorf("failed to get first log index: %v", err)
+ }
+
+ // Check if we have enough logs to truncate
+ lastLogIdx, _ := r.getLastLog()
+ if lastLogIdx <= r.conf.TrailingLogs {
+ return nil
+ }
+
+ // Truncate up to the end of the snapshot, or `TrailingLogs`
+ // back from the head, which ever is further back. This ensures
+ // at least `TrailingLogs` entries, but does not allow logs
+ // after the snapshot to be removed.
+ maxLog := min(snapIdx, lastLogIdx-r.conf.TrailingLogs)
+
+ // Log this
+ r.logger.Info(fmt.Sprintf("Compacting logs from %d to %d", minLog, maxLog))
+
+ // Compact the logs
+ if err := r.logs.DeleteRange(minLog, maxLog); err != nil {
+ return fmt.Errorf("log compaction failed: %v", err)
+ }
+ return nil
+}
diff -Naur --color b/vendor/github.com/hashicorp/raft/stable.go a/vendor/github.com/hashicorp/raft/stable.go
--- b/vendor/github.com/hashicorp/raft/stable.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/stable.go 2022-11-15 23:06:31.568724593 +0100
@@ -0,0 +1,15 @@
+package raft
+
+// StableStore is used to provide stable storage
+// of key configurations to ensure safety.
+type StableStore interface {
+ Set(key []byte, val []byte) error
+
+ // Get returns the value for key, or an empty byte slice if key was not found.
+ Get(key []byte) ([]byte, error)
+
+ SetUint64(key []byte, val uint64) error
+
+ // GetUint64 returns the uint64 value for key, or 0 if key was not found.
+ GetUint64(key []byte) (uint64, error)
+}
diff -Naur --color b/vendor/github.com/hashicorp/raft/state.go a/vendor/github.com/hashicorp/raft/state.go
--- b/vendor/github.com/hashicorp/raft/state.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/state.go 2022-11-15 23:06:31.568724593 +0100
@@ -0,0 +1,171 @@
+package raft
+
+import (
+ "sync"
+ "sync/atomic"
+)
+
+// RaftState captures the state of a Raft node: Follower, Candidate, Leader,
+// or Shutdown.
+type RaftState uint32
+
+const (
+ // Follower is the initial state of a Raft node.
+ Follower RaftState = iota
+
+ // Candidate is one of the valid states of a Raft node.
+ Candidate
+
+ // Leader is one of the valid states of a Raft node.
+ Leader
+
+ // Shutdown is the terminal state of a Raft node.
+ Shutdown
+)
+
+func (s RaftState) String() string {
+ switch s {
+ case Follower:
+ return "Follower"
+ case Candidate:
+ return "Candidate"
+ case Leader:
+ return "Leader"
+ case Shutdown:
+ return "Shutdown"
+ default:
+ return "Unknown"
+ }
+}
+
+// raftState is used to maintain various state variables
+// and provides an interface to set/get the variables in a
+// thread safe manner.
+type raftState struct {
+ // currentTerm commitIndex, lastApplied, must be kept at the top of
+ // the struct so they're 64 bit aligned which is a requirement for
+ // atomic ops on 32 bit platforms.
+
+ // The current term, cache of StableStore
+ currentTerm uint64
+
+ // Highest committed log entry
+ commitIndex uint64
+
+ // Last applied log to the FSM
+ lastApplied uint64
+
+ // protects 4 next fields
+ lastLock sync.Mutex
+
+ // Cache the latest snapshot index/term
+ lastSnapshotIndex uint64
+ lastSnapshotTerm uint64
+
+ // Cache the latest log from LogStore
+ lastLogIndex uint64
+ lastLogTerm uint64
+
+ // Tracks running goroutines
+ routinesGroup sync.WaitGroup
+
+ // The current state
+ state RaftState
+}
+
+func (r *raftState) getState() RaftState {
+ stateAddr := (*uint32)(&r.state)
+ return RaftState(atomic.LoadUint32(stateAddr))
+}
+
+func (r *raftState) setState(s RaftState) {
+ stateAddr := (*uint32)(&r.state)
+ atomic.StoreUint32(stateAddr, uint32(s))
+}
+
+func (r *raftState) getCurrentTerm() uint64 {
+ return atomic.LoadUint64(&r.currentTerm)
+}
+
+func (r *raftState) setCurrentTerm(term uint64) {
+ atomic.StoreUint64(&r.currentTerm, term)
+}
+
+func (r *raftState) getLastLog() (index, term uint64) {
+ r.lastLock.Lock()
+ index = r.lastLogIndex
+ term = r.lastLogTerm
+ r.lastLock.Unlock()
+ return
+}
+
+func (r *raftState) setLastLog(index, term uint64) {
+ r.lastLock.Lock()
+ r.lastLogIndex = index
+ r.lastLogTerm = term
+ r.lastLock.Unlock()
+}
+
+func (r *raftState) getLastSnapshot() (index, term uint64) {
+ r.lastLock.Lock()
+ index = r.lastSnapshotIndex
+ term = r.lastSnapshotTerm
+ r.lastLock.Unlock()
+ return
+}
+
+func (r *raftState) setLastSnapshot(index, term uint64) {
+ r.lastLock.Lock()
+ r.lastSnapshotIndex = index
+ r.lastSnapshotTerm = term
+ r.lastLock.Unlock()
+}
+
+func (r *raftState) getCommitIndex() uint64 {
+ return atomic.LoadUint64(&r.commitIndex)
+}
+
+func (r *raftState) setCommitIndex(index uint64) {
+ atomic.StoreUint64(&r.commitIndex, index)
+}
+
+func (r *raftState) getLastApplied() uint64 {
+ return atomic.LoadUint64(&r.lastApplied)
+}
+
+func (r *raftState) setLastApplied(index uint64) {
+ atomic.StoreUint64(&r.lastApplied, index)
+}
+
+// Start a goroutine and properly handle the race between a routine
+// starting and incrementing, and exiting and decrementing.
+func (r *raftState) goFunc(f func()) {
+ r.routinesGroup.Add(1)
+ go func() {
+ defer r.routinesGroup.Done()
+ f()
+ }()
+}
+
+func (r *raftState) waitShutdown() {
+ r.routinesGroup.Wait()
+}
+
+// getLastIndex returns the last index in stable storage.
+// Either from the last log or from the last snapshot.
+func (r *raftState) getLastIndex() uint64 {
+ r.lastLock.Lock()
+ defer r.lastLock.Unlock()
+ return max(r.lastLogIndex, r.lastSnapshotIndex)
+}
+
+// getLastEntry returns the last index and term in stable storage.
+// Either from the last log or from the last snapshot.
+func (r *raftState) getLastEntry() (uint64, uint64) {
+ r.lastLock.Lock()
+ defer r.lastLock.Unlock()
+ if r.lastLogIndex >= r.lastSnapshotIndex {
+ return r.lastLogIndex, r.lastLogTerm
+ }
+ return r.lastSnapshotIndex, r.lastSnapshotTerm
+}
diff -Naur --color b/vendor/github.com/hashicorp/raft/tag.sh a/vendor/github.com/hashicorp/raft/tag.sh
--- b/vendor/github.com/hashicorp/raft/tag.sh 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/tag.sh 2022-11-15 23:06:31.568724593 +0100
@@ -0,0 +1,16 @@
+#!/usr/bin/env bash
+set -e
+
+# The version must be supplied from the environment. Do not include the
+# leading "v".
+if [ -z $VERSION ]; then
+ echo "Please specify a version."
+ exit 1
+fi
+
+# Generate the tag.
+echo "==> Tagging version $VERSION..."
+git commit --allow-empty -a --gpg-sign=348FFC4C -m "Release v$VERSION"
+git tag -a -m "Version $VERSION" -s -u 348FFC4C "v${VERSION}" master
+
+exit 0
diff -Naur --color b/vendor/github.com/hashicorp/raft/tcp_transport.go a/vendor/github.com/hashicorp/raft/tcp_transport.go
--- b/vendor/github.com/hashicorp/raft/tcp_transport.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/tcp_transport.go 2022-11-15 23:06:31.568724593 +0100
@@ -0,0 +1,116 @@
+package raft
+
+import (
+ "errors"
+ "io"
+ "log"
+ "net"
+ "time"
+)
+
+var (
+ errNotAdvertisable = errors.New("local bind address is not advertisable")
+ errNotTCP = errors.New("local address is not a TCP address")
+)
+
+// TCPStreamLayer implements StreamLayer interface for plain TCP.
+type TCPStreamLayer struct {
+ advertise net.Addr
+ listener *net.TCPListener
+}
+
+// NewTCPTransport returns a NetworkTransport that is built on top of
+// a TCP streaming transport layer.
+func NewTCPTransport(
+ bindAddr string,
+ advertise net.Addr,
+ maxPool int,
+ timeout time.Duration,
+ logOutput io.Writer,
+) (*NetworkTransport, error) {
+ return newTCPTransport(bindAddr, advertise, func(stream StreamLayer) *NetworkTransport {
+ return NewNetworkTransport(stream, maxPool, timeout, logOutput)
+ })
+}
+
+// NewTCPTransportWithLogger returns a NetworkTransport that is built on top of
+// a TCP streaming transport layer, with log output going to the supplied Logger
+func NewTCPTransportWithLogger(
+ bindAddr string,
+ advertise net.Addr,
+ maxPool int,
+ timeout time.Duration,
+ logger *log.Logger,
+) (*NetworkTransport, error) {
+ return newTCPTransport(bindAddr, advertise, func(stream StreamLayer) *NetworkTransport {
+ return NewNetworkTransportWithLogger(stream, maxPool, timeout, logger)
+ })
+}
+
+// NewTCPTransportWithConfig returns a NetworkTransport that is built on top of
+// a TCP streaming transport layer, using the given config struct.
+func NewTCPTransportWithConfig(
+ bindAddr string,
+ advertise net.Addr,
+ config *NetworkTransportConfig,
+) (*NetworkTransport, error) {
+ return newTCPTransport(bindAddr, advertise, func(stream StreamLayer) *NetworkTransport {
+ config.Stream = stream
+ return NewNetworkTransportWithConfig(config)
+ })
+}
+
+func newTCPTransport(bindAddr string,
+ advertise net.Addr,
+ transportCreator func(stream StreamLayer) *NetworkTransport) (*NetworkTransport, error) {
+ // Try to bind
+ list, err := net.Listen("tcp", bindAddr)
+ if err != nil {
+ return nil, err
+ }
+
+ // Create stream
+ stream := &TCPStreamLayer{
+ advertise: advertise,
+ listener: list.(*net.TCPListener),
+ }
+
+ // Verify that we have a usable advertise address
+ addr, ok := stream.Addr().(*net.TCPAddr)
+ if !ok {
+ list.Close()
+ return nil, errNotTCP
+ }
+ if addr.IP.IsUnspecified() {
+ list.Close()
+ return nil, errNotAdvertisable
+ }
+
+ // Create the network transport
+ trans := transportCreator(stream)
+ return trans, nil
+}
+
+// Dial implements the StreamLayer interface.
+func (t *TCPStreamLayer) Dial(address ServerAddress, timeout time.Duration) (net.Conn, error) {
+ return net.DialTimeout("tcp", string(address), timeout)
+}
+
+// Accept implements the net.Listener interface.
+func (t *TCPStreamLayer) Accept() (c net.Conn, err error) {
+ return t.listener.Accept()
+}
+
+// Close implements the net.Listener interface.
+func (t *TCPStreamLayer) Close() (err error) {
+ return t.listener.Close()
+}
+
+// Addr implements the net.Listener interface.
+func (t *TCPStreamLayer) Addr() net.Addr {
+ // Use an advertise addr if provided
+ if t.advertise != nil {
+ return t.advertise
+ }
+ return t.listener.Addr()
+}
diff -Naur --color b/vendor/github.com/hashicorp/raft/testing.go a/vendor/github.com/hashicorp/raft/testing.go
--- b/vendor/github.com/hashicorp/raft/testing.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/testing.go 2022-11-15 23:06:31.568724593 +0100
@@ -0,0 +1,799 @@
+package raft
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "log"
+ "os"
+ "reflect"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/hashicorp/go-hclog"
+ "github.com/hashicorp/go-msgpack/codec"
+)
+
+// Return configurations optimized for in-memory
+func inmemConfig(t *testing.T) *Config {
+ conf := DefaultConfig()
+ conf.HeartbeatTimeout = 50 * time.Millisecond
+ conf.ElectionTimeout = 50 * time.Millisecond
+ conf.LeaderLeaseTimeout = 50 * time.Millisecond
+ conf.CommitTimeout = 5 * time.Millisecond
+ conf.Logger = newTestLeveledLogger(t)
+ return conf
+}
+
+// MockFSM is an implementation of the FSM interface, and just stores
+// the logs sequentially.
+//
+// NOTE: This is exposed for middleware testing purposes and is not a stable API
+type MockFSM struct {
+ sync.Mutex
+ logs [][]byte
+ configurations []Configuration
+}
+
+// NOTE: This is exposed for middleware testing purposes and is not a stable API
+type MockFSMConfigStore struct {
+ FSM
+}
+
+// NOTE: This is exposed for middleware testing purposes and is not a stable API
+type WrappingFSM interface {
+ Underlying() FSM
+}
+
+func getMockFSM(fsm FSM) *MockFSM {
+ switch f := fsm.(type) {
+ case *MockFSM:
+ return f
+ case *MockFSMConfigStore:
+ return f.FSM.(*MockFSM)
+ case WrappingFSM:
+ return getMockFSM(f.Underlying())
+ }
+
+ return nil
+}
+
+// NOTE: This is exposed for middleware testing purposes and is not a stable API
+type MockSnapshot struct {
+ logs [][]byte
+ maxIndex int
+}
+
+var _ ConfigurationStore = (*MockFSMConfigStore)(nil)
+
+// NOTE: This is exposed for middleware testing purposes and is not a stable API
+func (m *MockFSM) Apply(log *Log) interface{} {
+ m.Lock()
+ defer m.Unlock()
+ m.logs = append(m.logs, log.Data)
+ return len(m.logs)
+}
+
+// NOTE: This is exposed for middleware testing purposes and is not a stable API
+func (m *MockFSM) Snapshot() (FSMSnapshot, error) {
+ m.Lock()
+ defer m.Unlock()
+ return &MockSnapshot{m.logs, len(m.logs)}, nil
+}
+
+// NOTE: This is exposed for middleware testing purposes and is not a stable API
+func (m *MockFSM) Restore(inp io.ReadCloser) error {
+ m.Lock()
+ defer m.Unlock()
+ defer inp.Close()
+ hd := codec.MsgpackHandle{}
+ dec := codec.NewDecoder(inp, &hd)
+
+ m.logs = nil
+ return dec.Decode(&m.logs)
+}
+
+// NOTE: This is exposed for middleware testing purposes and is not a stable API
+func (m *MockFSM) Logs() [][]byte {
+ m.Lock()
+ defer m.Unlock()
+ return m.logs
+}
+
+// NOTE: This is exposed for middleware testing purposes and is not a stable API
+func (m *MockFSMConfigStore) StoreConfiguration(index uint64, config Configuration) {
+ mm := m.FSM.(*MockFSM)
+ mm.Lock()
+ defer mm.Unlock()
+ mm.configurations = append(mm.configurations, config)
+}
+
+// NOTE: This is exposed for middleware testing purposes and is not a stable API
+func (m *MockSnapshot) Persist(sink SnapshotSink) error {
+ hd := codec.MsgpackHandle{}
+ enc := codec.NewEncoder(sink, &hd)
+ if err := enc.Encode(m.logs[:m.maxIndex]); err != nil {
+ sink.Cancel()
+ return err
+ }
+ sink.Close()
+ return nil
+}
+
+// NOTE: This is exposed for middleware testing purposes and is not a stable API
+func (m *MockSnapshot) Release() {
+}
+
+// This can be used as the destination for a logger and it'll
+// map them into calls to testing.T.Log, so that you only see
+// the logging for failed tests.
+type testLoggerAdapter struct {
+ t *testing.T
+ prefix string
+}
+
+func (a *testLoggerAdapter) Write(d []byte) (int, error) {
+ if d[len(d)-1] == '\n' {
+ d = d[:len(d)-1]
+ }
+ if a.prefix != "" {
+ l := a.prefix + ": " + string(d)
+ if testing.Verbose() {
+ fmt.Printf("testLoggerAdapter verbose: %s\n", l)
+ }
+ a.t.Log(l)
+ return len(l), nil
+ }
+
+ a.t.Log(string(d))
+ return len(d), nil
+}
+
+func newTestLogger(t *testing.T) *log.Logger {
+ return log.New(&testLoggerAdapter{t: t}, "", log.Lmicroseconds)
+}
+
+func newTestLoggerWithPrefix(t *testing.T, prefix string) *log.Logger {
+ return log.New(&testLoggerAdapter{t: t, prefix: prefix}, "", log.Lmicroseconds)
+}
+
+func newTestLeveledLogger(t *testing.T) hclog.Logger {
+ return hclog.New(&hclog.LoggerOptions{
+ Name: "",
+ Output: &testLoggerAdapter{t: t},
+ })
+}
+
+func newTestLeveledLoggerWithPrefix(t *testing.T, prefix string) hclog.Logger {
+ return hclog.New(&hclog.LoggerOptions{
+ Name: prefix,
+ Output: &testLoggerAdapter{t: t, prefix: prefix},
+ })
+}
+
+type cluster struct {
+ dirs []string
+ stores []*InmemStore
+ fsms []FSM
+ snaps []*FileSnapshotStore
+ trans []LoopbackTransport
+ rafts []*Raft
+ t *testing.T
+ observationCh chan Observation
+ conf *Config
+ propagateTimeout time.Duration
+ longstopTimeout time.Duration
+ logger *log.Logger
+ startTime time.Time
+
+ failedLock sync.Mutex
+ failedCh chan struct{}
+ failed bool
+}
+
+func (c *cluster) Merge(other *cluster) {
+ c.dirs = append(c.dirs, other.dirs...)
+ c.stores = append(c.stores, other.stores...)
+ c.fsms = append(c.fsms, other.fsms...)
+ c.snaps = append(c.snaps, other.snaps...)
+ c.trans = append(c.trans, other.trans...)
+ c.rafts = append(c.rafts, other.rafts...)
+}
+
+// notifyFailed will close the failed channel which can signal the goroutine
+// running the test that another goroutine has detected a failure in order to
+// terminate the test.
+func (c *cluster) notifyFailed() {
+ c.failedLock.Lock()
+ defer c.failedLock.Unlock()
+ if !c.failed {
+ c.failed = true
+ close(c.failedCh)
+ }
+}
+
+// Failf provides a logging function that fails the tests, prints the output
+// with microseconds, and does not mysteriously eat the string. This can be
+// safely called from goroutines but won't immediately halt the test. The
+// failedCh will be closed to allow blocking functions in the main thread to
+// detect the failure and react. Note that you should arrange for the main
+// thread to block until all goroutines have completed in order to reliably
+// fail tests using this function.
+func (c *cluster) Failf(format string, args ...interface{}) {
+ c.logger.Printf(format, args...)
+ c.t.Fail()
+ c.notifyFailed()
+}
+
+// FailNowf provides a logging function that fails the tests, prints the output
+// with microseconds, and does not mysteriously eat the string. FailNowf must be
+// called from the goroutine running the test or benchmark function, not from
+// other goroutines created during the test. Calling FailNowf does not stop
+// those other goroutines.
+func (c *cluster) FailNowf(format string, args ...interface{}) {
+ c.logger.Printf(format, args...)
+ c.t.FailNow()
+}
+
+// Close shuts down the cluster and cleans up.
+func (c *cluster) Close() {
+ var futures []Future
+ for _, r := range c.rafts {
+ futures = append(futures, r.Shutdown())
+ }
+
+ // Wait for shutdown
+ limit := time.AfterFunc(c.longstopTimeout, func() {
+ // We can't FailNowf here, and c.Failf won't do anything if we
+ // hang, so panic.
+ panic("timed out waiting for shutdown")
+ })
+ defer limit.Stop()
+
+ for _, f := range futures {
+ if err := f.Error(); err != nil {
+ c.FailNowf("[ERR] shutdown future err: %v", err)
+ }
+ }
+
+ for _, d := range c.dirs {
+ os.RemoveAll(d)
+ }
+}
+
+// WaitEventChan returns a channel which will signal if an observation is made
+// or a timeout occurs. It is possible to set a filter to look for specific
+// observations. Setting timeout to 0 means that it will wait forever until a
+// non-filtered observation is made.
+func (c *cluster) WaitEventChan(filter FilterFn, timeout time.Duration) <-chan struct{} {
+ ch := make(chan struct{})
+ go func() {
+ defer close(ch)
+ var timeoutCh <-chan time.Time
+ if timeout > 0 {
+ timeoutCh = time.After(timeout)
+ }
+ for {
+ select {
+ case <-timeoutCh:
+ return
+
+ case o, ok := <-c.observationCh:
+ if !ok || filter == nil || filter(&o) {
+ return
+ }
+ }
+ }
+ }()
+ return ch
+}
+
+// WaitEvent waits until an observation is made, a timeout occurs, or a test
+// failure is signaled. It is possible to set a filter to look for specific
+// observations. Setting timeout to 0 means that it will wait forever until a
+// non-filtered observation is made or a test failure is signaled.
+func (c *cluster) WaitEvent(filter FilterFn, timeout time.Duration) {
+ select {
+ case <-c.failedCh:
+ c.t.FailNow()
+
+ case <-c.WaitEventChan(filter, timeout):
+ }
+}
+
+// WaitForReplication blocks until every FSM in the cluster has the given
+// length, or the long sanity check timeout expires.
+func (c *cluster) WaitForReplication(fsmLength int) {
+ limitCh := time.After(c.longstopTimeout)
+
+CHECK:
+ for {
+ ch := c.WaitEventChan(nil, c.conf.CommitTimeout)
+ select {
+ case <-c.failedCh:
+ c.t.FailNow()
+
+ case <-limitCh:
+ c.FailNowf("[ERR] Timeout waiting for replication")
+
+ case <-ch:
+ for _, fsmRaw := range c.fsms {
+ fsm := getMockFSM(fsmRaw)
+ fsm.Lock()
+ num := len(fsm.logs)
+ fsm.Unlock()
+ if num != fsmLength {
+ continue CHECK
+ }
+ }
+ return
+ }
+ }
+}
+
+// pollState takes a snapshot of the state of the cluster. This might not be
+// stable, so use GetInState() to apply some additional checks when waiting
+// for the cluster to achieve a particular state.
+func (c *cluster) pollState(s RaftState) ([]*Raft, uint64) {
+ var highestTerm uint64
+ in := make([]*Raft, 0, 1)
+ for _, r := range c.rafts {
+ if r.State() == s {
+ in = append(in, r)
+ }
+ term := r.getCurrentTerm()
+ if term > highestTerm {
+ highestTerm = term
+ }
+ }
+ return in, highestTerm
+}
+
+// GetInState polls the state of the cluster and attempts to identify when it has
+// settled into the given state.
+func (c *cluster) GetInState(s RaftState) []*Raft {
+ c.logger.Printf("[INFO] Starting stability test for raft state: %+v", s)
+ limitCh := time.After(c.longstopTimeout)
+
+ // An election should complete after 2 * max(HeartbeatTimeout, ElectionTimeout)
+ // because of the randomised timer expiring in 1 x interval ... 2 x interval.
+ // We add a bit for propagation delay. If the election fails (e.g. because
+ // two elections start at once), we will have got something through our
+ // observer channel indicating a different state (i.e. one of the nodes
+ // will have moved to candidate state) which will reset the timer.
+ //
+ // Because of an implementation peculiarity, it can actually be 3 x timeout.
+ timeout := c.conf.HeartbeatTimeout
+ if timeout < c.conf.ElectionTimeout {
+ timeout = c.conf.ElectionTimeout
+ }
+ timeout = 2*timeout + c.conf.CommitTimeout
+ timer := time.NewTimer(timeout)
+ defer timer.Stop()
+
+ // Wait until we have a stable instate slice. Each time we see an
+ // observation a state has changed, recheck it and if it has changed,
+ // restart the timer.
+ var pollStartTime = time.Now()
+ for {
+ inState, highestTerm := c.pollState(s)
+ inStateTime := time.Now()
+
+ // Sometimes this routine is called very early on before the
+ // rafts have started up. We then timeout even though no one has
+ // even started an election. So if the highest term in use is
+ // zero, we know there are no raft processes that have yet issued
+ // a RequestVote, and we set a long time out. This is fixed when
+ // we hear the first RequestVote, at which point we reset the
+ // timer.
+ if highestTerm == 0 {
+ timer.Reset(c.longstopTimeout)
+ } else {
+ timer.Reset(timeout)
+ }
+
+ // Filter will wake up whenever we observe a RequestVote.
+ filter := func(ob *Observation) bool {
+ switch ob.Data.(type) {
+ case RaftState:
+ return true
+ case RequestVoteRequest:
+ return true
+ default:
+ return false
+ }
+ }
+
+ select {
+ case <-c.failedCh:
+ c.t.FailNow()
+
+ case <-limitCh:
+ c.FailNowf("[ERR] Timeout waiting for stable %s state", s)
+
+ case <-c.WaitEventChan(filter, 0):
+ c.logger.Printf("[DEBUG] Resetting stability timeout")
+
+ case t, ok := <-timer.C:
+ if !ok {
+ c.FailNowf("[ERR] Timer channel errored")
+ }
+ c.logger.Printf("[INFO] Stable state for %s reached at %s (%d nodes), %s from start of poll, %s from cluster start. Timeout at %s, %s after stability",
+ s, inStateTime, len(inState), inStateTime.Sub(pollStartTime), inStateTime.Sub(c.startTime), t, t.Sub(inStateTime))
+ return inState
+ }
+ }
+}
+
+// Leader waits for the cluster to elect a leader and stay in a stable state.
+func (c *cluster) Leader() *Raft {
+ leaders := c.GetInState(Leader)
+ if len(leaders) != 1 {
+ c.FailNowf("[ERR] expected one leader: %v", leaders)
+ }
+ return leaders[0]
+}
+
+// Followers waits for the cluster to have N-1 followers and stay in a stable
+// state.
+func (c *cluster) Followers() []*Raft {
+ expFollowers := len(c.rafts) - 1
+ followers := c.GetInState(Follower)
+ if len(followers) != expFollowers {
+ c.FailNowf("[ERR] timeout waiting for %d followers (followers are %v)", expFollowers, followers)
+ }
+ return followers
+}
+
+// FullyConnect connects all the transports together.
+func (c *cluster) FullyConnect() {
+ c.logger.Printf("[DEBUG] Fully Connecting")
+ for i, t1 := range c.trans {
+ for j, t2 := range c.trans {
+ if i != j {
+ t1.Connect(t2.LocalAddr(), t2)
+ t2.Connect(t1.LocalAddr(), t1)
+ }
+ }
+ }
+}
+
+// Disconnect disconnects all transports from the given address.
+func (c *cluster) Disconnect(a ServerAddress) {
+ c.logger.Printf("[DEBUG] Disconnecting %v", a)
+ for _, t := range c.trans {
+ if t.LocalAddr() == a {
+ t.DisconnectAll()
+ } else {
+ t.Disconnect(a)
+ }
+ }
+}
+
+// Partition keeps the given list of addresses connected but isolates them
+// from the other members of the cluster.
+func (c *cluster) Partition(far []ServerAddress) {
+ c.logger.Printf("[DEBUG] Partitioning %v", far)
+
+ // Gather the set of nodes on the "near" side of the partition (we
+ // will call the supplied list of nodes the "far" side).
+ near := make(map[ServerAddress]struct{})
+OUTER:
+ for _, t := range c.trans {
+ l := t.LocalAddr()
+ for _, a := range far {
+ if l == a {
+ continue OUTER
+ }
+ }
+ near[l] = struct{}{}
+ }
+
+ // Now fixup all the connections. The near side will be separated from
+ // the far side, and vice-versa.
+ for _, t := range c.trans {
+ l := t.LocalAddr()
+ if _, ok := near[l]; ok {
+ for _, a := range far {
+ t.Disconnect(a)
+ }
+ } else {
+ for a, _ := range near {
+ t.Disconnect(a)
+ }
+ }
+ }
+}
+
+// IndexOf returns the index of the given raft instance.
+func (c *cluster) IndexOf(r *Raft) int {
+ for i, n := range c.rafts {
+ if n == r {
+ return i
+ }
+ }
+ return -1
+}
+
+// EnsureLeader checks that ALL the nodes think the leader is the given expected
+// leader.
+func (c *cluster) EnsureLeader(t *testing.T, expect ServerAddress) {
+ // We assume c.Leader() has been called already; now check all the rafts
+ // think the leader is correct
+ fail := false
+ for _, r := range c.rafts {
+ leader := ServerAddress(r.Leader())
+ if leader != expect {
+ if leader == "" {
+ leader = "[none]"
+ }
+ if expect == "" {
+ c.logger.Printf("[ERR] Peer %s sees leader %v expected [none]", r, leader)
+ } else {
+ c.logger.Printf("[ERR] Peer %s sees leader %v expected %v", r, leader, expect)
+ }
+ fail = true
+ }
+ }
+ if fail {
+ c.FailNowf("[ERR] At least one peer has the wrong notion of leader")
+ }
+}
+
+// EnsureSame makes sure all the FSMs have the same contents.
+func (c *cluster) EnsureSame(t *testing.T) {
+ limit := time.Now().Add(c.longstopTimeout)
+ first := getMockFSM(c.fsms[0])
+
+CHECK:
+ first.Lock()
+ for i, fsmRaw := range c.fsms {
+ fsm := getMockFSM(fsmRaw)
+ if i == 0 {
+ continue
+ }
+ fsm.Lock()
+
+ if len(first.logs) != len(fsm.logs) {
+ fsm.Unlock()
+ if time.Now().After(limit) {
+ c.FailNowf("[ERR] FSM log length mismatch: %d %d",
+ len(first.logs), len(fsm.logs))
+ } else {
+ goto WAIT
+ }
+ }
+
+ for idx := 0; idx < len(first.logs); idx++ {
+ if bytes.Compare(first.logs[idx], fsm.logs[idx]) != 0 {
+ fsm.Unlock()
+ if time.Now().After(limit) {
+ c.FailNowf("[ERR] FSM log mismatch at index %d", idx)
+ } else {
+ goto WAIT
+ }
+ }
+ }
+ if len(first.configurations) != len(fsm.configurations) {
+ fsm.Unlock()
+ if time.Now().After(limit) {
+ c.FailNowf("[ERR] FSM configuration length mismatch: %d %d",
+ len(first.logs), len(fsm.logs))
+ } else {
+ goto WAIT
+ }
+ }
+
+ for idx := 0; idx < len(first.configurations); idx++ {
+ if !reflect.DeepEqual(first.configurations[idx], fsm.configurations[idx]) {
+ fsm.Unlock()
+ if time.Now().After(limit) {
+ c.FailNowf("[ERR] FSM configuration mismatch at index %d: %v, %v", idx, first.configurations[idx], fsm.configurations[idx])
+ } else {
+ goto WAIT
+ }
+ }
+ }
+ fsm.Unlock()
+ }
+
+ first.Unlock()
+ return
+
+WAIT:
+ first.Unlock()
+ c.WaitEvent(nil, c.conf.CommitTimeout)
+ goto CHECK
+}
+
+// getConfiguration returns the configuration of the given Raft instance, or
+// fails the test if there's an error
+func (c *cluster) getConfiguration(r *Raft) Configuration {
+ future := r.GetConfiguration()
+ if err := future.Error(); err != nil {
+ c.FailNowf("[ERR] failed to get configuration: %v", err)
+ return Configuration{}
+ }
+
+ return future.Configuration()
+}
+
+// EnsureSamePeers makes sure all the rafts have the same set of peers.
+func (c *cluster) EnsureSamePeers(t *testing.T) {
+ limit := time.Now().Add(c.longstopTimeout)
+ peerSet := c.getConfiguration(c.rafts[0])
+
+CHECK:
+ for i, raft := range c.rafts {
+ if i == 0 {
+ continue
+ }
+
+ otherSet := c.getConfiguration(raft)
+ if !reflect.DeepEqual(peerSet, otherSet) {
+ if time.Now().After(limit) {
+ c.FailNowf("[ERR] peer mismatch: %+v %+v", peerSet, otherSet)
+ } else {
+ goto WAIT
+ }
+ }
+ }
+ return
+
+WAIT:
+ c.WaitEvent(nil, c.conf.CommitTimeout)
+ goto CHECK
+}
+
+// NOTE: This is exposed for middleware testing purposes and is not a stable API
+type MakeClusterOpts struct {
+ Peers int
+ Bootstrap bool
+ Conf *Config
+ ConfigStoreFSM bool
+ MakeFSMFunc func() FSM
+ LongstopTimeout time.Duration
+}
+
+// makeCluster will return a cluster with the given config and number of peers.
+// If bootstrap is true, the servers will know about each other before starting,
+// otherwise their transports will be wired up but they won't yet have configured
+// each other.
+func makeCluster(t *testing.T, opts *MakeClusterOpts) *cluster {
+ if opts.Conf == nil {
+ opts.Conf = inmemConfig(t)
+ }
+
+ c := &cluster{
+ observationCh: make(chan Observation, 1024),
+ conf: opts.Conf,
+ // Propagation takes a maximum of 2 heartbeat timeouts (time to
+ // get a new heartbeat that would cause a commit) plus a bit.
+ propagateTimeout: opts.Conf.HeartbeatTimeout*2 + opts.Conf.CommitTimeout,
+ longstopTimeout: 5 * time.Second,
+ logger: newTestLoggerWithPrefix(t, "cluster"),
+ failedCh: make(chan struct{}),
+ }
+ if opts.LongstopTimeout > 0 {
+ c.longstopTimeout = opts.LongstopTimeout
+ }
+
+ c.t = t
+ var configuration Configuration
+
+ // Setup the stores and transports
+ for i := 0; i < opts.Peers; i++ {
+ dir, err := ioutil.TempDir("", "raft")
+ if err != nil {
+ c.FailNowf("[ERR] err: %v ", err)
+ }
+
+ store := NewInmemStore()
+ c.dirs = append(c.dirs, dir)
+ c.stores = append(c.stores, store)
+ if opts.ConfigStoreFSM {
+ c.fsms = append(c.fsms, &MockFSMConfigStore{
+ FSM: &MockFSM{},
+ })
+ } else {
+ var fsm FSM
+ if opts.MakeFSMFunc != nil {
+ fsm = opts.MakeFSMFunc()
+ } else {
+ fsm = &MockFSM{}
+ }
+ c.fsms = append(c.fsms, fsm)
+ }
+
+ dir2, snap := FileSnapTest(t)
+ c.dirs = append(c.dirs, dir2)
+ c.snaps = append(c.snaps, snap)
+
+ addr, trans := NewInmemTransport("")
+ c.trans = append(c.trans, trans)
+ localID := ServerID(fmt.Sprintf("server-%s", addr))
+ if opts.Conf.ProtocolVersion < 3 {
+ localID = ServerID(addr)
+ }
+ configuration.Servers = append(configuration.Servers, Server{
+ Suffrage: Voter,
+ ID: localID,
+ Address: addr,
+ })
+ }
+
+ // Wire the transports together
+ c.FullyConnect()
+
+ // Create all the rafts
+ c.startTime = time.Now()
+ for i := 0; i < opts.Peers; i++ {
+ logs := c.stores[i]
+ store := c.stores[i]
+ snap := c.snaps[i]
+ trans := c.trans[i]
+
+ peerConf := opts.Conf
+ peerConf.LocalID = configuration.Servers[i].ID
+ peerConf.Logger = newTestLeveledLoggerWithPrefix(t, string(configuration.Servers[i].ID))
+
+ if opts.Bootstrap {
+ err := BootstrapCluster(peerConf, logs, store, snap, trans, configuration)
+ if err != nil {
+ c.FailNowf("[ERR] BootstrapCluster failed: %v", err)
+ }
+ }
+
+ raft, err := NewRaft(peerConf, c.fsms[i], logs, store, snap, trans)
+ if err != nil {
+ c.FailNowf("[ERR] NewRaft failed: %v", err)
+ }
+
+ raft.RegisterObserver(NewObserver(c.observationCh, false, nil))
+ if err != nil {
+ c.FailNowf("[ERR] RegisterObserver failed: %v", err)
+ }
+ c.rafts = append(c.rafts, raft)
+ }
+
+ return c
+}
+
+// NOTE: This is exposed for middleware testing purposes and is not a stable API
+func MakeCluster(n int, t *testing.T, conf *Config) *cluster {
+ return makeCluster(t, &MakeClusterOpts{
+ Peers: n,
+ Bootstrap: true,
+ Conf: conf,
+ })
+}
+
+// NOTE: This is exposed for middleware testing purposes and is not a stable API
+func MakeClusterNoBootstrap(n int, t *testing.T, conf *Config) *cluster {
+ return makeCluster(t, &MakeClusterOpts{
+ Peers: n,
+ Conf: conf,
+ })
+}
+
+// NOTE: This is exposed for middleware testing purposes and is not a stable API
+func MakeClusterCustom(t *testing.T, opts *MakeClusterOpts) *cluster {
+ return makeCluster(t, opts)
+}
+
+// NOTE: This is exposed for middleware testing purposes and is not a stable API
+func FileSnapTest(t *testing.T) (string, *FileSnapshotStore) {
+ // Create a test dir
+ dir, err := ioutil.TempDir("", "raft")
+ if err != nil {
+ t.Fatalf("err: %v ", err)
+ }
+
+ snap, err := NewFileSnapshotStoreWithLogger(dir, 3, newTestLogger(t))
+ if err != nil {
+ t.Fatalf("err: %v", err)
+ }
+ return dir, snap
+}
diff -Naur --color b/vendor/github.com/hashicorp/raft/transport.go a/vendor/github.com/hashicorp/raft/transport.go
--- b/vendor/github.com/hashicorp/raft/transport.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/transport.go 2022-11-15 23:06:31.568724593 +0100
@@ -0,0 +1,127 @@
+package raft
+
+import (
+ "io"
+ "time"
+)
+
+// RPCResponse captures both a response and a potential error.
+type RPCResponse struct {
+ Response interface{}
+ Error error
+}
+
+// RPC has a command, and provides a response mechanism.
+type RPC struct {
+ Command interface{}
+ Reader io.Reader // Set only for InstallSnapshot
+ RespChan chan<- RPCResponse
+}
+
+// Respond is used to respond with a response, error or both
+func (r *RPC) Respond(resp interface{}, err error) {
+ r.RespChan <- RPCResponse{resp, err}
+}
+
+// Transport provides an interface for network transports
+// to allow Raft to communicate with other nodes.
+type Transport interface {
+ // Consumer returns a channel that can be used to
+ // consume and respond to RPC requests.
+ Consumer() <-chan RPC
+
+ // LocalAddr is used to return our local address to distinguish from our peers.
+ LocalAddr() ServerAddress
+
+ // AppendEntriesPipeline returns an interface that can be used to pipeline
+ // AppendEntries requests.
+ AppendEntriesPipeline(id ServerID, target ServerAddress) (AppendPipeline, error)
+
+ // AppendEntries sends the appropriate RPC to the target node.
+ AppendEntries(id ServerID, target ServerAddress, args *AppendEntriesRequest, resp *AppendEntriesResponse) error
+
+ // RequestVote sends the appropriate RPC to the target node.
+ RequestVote(id ServerID, target ServerAddress, args *RequestVoteRequest, resp *RequestVoteResponse) error
+
+ // InstallSnapshot is used to push a snapshot down to a follower. The data is read from
+ // the ReadCloser and streamed to the client.
+ InstallSnapshot(id ServerID, target ServerAddress, args *InstallSnapshotRequest, resp *InstallSnapshotResponse, data io.Reader) error
+
+ // EncodePeer is used to serialize a peer's address.
+ EncodePeer(id ServerID, addr ServerAddress) []byte
+
+ // DecodePeer is used to deserialize a peer's address.
+ DecodePeer([]byte) ServerAddress
+
+ // SetHeartbeatHandler is used to setup a heartbeat handler
+ // as a fast-pass. This is to avoid head-of-line blocking from
+ // disk IO. If a Transport does not support this, it can simply
+ // ignore the call, and push the heartbeat onto the Consumer channel.
+ SetHeartbeatHandler(cb func(rpc RPC))
+
+ // TimeoutNow is used to start a leadership transfer to the target node.
+ TimeoutNow(id ServerID, target ServerAddress, args *TimeoutNowRequest, resp *TimeoutNowResponse) error
+}
+
+// WithClose is an interface that a transport may provide which
+// allows a transport to be shut down cleanly when a Raft instance
+// shuts down.
+//
+// It is defined separately from Transport as unfortunately it wasn't in the
+// original interface specification.
+type WithClose interface {
+ // Close permanently closes a transport, stopping
+ // any associated goroutines and freeing other resources.
+ Close() error
+}
+
+// LoopbackTransport is an interface that provides a loopback transport suitable for testing
+// e.g. InmemTransport. It's there so we don't have to rewrite tests.
+type LoopbackTransport interface {
+ Transport // Embedded transport reference
+ WithPeers // Embedded peer management
+ WithClose // with a close routine
+}
+
+// WithPeers is an interface that a transport may provide which allows for connection and
+// disconnection. Unless the transport is a loopback transport, the transport specified to
+// "Connect" is likely to be nil.
+type WithPeers interface {
+ Connect(peer ServerAddress, t Transport) // Connect a peer
+ Disconnect(peer ServerAddress) // Disconnect a given peer
+ DisconnectAll() // Disconnect all peers, possibly to reconnect them later
+}
+
+// AppendPipeline is used for pipelining AppendEntries requests. It is used
+// to increase the replication throughput by masking latency and better
+// utilizing bandwidth.
+type AppendPipeline interface {
+ // AppendEntries is used to add another request to the pipeline.
+ // The send may block which is an effective form of back-pressure.
+ AppendEntries(args *AppendEntriesRequest, resp *AppendEntriesResponse) (AppendFuture, error)
+
+ // Consumer returns a channel that can be used to consume
+ // response futures when they are ready.
+ Consumer() <-chan AppendFuture
+
+ // Close closes the pipeline and cancels all inflight RPCs
+ Close() error
+}
+
+// AppendFuture is used to return information about a pipelined AppendEntries request.
+type AppendFuture interface {
+ Future
+
+ // Start returns the time that the append request was started.
+ // It is always OK to call this method.
+ Start() time.Time
+
+ // Request holds the parameters of the AppendEntries call.
+ // It is always OK to call this method.
+ Request() *AppendEntriesRequest
+
+ // Response holds the results of the AppendEntries call.
+ // This method must only be called after the Error
+ // method returns, and will only be valid on success.
+ Response() *AppendEntriesResponse
+}
diff -Naur --color b/vendor/github.com/hashicorp/raft/.travis.yml a/vendor/github.com/hashicorp/raft/.travis.yml
--- b/vendor/github.com/hashicorp/raft/.travis.yml 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/.travis.yml 2022-11-15 23:06:31.562057797 +0100
@@ -0,0 +1,18 @@
+language: go
+
+go:
+ # Disabled until https://github.com/armon/go-metrics/issues/59 is fixed
+ # - 1.6
+ - 1.8
+ - 1.9
+ - 1.12
+ - tip
+
+install: make deps
+script:
+ - make integ
+
+notifications:
+ flowdock:
+ secure: fZrcf9rlh2IrQrlch1sHkn3YI7SKvjGnAl/zyV5D6NROe1Bbr6d3QRMuCXWWdhJHzjKmXk5rIzbqJhUc0PNF7YjxGNKSzqWMQ56KcvN1k8DzlqxpqkcA3Jbs6fXCWo2fssRtZ7hj/wOP1f5n6cc7kzHDt9dgaYJ6nO2fqNPJiTc=
+
diff -Naur --color b/vendor/github.com/hashicorp/raft/util.go a/vendor/github.com/hashicorp/raft/util.go
--- b/vendor/github.com/hashicorp/raft/util.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft/util.go 2022-11-15 23:06:31.568724593 +0100
@@ -0,0 +1,133 @@
+package raft
+
+import (
+ "bytes"
+ crand "crypto/rand"
+ "fmt"
+ "math"
+ "math/big"
+ "math/rand"
+ "time"
+
+ "github.com/hashicorp/go-msgpack/codec"
+)
+
+func init() {
+ // Ensure we use a high-entropy seed for the psuedo-random generator
+ rand.Seed(newSeed())
+}
+
+// returns an int64 from a crypto random source
+// can be used to seed a source for a math/rand.
+func newSeed() int64 {
+ r, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
+ if err != nil {
+ panic(fmt.Errorf("failed to read random bytes: %v", err))
+ }
+ return r.Int64()
+}
+
+// randomTimeout returns a value that is between the minVal and 2x minVal.
+func randomTimeout(minVal time.Duration) <-chan time.Time {
+ if minVal == 0 {
+ return nil
+ }
+ extra := (time.Duration(rand.Int63()) % minVal)
+ return time.After(minVal + extra)
+}
+
+// min returns the minimum.
+func min(a, b uint64) uint64 {
+ if a <= b {
+ return a
+ }
+ return b
+}
+
+// max returns the maximum.
+func max(a, b uint64) uint64 {
+ if a >= b {
+ return a
+ }
+ return b
+}
+
+// generateUUID is used to generate a random UUID.
+func generateUUID() string {
+ buf := make([]byte, 16)
+ if _, err := crand.Read(buf); err != nil {
+ panic(fmt.Errorf("failed to read random bytes: %v", err))
+ }
+
+ return fmt.Sprintf("%08x-%04x-%04x-%04x-%12x",
+ buf[0:4],
+ buf[4:6],
+ buf[6:8],
+ buf[8:10],
+ buf[10:16])
+}
+
+// asyncNotifyCh is used to do an async channel send
+// to a single channel without blocking.
+func asyncNotifyCh(ch chan struct{}) {
+ select {
+ case ch <- struct{}{}:
+ default:
+ }
+}
+
+// drainNotifyCh empties out a single-item notification channel without
+// blocking, and returns whether it received anything.
+func drainNotifyCh(ch chan struct{}) bool {
+ select {
+ case <-ch:
+ return true
+ default:
+ return false
+ }
+}
+
+// asyncNotifyBool is used to do an async notification
+// on a bool channel.
+func asyncNotifyBool(ch chan bool, v bool) {
+ select {
+ case ch <- v:
+ default:
+ }
+}
+
+// Decode reverses the encode operation on a byte slice input.
+func decodeMsgPack(buf []byte, out interface{}) error {
+ r := bytes.NewBuffer(buf)
+ hd := codec.MsgpackHandle{}
+ dec := codec.NewDecoder(r, &hd)
+ return dec.Decode(out)
+}
+
+// Encode writes an encoded object to a new bytes buffer.
+func encodeMsgPack(in interface{}) (*bytes.Buffer, error) {
+ buf := bytes.NewBuffer(nil)
+ hd := codec.MsgpackHandle{}
+ enc := codec.NewEncoder(buf, &hd)
+ err := enc.Encode(in)
+ return buf, err
+}
+
+// backoff is used to compute an exponential backoff
+// duration. Base time is scaled by the current round,
+// up to some maximum scale factor.
+func backoff(base time.Duration, round, limit uint64) time.Duration {
+ power := min(round, limit)
+ for power > 2 {
+ base *= 2
+ power--
+ }
+ return base
+}
+
+// Needed for sorting []uint64, used to determine commitment
+type uint64Slice []uint64
+
+func (p uint64Slice) Len() int { return len(p) }
+func (p uint64Slice) Less(i, j int) bool { return p[i] < p[j] }
+func (p uint64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
diff -Naur --color b/vendor/github.com/hashicorp/raft-boltdb/bolt_store.go a/vendor/github.com/hashicorp/raft-boltdb/bolt_store.go
--- b/vendor/github.com/hashicorp/raft-boltdb/bolt_store.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft-boltdb/bolt_store.go 2022-11-15 23:06:31.575391387 +0100
@@ -0,0 +1,268 @@
+package raftboltdb
+
+import (
+ "errors"
+
+ "github.com/boltdb/bolt"
+ "github.com/hashicorp/raft"
+)
+
+const (
+ // Permissions to use on the db file. This is only used if the
+ // database file does not exist and needs to be created.
+ dbFileMode = 0600
+)
+
+var (
+ // Bucket names we perform transactions in
+ dbLogs = []byte("logs")
+ dbConf = []byte("conf")
+
+ // An error indicating a given key does not exist
+ ErrKeyNotFound = errors.New("not found")
+)
+
+// BoltStore provides access to BoltDB for Raft to store and retrieve
+// log entries. It also provides key/value storage, and can be used as
+// a LogStore and StableStore.
+type BoltStore struct {
+ // conn is the underlying handle to the db.
+ conn *bolt.DB
+
+ // The path to the Bolt database file
+ path string
+}
+
+// Options contains all the configuraiton used to open the BoltDB
+type Options struct {
+ // Path is the file path to the BoltDB to use
+ Path string
+
+ // BoltOptions contains any specific BoltDB options you might
+ // want to specify [e.g. open timeout]
+ BoltOptions *bolt.Options
+
+ // NoSync causes the database to skip fsync calls after each
+ // write to the log. This is unsafe, so it should be used
+ // with caution.
+ NoSync bool
+}
+
+// readOnly returns true if the contained bolt options say to open
+// the DB in readOnly mode [this can be useful to tools that want
+// to examine the log]
+func (o *Options) readOnly() bool {
+ return o != nil && o.BoltOptions != nil && o.BoltOptions.ReadOnly
+}
+
+// NewBoltStore takes a file path and returns a connected Raft backend.
+func NewBoltStore(path string) (*BoltStore, error) {
+ return New(Options{Path: path})
+}
+
+// New uses the supplied options to open the BoltDB and prepare it for use as a raft backend.
+func New(options Options) (*BoltStore, error) {
+ // Try to connect
+ handle, err := bolt.Open(options.Path, dbFileMode, options.BoltOptions)
+ if err != nil {
+ return nil, err
+ }
+ handle.NoSync = options.NoSync
+
+ // Create the new store
+ store := &BoltStore{
+ conn: handle,
+ path: options.Path,
+ }
+
+ // If the store was opened read-only, don't try and create buckets
+ if !options.readOnly() {
+ // Set up our buckets
+ if err := store.initialize(); err != nil {
+ store.Close()
+ return nil, err
+ }
+ }
+ return store, nil
+}
+
+// initialize is used to set up all of the buckets.
+func (b *BoltStore) initialize() error {
+ tx, err := b.conn.Begin(true)
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+
+ // Create all the buckets
+ if _, err := tx.CreateBucketIfNotExists(dbLogs); err != nil {
+ return err
+ }
+ if _, err := tx.CreateBucketIfNotExists(dbConf); err != nil {
+ return err
+ }
+
+ return tx.Commit()
+}
+
+// Close is used to gracefully close the DB connection.
+func (b *BoltStore) Close() error {
+ return b.conn.Close()
+}
+
+// FirstIndex returns the first known index from the Raft log.
+func (b *BoltStore) FirstIndex() (uint64, error) {
+ tx, err := b.conn.Begin(false)
+ if err != nil {
+ return 0, err
+ }
+ defer tx.Rollback()
+
+ curs := tx.Bucket(dbLogs).Cursor()
+ if first, _ := curs.First(); first == nil {
+ return 0, nil
+ } else {
+ return bytesToUint64(first), nil
+ }
+}
+
+// LastIndex returns the last known index from the Raft log.
+func (b *BoltStore) LastIndex() (uint64, error) {
+ tx, err := b.conn.Begin(false)
+ if err != nil {
+ return 0, err
+ }
+ defer tx.Rollback()
+
+ curs := tx.Bucket(dbLogs).Cursor()
+ if last, _ := curs.Last(); last == nil {
+ return 0, nil
+ } else {
+ return bytesToUint64(last), nil
+ }
+}
+
+// GetLog is used to retrieve a log from BoltDB at a given index.
+func (b *BoltStore) GetLog(idx uint64, log *raft.Log) error {
+ tx, err := b.conn.Begin(false)
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+
+ bucket := tx.Bucket(dbLogs)
+ val := bucket.Get(uint64ToBytes(idx))
+
+ if val == nil {
+ return raft.ErrLogNotFound
+ }
+ return decodeMsgPack(val, log)
+}
+
+// StoreLog is used to store a single raft log
+func (b *BoltStore) StoreLog(log *raft.Log) error {
+ return b.StoreLogs([]*raft.Log{log})
+}
+
+// StoreLogs is used to store a set of raft logs
+func (b *BoltStore) StoreLogs(logs []*raft.Log) error {
+ tx, err := b.conn.Begin(true)
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+
+ for _, log := range logs {
+ key := uint64ToBytes(log.Index)
+ val, err := encodeMsgPack(log)
+ if err != nil {
+ return err
+ }
+ bucket := tx.Bucket(dbLogs)
+ if err := bucket.Put(key, val.Bytes()); err != nil {
+ return err
+ }
+ }
+
+ return tx.Commit()
+}
+
+// DeleteRange is used to delete logs within a given range inclusively.
+func (b *BoltStore) DeleteRange(min, max uint64) error {
+ minKey := uint64ToBytes(min)
+
+ tx, err := b.conn.Begin(true)
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+
+ curs := tx.Bucket(dbLogs).Cursor()
+ for k, _ := curs.Seek(minKey); k != nil; k, _ = curs.Next() {
+ // Handle out-of-range log index
+ if bytesToUint64(k) > max {
+ break
+ }
+
+ // Delete in-range log index
+ if err := curs.Delete(); err != nil {
+ return err
+ }
+ }
+
+ return tx.Commit()
+}
+
+// Set is used to set a key/value set outside of the raft log
+func (b *BoltStore) Set(k, v []byte) error {
+ tx, err := b.conn.Begin(true)
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+
+ bucket := tx.Bucket(dbConf)
+ if err := bucket.Put(k, v); err != nil {
+ return err
+ }
+
+ return tx.Commit()
+}
+
+// Get is used to retrieve a value from the k/v store by key
+func (b *BoltStore) Get(k []byte) ([]byte, error) {
+ tx, err := b.conn.Begin(false)
+ if err != nil {
+ return nil, err
+ }
+ defer tx.Rollback()
+
+ bucket := tx.Bucket(dbConf)
+ val := bucket.Get(k)
+
+ if val == nil {
+ return nil, ErrKeyNotFound
+ }
+ return append([]byte(nil), val...), nil
+}
+
+// SetUint64 is like Set, but handles uint64 values
+func (b *BoltStore) SetUint64(key []byte, val uint64) error {
+ return b.Set(key, uint64ToBytes(val))
+}
+
+// GetUint64 is like Get, but handles uint64 values
+func (b *BoltStore) GetUint64(key []byte) (uint64, error) {
+ val, err := b.Get(key)
+ if err != nil {
+ return 0, err
+ }
+ return bytesToUint64(val), nil
+}
+
+// Sync performs an fsync on the database file handle. This is not necessary
+// under normal operation unless NoSync is enabled, in which this forces the
+// database file to sync against the disk.
+func (b *BoltStore) Sync() error {
+ return b.conn.Sync()
+}
diff -Naur --color b/vendor/github.com/hashicorp/raft-boltdb/LICENSE a/vendor/github.com/hashicorp/raft-boltdb/LICENSE
--- b/vendor/github.com/hashicorp/raft-boltdb/LICENSE 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft-boltdb/LICENSE 2022-11-15 23:06:31.572057990 +0100
@@ -0,0 +1,362 @@
+Mozilla Public License, version 2.0
+
+1. Definitions
+
+1.1. "Contributor"
+
+ means each individual or legal entity that creates, contributes to the
+ creation of, or owns Covered Software.
+
+1.2. "Contributor Version"
+
+ means the combination of the Contributions of others (if any) used by a
+ Contributor and that particular Contributor's Contribution.
+
+1.3. "Contribution"
+
+ means Covered Software of a particular Contributor.
+
+1.4. "Covered Software"
+
+ means Source Code Form to which the initial Contributor has attached the
+ notice in Exhibit A, the Executable Form of such Source Code Form, and
+ Modifications of such Source Code Form, in each case including portions
+ thereof.
+
+1.5. "Incompatible With Secondary Licenses"
+ means
+
+ a. that the initial Contributor has attached the notice described in
+ Exhibit B to the Covered Software; or
+
+ b. that the Covered Software was made available under the terms of
+ version 1.1 or earlier of the License, but not also under the terms of
+ a Secondary License.
+
+1.6. "Executable Form"
+
+ means any form of the work other than Source Code Form.
+
+1.7. "Larger Work"
+
+ means a work that combines Covered Software with other material, in a
+ separate file or files, that is not Covered Software.
+
+1.8. "License"
+
+ means this document.
+
+1.9. "Licensable"
+
+ means having the right to grant, to the maximum extent possible, whether
+ at the time of the initial grant or subsequently, any and all of the
+ rights conveyed by this License.
+
+1.10. "Modifications"
+
+ means any of the following:
+
+ a. any file in Source Code Form that results from an addition to,
+ deletion from, or modification of the contents of Covered Software; or
+
+ b. any new file in Source Code Form that contains any Covered Software.
+
+1.11. "Patent Claims" of a Contributor
+
+ means any patent claim(s), including without limitation, method,
+ process, and apparatus claims, in any patent Licensable by such
+ Contributor that would be infringed, but for the grant of the License,
+ by the making, using, selling, offering for sale, having made, import,
+ or transfer of either its Contributions or its Contributor Version.
+
+1.12. "Secondary License"
+
+ means either the GNU General Public License, Version 2.0, the GNU Lesser
+ General Public License, Version 2.1, the GNU Affero General Public
+ License, Version 3.0, or any later versions of those licenses.
+
+1.13. "Source Code Form"
+
+ means the form of the work preferred for making modifications.
+
+1.14. "You" (or "Your")
+
+ means an individual or a legal entity exercising rights under this
+ License. For legal entities, "You" includes any entity that controls, is
+ controlled by, or is under common control with You. For purposes of this
+ definition, "control" means (a) the power, direct or indirect, to cause
+ the direction or management of such entity, whether by contract or
+ otherwise, or (b) ownership of more than fifty percent (50%) of the
+ outstanding shares or beneficial ownership of such entity.
+
+
+2. License Grants and Conditions
+
+2.1. Grants
+
+ Each Contributor hereby grants You a world-wide, royalty-free,
+ non-exclusive license:
+
+ a. under intellectual property rights (other than patent or trademark)
+ Licensable by such Contributor to use, reproduce, make available,
+ modify, display, perform, distribute, and otherwise exploit its
+ Contributions, either on an unmodified basis, with Modifications, or
+ as part of a Larger Work; and
+
+ b. under Patent Claims of such Contributor to make, use, sell, offer for
+ sale, have made, import, and otherwise transfer either its
+ Contributions or its Contributor Version.
+
+2.2. Effective Date
+
+ The licenses granted in Section 2.1 with respect to any Contribution
+ become effective for each Contribution on the date the Contributor first
+ distributes such Contribution.
+
+2.3. Limitations on Grant Scope
+
+ The licenses granted in this Section 2 are the only rights granted under
+ this License. No additional rights or licenses will be implied from the
+ distribution or licensing of Covered Software under this License.
+ Notwithstanding Section 2.1(b) above, no patent license is granted by a
+ Contributor:
+
+ a. for any code that a Contributor has removed from Covered Software; or
+
+ b. for infringements caused by: (i) Your and any other third party's
+ modifications of Covered Software, or (ii) the combination of its
+ Contributions with other software (except as part of its Contributor
+ Version); or
+
+ c. under Patent Claims infringed by Covered Software in the absence of
+ its Contributions.
+
+ This License does not grant any rights in the trademarks, service marks,
+ or logos of any Contributor (except as may be necessary to comply with
+ the notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+ No Contributor makes additional grants as a result of Your choice to
+ distribute the Covered Software under a subsequent version of this
+ License (see Section 10.2) or under the terms of a Secondary License (if
+ permitted under the terms of Section 3.3).
+
+2.5. Representation
+
+ Each Contributor represents that the Contributor believes its
+ Contributions are its original creation(s) or it has sufficient rights to
+ grant the rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+ This License is not intended to limit any rights You have under
+ applicable copyright doctrines of fair use, fair dealing, or other
+ equivalents.
+
+2.7. Conditions
+
+ Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
+ Section 2.1.
+
+
+3. Responsibilities
+
+3.1. Distribution of Source Form
+
+ All distribution of Covered Software in Source Code Form, including any
+ Modifications that You create or to which You contribute, must be under
+ the terms of this License. You must inform recipients that the Source
+ Code Form of the Covered Software is governed by the terms of this
+ License, and how they can obtain a copy of this License. You may not
+ attempt to alter or restrict the recipients' rights in the Source Code
+ Form.
+
+3.2. Distribution of Executable Form
+
+ If You distribute Covered Software in Executable Form then:
+
+ a. such Covered Software must also be made available in Source Code Form,
+ as described in Section 3.1, and You must inform recipients of the
+ Executable Form how they can obtain a copy of such Source Code Form by
+ reasonable means in a timely manner, at a charge no more than the cost
+ of distribution to the recipient; and
+
+ b. You may distribute such Executable Form under the terms of this
+ License, or sublicense it under different terms, provided that the
+ license for the Executable Form does not attempt to limit or alter the
+ recipients' rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+ You may create and distribute a Larger Work under terms of Your choice,
+ provided that You also comply with the requirements of this License for
+ the Covered Software. If the Larger Work is a combination of Covered
+ Software with a work governed by one or more Secondary Licenses, and the
+ Covered Software is not Incompatible With Secondary Licenses, this
+ License permits You to additionally distribute such Covered Software
+ under the terms of such Secondary License(s), so that the recipient of
+ the Larger Work may, at their option, further distribute the Covered
+ Software under the terms of either this License or such Secondary
+ License(s).
+
+3.4. Notices
+
+ You may not remove or alter the substance of any license notices
+ (including copyright notices, patent notices, disclaimers of warranty, or
+ limitations of liability) contained within the Source Code Form of the
+ Covered Software, except that You may alter any license notices to the
+ extent required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+ You may choose to offer, and to charge a fee for, warranty, support,
+ indemnity or liability obligations to one or more recipients of Covered
+ Software. However, You may do so only on Your own behalf, and not on
+ behalf of any Contributor. You must make it absolutely clear that any
+ such warranty, support, indemnity, or liability obligation is offered by
+ You alone, and You hereby agree to indemnify every Contributor for any
+ liability incurred by such Contributor as a result of warranty, support,
+ indemnity or liability terms You offer. You may include additional
+ disclaimers of warranty and limitations of liability specific to any
+ jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+
+ If it is impossible for You to comply with any of the terms of this License
+ with respect to some or all of the Covered Software due to statute,
+ judicial order, or regulation then You must: (a) comply with the terms of
+ this License to the maximum extent possible; and (b) describe the
+ limitations and the code they affect. Such description must be placed in a
+ text file included with all distributions of the Covered Software under
+ this License. Except to the extent prohibited by statute or regulation,
+ such description must be sufficiently detailed for a recipient of ordinary
+ skill to be able to understand it.
+
+5. Termination
+
+5.1. The rights granted under this License will terminate automatically if You
+ fail to comply with any of its terms. However, if You become compliant,
+ then the rights granted under this License from a particular Contributor
+ are reinstated (a) provisionally, unless and until such Contributor
+ explicitly and finally terminates Your grants, and (b) on an ongoing
+ basis, if such Contributor fails to notify You of the non-compliance by
+ some reasonable means prior to 60 days after You have come back into
+ compliance. Moreover, Your grants from a particular Contributor are
+ reinstated on an ongoing basis if such Contributor notifies You of the
+ non-compliance by some reasonable means, this is the first time You have
+ received notice of non-compliance with this License from such
+ Contributor, and You become compliant prior to 30 days after Your receipt
+ of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+ infringement claim (excluding declaratory judgment actions,
+ counter-claims, and cross-claims) alleging that a Contributor Version
+ directly or indirectly infringes any patent, then the rights granted to
+ You by any and all Contributors for the Covered Software under Section
+ 2.1 of this License shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
+ license agreements (excluding distributors and resellers) which have been
+ validly granted by You or Your distributors under this License prior to
+ termination shall survive termination.
+
+6. Disclaimer of Warranty
+
+ Covered Software is provided under this License on an "as is" basis,
+ without warranty of any kind, either expressed, implied, or statutory,
+ including, without limitation, warranties that the Covered Software is free
+ of defects, merchantable, fit for a particular purpose or non-infringing.
+ The entire risk as to the quality and performance of the Covered Software
+ is with You. Should any Covered Software prove defective in any respect,
+ You (not any Contributor) assume the cost of any necessary servicing,
+ repair, or correction. This disclaimer of warranty constitutes an essential
+ part of this License. No use of any Covered Software is authorized under
+ this License except under this disclaimer.
+
+7. Limitation of Liability
+
+ Under no circumstances and under no legal theory, whether tort (including
+ negligence), contract, or otherwise, shall any Contributor, or anyone who
+ distributes Covered Software as permitted above, be liable to You for any
+ direct, indirect, special, incidental, or consequential damages of any
+ character including, without limitation, damages for lost profits, loss of
+ goodwill, work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses, even if such party shall have been
+ informed of the possibility of such damages. This limitation of liability
+ shall not apply to liability for death or personal injury resulting from
+ such party's negligence to the extent applicable law prohibits such
+ limitation. Some jurisdictions do not allow the exclusion or limitation of
+ incidental or consequential damages, so this exclusion and limitation may
+ not apply to You.
+
+8. Litigation
+
+ Any litigation relating to this License may be brought only in the courts
+ of a jurisdiction where the defendant maintains its principal place of
+ business and such litigation shall be governed by laws of that
+ jurisdiction, without reference to its conflict-of-law provisions. Nothing
+ in this Section shall prevent a party's ability to bring cross-claims or
+ counter-claims.
+
+9. Miscellaneous
+
+ This License represents the complete agreement concerning the subject
+ matter hereof. If any provision of this License is held to be
+ unenforceable, such provision shall be reformed only to the extent
+ necessary to make it enforceable. Any law or regulation which provides that
+ the language of a contract shall be construed against the drafter shall not
+ be used to construe this License against a Contributor.
+
+
+10. Versions of the License
+
+10.1. New Versions
+
+ Mozilla Foundation is the license steward. Except as provided in Section
+ 10.3, no one other than the license steward has the right to modify or
+ publish new versions of this License. Each version will be given a
+ distinguishing version number.
+
+10.2. Effect of New Versions
+
+ You may distribute the Covered Software under the terms of the version
+ of the License under which You originally received the Covered Software,
+ or under the terms of any subsequent version published by the license
+ steward.
+
+10.3. Modified Versions
+
+ If you create software not governed by this License, and you want to
+ create a new license for such software, you may create and use a
+ modified version of this License if you rename the license and remove
+ any references to the name of the license steward (except to note that
+ such modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary
+ Licenses If You choose to distribute Source Code Form that is
+ Incompatible With Secondary Licenses under the terms of this version of
+ the License, the notice described in Exhibit B of this License must be
+ attached.
+
+Exhibit A - Source Code Form License Notice
+
+ This Source Code Form is subject to the
+ terms of the Mozilla Public License, v.
+ 2.0. If a copy of the MPL was not
+ distributed with this file, You can
+ obtain one at
+ http://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular file,
+then You may include the notice in a location (such as a LICENSE file in a
+relevant directory) where a recipient would be likely to look for such a
+notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - "Incompatible With Secondary Licenses" Notice
+
+ This Source Code Form is "Incompatible
+ With Secondary Licenses", as defined by
+ the Mozilla Public License, v. 2.0.
\ No newline at end of file
diff -Naur --color b/vendor/github.com/hashicorp/raft-boltdb/Makefile a/vendor/github.com/hashicorp/raft-boltdb/Makefile
--- b/vendor/github.com/hashicorp/raft-boltdb/Makefile 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft-boltdb/Makefile 2022-11-15 23:06:31.575391387 +0100
@@ -0,0 +1,11 @@
+DEPS = $(go list -f '{{range .TestImports}}{{.}} {{end}}' ./...)
+
+.PHONY: test deps
+
+test:
+ go test -timeout=30s ./...
+
+deps:
+ go get -d -v ./...
+ echo $(DEPS) | xargs -n1 go get -d
+
diff -Naur --color b/vendor/github.com/hashicorp/raft-boltdb/README.md a/vendor/github.com/hashicorp/raft-boltdb/README.md
--- b/vendor/github.com/hashicorp/raft-boltdb/README.md 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft-boltdb/README.md 2022-11-15 23:06:31.575391387 +0100
@@ -0,0 +1,11 @@
+raft-boltdb
+===========
+
+This repository provides the `raftboltdb` package. The package exports the
+`BoltStore` which is an implementation of both a `LogStore` and `StableStore`.
+
+It is meant to be used as a backend for the `raft` [package
+here](https://github.com/hashicorp/raft).
+
+This implementation uses [BoltDB](https://github.com/boltdb/bolt). BoltDB is
+a simple key/value store implemented in pure Go, and inspired by LMDB.
diff -Naur --color b/vendor/github.com/hashicorp/raft-boltdb/.travis.yml a/vendor/github.com/hashicorp/raft-boltdb/.travis.yml
--- b/vendor/github.com/hashicorp/raft-boltdb/.travis.yml 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft-boltdb/.travis.yml 2022-11-15 23:06:31.572057990 +0100
@@ -0,0 +1,10 @@
+language: go
+
+go:
+ - 1.6
+ - 1.7
+ - tip
+
+install: make deps
+script:
+ - make test
diff -Naur --color b/vendor/github.com/hashicorp/raft-boltdb/util.go a/vendor/github.com/hashicorp/raft-boltdb/util.go
--- b/vendor/github.com/hashicorp/raft-boltdb/util.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/hashicorp/raft-boltdb/util.go 2022-11-15 23:06:31.575391387 +0100
@@ -0,0 +1,37 @@
+package raftboltdb
+
+import (
+ "bytes"
+ "encoding/binary"
+
+ "github.com/hashicorp/go-msgpack/codec"
+)
+
+// Decode reverses the encode operation on a byte slice input
+func decodeMsgPack(buf []byte, out interface{}) error {
+ r := bytes.NewBuffer(buf)
+ hd := codec.MsgpackHandle{}
+ dec := codec.NewDecoder(r, &hd)
+ return dec.Decode(out)
+}
+
+// Encode writes an encoded object to a new bytes buffer
+func encodeMsgPack(in interface{}) (*bytes.Buffer, error) {
+ buf := bytes.NewBuffer(nil)
+ hd := codec.MsgpackHandle{}
+ enc := codec.NewEncoder(buf, &hd)
+ err := enc.Encode(in)
+ return buf, err
+}
+
+// Converts bytes to an integer
+func bytesToUint64(b []byte) uint64 {
+ return binary.BigEndian.Uint64(b)
+}
+
+// Converts a uint to a byte slice
+func uint64ToBytes(u uint64) []byte {
+ buf := make([]byte, 8)
+ binary.BigEndian.PutUint64(buf, u)
+ return buf
+}
diff -Naur --color b/vendor/github.com/libp2p/go-libp2p-consensus/consensus.go a/vendor/github.com/libp2p/go-libp2p-consensus/consensus.go
--- b/vendor/github.com/libp2p/go-libp2p-consensus/consensus.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/libp2p/go-libp2p-consensus/consensus.go 2022-11-15 23:06:32.142068993 +0100
@@ -0,0 +1,44 @@
+package consensus
+
+type State interface {
+}
+
+type Consensus interface {
+ // GetCurrentState returns the current agreed upon state of the system
+ GetCurrentState() (State, error)
+
+ // CommitState attempts to set the current state of the system. It returns
+ // the new state of the system if the call succeeds.
+ CommitState(State) (State, error)
+
+ // SetActor sets the underlying actor that will actually be performing the
+ // operations of setting and changing the state.
+ SetActor(Actor)
+}
+
+type Actor interface {
+ // SetState attempts to set the state of the cluster to the state
+ // represented by the given Node
+ SetState(State) (State, error)
+}
+
+type Op interface {
+ ApplyTo(State) (State, error)
+}
+
+type OpLogConsensus interface {
+ // CommitOp takes the current state and applies the given operation to it, then
+ // sets the new state as the clusters 'current' state.
+ CommitOp(Op) (State, error)
+
+ SetActor(Actor)
+
+ // GetLogHead returns a node that represents the current state of the cluster
+ GetLogHead() (State, error)
+
+ // Rollback rolls the state of the cluster back to the given node. The
+ // passed in node should be a node that was previously a state in the chain of
+ // states. Although some discussion will need to be had as to whether or not
+ // this is truly necessary
+ Rollback(State) error
+}
diff -Naur --color b/vendor/github.com/libp2p/go-libp2p-consensus/Makefile a/vendor/github.com/libp2p/go-libp2p-consensus/Makefile
--- b/vendor/github.com/libp2p/go-libp2p-consensus/Makefile 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/libp2p/go-libp2p-consensus/Makefile 2022-11-15 23:06:32.142068993 +0100
@@ -0,0 +1,14 @@
+all: deps
+gx:
+ go get github.com/whyrusleeping/gx
+ go get github.com/whyrusleeping/gx-go
+
+deps: gx
+ gx --verbose install --global
+ gx-go rewrite
+
+
+test: deps # just check that it builds as there is nothing to test
+ go build .
+publish:
+ gx-go rewrite --undo
diff -Naur --color b/vendor/github.com/libp2p/go-libp2p-consensus/package.json a/vendor/github.com/libp2p/go-libp2p-consensus/package.json
--- b/vendor/github.com/libp2p/go-libp2p-consensus/package.json 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/libp2p/go-libp2p-consensus/package.json 2022-11-15 23:06:32.145402391 +0100
@@ -0,0 +1,16 @@
+{
+ "author": "hsanjuan",
+ "bugs": {
+ "url": "https://github.com/libp2p/go-libp2p-consensus"
+ },
+ "gx": {
+ "dvcsimport": "github.com/libp2p/go-libp2p-consensus"
+ },
+ "gxVersion": "0.10.0",
+ "language": "go",
+ "license": "MIT",
+ "name": "go-libp2p-consensus",
+ "releaseCmd": "git commit -a -m \"gx publish $VERSION\"",
+ "version": "0.0.3"
+}
+
diff -Naur --color b/vendor/github.com/libp2p/go-libp2p-consensus/README.md a/vendor/github.com/libp2p/go-libp2p-consensus/README.md
--- b/vendor/github.com/libp2p/go-libp2p-consensus/README.md 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/libp2p/go-libp2p-consensus/README.md 2022-11-15 23:06:32.142068993 +0100
@@ -0,0 +1,55 @@
+# go-libp2p-consensus
+
+[![](https://img.shields.io/badge/made%20by-Protocol%20Labs-blue.svg?style=flat-square)](http://ipn.io)
+[![](https://img.shields.io/badge/project-libp2p-blue.svg?style=flat-square)](http://github.com/libp2p/libp2p)
+[![](https://img.shields.io/badge/freenode-%23ipfs-blue.svg?style=flat-square)](http://webchat.freenode.net/?channels=%23ipfs)
+[![standard-readme compliant](https://img.shields.io/badge/standard--readme-OK-green.svg?style=flat-square)](https://github.com/RichardLitt/standard-readme)
+[![GoDoc](https://godoc.org/github.com/libp2p/go-libp2p-raft?status.svg)](https://godoc.org/github.com/libp2p/go-libp2p-consensus)
+[![Build Status](https://travis-ci.org/libp2p/go-libp2p-consensus.svg?branch=master)](https://travis-ci.org/libp2p/go-libp2p-consensus)
+
+> A Consensus interface for LibP2P
+
+The LibP2P Consensus interface allows to abstract different consensus algorithms implemented for libp2p with an standarized layer so they can be swapped seamlessly.
+
+## Table of Contents
+
+- [Install](#install)
+- [Usage](#usage)
+- [Contribute](#contribute)
+- [License](#license)
+
+## Install
+
+Simply `go-get` the module:
+
+```
+go get -u github.com/libp2p/go-libp2p-consensus
+```
+
+You can run `make deps` and `make test`, although they do very little because this module only declares some interfaces.
+
+## Usage
+
+In a different project just:
+
+```
+import "github.com/libp2p/go-libp2p-consensus"
+```
+
+This module is published as a GX dependency. So you can also import in GX with:
+
+```
+> gx import github.com/libp2p/go-libp2p-consensus
+```
+
+The code is documented in [godoc.org/github.com/libp2p/go-libp2p-consensus](https://godoc.org/github.com/libp2p/go-libp2p-consensus).
+
+## Contribute
+
+PRs accepted.
+
+Small note: If editing the README, please conform to the [standard-readme](https://github.com/RichardLitt/standard-readme) specification.
+
+## License
+
+MIT © Protocol Labs, Inc.
diff -Naur --color b/vendor/github.com/libp2p/go-libp2p-consensus/.travis.yml a/vendor/github.com/libp2p/go-libp2p-consensus/.travis.yml
--- b/vendor/github.com/libp2p/go-libp2p-consensus/.travis.yml 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/libp2p/go-libp2p-consensus/.travis.yml 2022-11-15 23:06:32.142068993 +0100
@@ -0,0 +1,32 @@
+os:
+ - linux
+
+language: go
+
+go:
+ - 1.11.x
+
+env:
+ global:
+ - GOTFLAGS="-race"
+ matrix:
+ - BUILD_DEPTYPE=gx
+ - BUILD_DEPTYPE=gomod
+
+
+# disable travis install
+install:
+ - true
+
+script:
+ - bash <(curl -s https://raw.githubusercontent.com/ipfs/ci-helpers/master/travis-ci/run-standard-tests.sh)
+
+
+cache:
+ directories:
+ - /Users/raul/go/src/gx
+ - /Users/raul/go/pkg/mod
+ - /Users/raul/.cache/go-build
+
+notifications:
+ email: false
diff -Naur --color b/vendor/github.com/libp2p/go-libp2p-gorpc/call.go a/vendor/github.com/libp2p/go-libp2p-gorpc/call.go
--- b/vendor/github.com/libp2p/go-libp2p-gorpc/call.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/libp2p/go-libp2p-gorpc/call.go 2022-11-15 23:06:32.162069380 +0100
@@ -0,0 +1,160 @@
+package rpc
+
+import (
+ "context"
+ "fmt"
+ "reflect"
+ "sync"
+
+ "github.com/libp2p/go-libp2p-core/network"
+ "github.com/libp2p/go-libp2p-core/peer"
+)
+
+// Call represents an active RPC. Calls are used to indicate completion
+// of RPC requests and are returned within the provided channel in
+// the Go() functions.
+type Call struct {
+ ctx context.Context
+ cancel func()
+
+ finishedMu sync.RWMutex
+ finished bool
+
+ Dest peer.ID
+ SvcID ServiceID // The name of the service and method to call.
+ Args interface{} // The argument to the function.
+ Reply interface{} // The reply from the function.
+ StreamArgs reflect.Value // streaming objects (channel).
+ StreamReplies reflect.Value // streaming replies (channel).
+ Done chan *Call // Strobes when call is complete.
+
+ errorMu sync.Mutex
+ Error error // After completion, the error status.
+}
+
+// newCall panics if arguments are not as expected.
+func newCall(ctx context.Context, dest peer.ID, svcName, svcMethod string, args, reply interface{}, done chan *Call) *Call {
+
+ sID := ServiceID{svcName, svcMethod}
+
+ if !isExportedOrBuiltinType(reflect.TypeOf(args)) {
+ panic(fmt.Sprintf("%s: method argument is not exported or builtin", sID))
+ }
+
+ if !isExportedOrBuiltinType(reflect.TypeOf(args)) {
+ panic(fmt.Sprintf("%s: method reply argument is not exported or builtin", sID))
+ }
+
+ if reply == nil || reflect.TypeOf(reply).Kind() != reflect.Ptr {
+ panic(fmt.Sprintf("%s: reply type must be a pointer to a type", sID))
+ }
+
+ ctx2, cancel := context.WithCancel(ctx)
+ return &Call{
+ ctx: ctx2,
+ cancel: cancel,
+ Dest: dest,
+ SvcID: sID,
+ Args: args,
+ Reply: reply,
+ Error: nil,
+ Done: done,
+ }
+}
+
+// newStreamingCall panics if arguments are not as expected.
+func newStreamingCall(ctx context.Context, dest peer.ID, svcName, svcMethod string, streamArgs, streamReplies reflect.Value, done chan *Call) *Call {
+ sID := ServiceID{svcName, svcMethod}
+
+ checkChanTypesValid(sID, streamArgs, reflect.RecvDir)
+ checkChanTypesValid(sID, streamReplies, reflect.SendDir)
+
+ ctx2, cancel := context.WithCancel(ctx)
+ return &Call{
+ ctx: ctx2,
+ cancel: cancel,
+ Dest: dest,
+ SvcID: sID,
+ StreamArgs: streamArgs,
+ StreamReplies: streamReplies,
+ Error: nil,
+ Done: done,
+ }
+}
+
+// done places the completed call in the done channel.
+func (call *Call) done() {
+ call.finishedMu.Lock()
+ call.finished = true
+ call.finishedMu.Unlock()
+
+ select {
+ case call.Done <- call:
+ // ok
+ default:
+ logger.Debugf("discarding %s call reply", call.SvcID)
+ }
+ call.cancel()
+}
+
+func (call *Call) doneWithError(err error) {
+ if err != nil {
+ logger.Warning(err)
+ call.setError(err)
+ }
+ call.done()
+}
+
+func (call *Call) isFinished() bool {
+ call.finishedMu.RLock()
+ defer call.finishedMu.RUnlock()
+ return call.finished
+}
+
+// watch context will wait for a context cancellation
+// and close the stream.
+func (call *Call) watchContextWithStream(s network.Stream) {
+ <-call.ctx.Done()
+ if !call.isFinished() { // context was cancelled not by us
+ logger.Debug("call context is done before finishing")
+ call.doneWithError(call.ctx.Err())
+ // This used to be s.Close() But for streaming we definitely
+ // need to signal an abnormal finalization of the call when a
+ // context is cancelled.
+ s.Reset()
+ }
+}
+
+func (call *Call) setError(err error) {
+ call.errorMu.Lock()
+ defer call.errorMu.Unlock()
+ if call.Error == nil {
+ call.Error = err
+ }
+}
+
+func (call *Call) getError() error {
+ call.errorMu.Lock()
+ defer call.errorMu.Unlock()
+ return call.Error
+}
+
+// panics otherwise
+func checkChanTypesValid(sID ServiceID, vChan reflect.Value, dir reflect.ChanDir) {
+ desc := "argument"
+ if dir == reflect.SendDir {
+ desc = "reply"
+ }
+
+ if vChan.Kind() != reflect.Chan {
+ panic(fmt.Sprintf("%s: %s type must be a channel", desc, sID))
+ }
+
+ if vChan.Type().ChanDir()&dir == 0 {
+ panic(fmt.Sprintf("%s: %s channel has wrong channel direction", sID, desc))
+ }
+
+ if !isExportedOrBuiltinType(vChan.Type().Elem()) {
+ panic(fmt.Sprintf("%s: %s channel type is not exported or builtin", sID, desc))
+ }
+}
diff -Naur --color b/vendor/github.com/libp2p/go-libp2p-gorpc/client.go a/vendor/github.com/libp2p/go-libp2p-gorpc/client.go
--- b/vendor/github.com/libp2p/go-libp2p-gorpc/client.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/libp2p/go-libp2p-gorpc/client.go 2022-11-15 23:06:32.162069380 +0100
@@ -0,0 +1,745 @@
+package rpc
+
+import (
+ "context"
+ "io"
+ "reflect"
+ "sync"
+
+ "github.com/libp2p/go-libp2p-core/host"
+ "github.com/libp2p/go-libp2p-core/peer"
+ "github.com/libp2p/go-libp2p-core/protocol"
+
+ stats "github.com/libp2p/go-libp2p-gorpc/stats"
+)
+
+// ClientOption allows for functional setting of options on a Client.
+type ClientOption func(*Client)
+
+// WithClientStatsHandler provides an implementation of stats.Handler to be
+// used by the Client.
+func WithClientStatsHandler(h stats.Handler) ClientOption {
+ return func(c *Client) {
+ c.statsHandler = h
+ }
+}
+
+// WithMultiStreamBufferSize sets the channel sizes for multiStream calls.
+// Reading from the argument channel will proceed as long as none of the
+// destinations have filled their buffer. See MultiStream().
+func WithMultiStreamBufferSize(size int) ClientOption {
+ return func(c *Client) {
+ c.multiStreamBufferSize = size
+ }
+}
+
+// Client represents an RPC client which can perform calls to a remote
+// (or local, see below) Server.
+type Client struct {
+ host host.Host
+ protocol protocol.ID
+ server *Server
+ statsHandler stats.Handler
+ multiStreamBufferSize int
+}
+
+// NewClient returns a new Client which uses the given libp2p host
+// and protocol ID, which must match the one used by the server.
+// The Host must be correctly configured to be able to open streams
+// to the server (addresses and keys in Peerstore etc.).
+//
+// The client returned will not be able to run any "local" requests (to its
+// own peer ID) if a server is configured with the same Host becase libp2p
+// hosts cannot open streams to themselves. For this, pass the server directly
+// using NewClientWithServer.
+func NewClient(h host.Host, p protocol.ID, opts ...ClientOption) *Client {
+ c := &Client{
+ host: h,
+ protocol: p,
+ }
+
+ for _, opt := range opts {
+ opt(c)
+ }
+
+ return c
+}
+
+// NewClientWithServer takes an additional RPC Server and returns a Client.
+//
+// Unlike the normal client, this one will be able to perform any requests to
+// itself by using the given directly (and way more efficiently). It is
+// assumed that Client and Server share the same libp2p host in this case.
+func NewClientWithServer(h host.Host, p protocol.ID, s *Server, opts ...ClientOption) *Client {
+ c := NewClient(h, p, opts...)
+ c.server = s
+ return c
+}
+
+// ID returns the peer.ID of the host associated with this client.
+func (c *Client) ID() peer.ID {
+ if c.host == nil {
+ return ""
+ }
+ return c.host.ID()
+}
+
+// Call performs an RPC call to a registered Server service and blocks until
+// completed, returning any errors.
+//
+// The args parameter represents the service's method args and must be of
+// exported or builtin type. The reply type will be used to provide a response
+// and must be a pointer to an exported or builtin type. Otherwise a panic
+// will occurr.
+//
+// If dest is empty ("") or matches the Client's host ID, it will
+// attempt to use the local configured Server when possible.
+func (c *Client) Call(
+ dest peer.ID,
+ svcName, svcMethod string,
+ args, reply interface{},
+) error {
+ ctx := context.Background()
+ return c.CallContext(ctx, dest, svcName, svcMethod, args, reply)
+}
+
+// CallContext performs an RPC call to a registered Server service and blocks
+// until completed, returning any errors. It takes a context which can be used
+// to abort the call at any point.
+//
+// The args parameter represents the service's method args and must be of
+// exported or builtin type. The reply type will be used to provide a response
+// and must be a pointer to an exported or builtin type. Otherwise a panic
+// will occurr.
+//
+// If dest is empty ("") or matches the Client's host ID, it will
+// attempt to use the local configured Server when possible.
+func (c *Client) CallContext(
+ ctx context.Context,
+ dest peer.ID,
+ svcName, svcMethod string,
+ args, reply interface{},
+) error {
+ done := make(chan *Call, 1)
+ call := newCall(ctx, dest, svcName, svcMethod, args, reply, done)
+ go c.makeCall(call)
+ <-done
+
+ return call.getError()
+}
+
+// Go performs an RPC call asynchronously. The associated Call will be placed
+// in the provided channel upon completion, holding any Reply or Errors.
+//
+// The args parameter represents the service's method args and must be of
+// exported or builtin type. The reply type will be used to provide a response
+// and must be a pointer to an exported or builtin type. Otherwise a panic
+// will occurr.
+//
+// The provided done channel must be nil, or have capacity for 1 element
+// at least, or a panic will be triggered.
+//
+// If dest is empty ("") or matches the Client's host ID, it will
+// attempt to use the local configured Server when possible.
+func (c *Client) Go(
+ dest peer.ID,
+ svcName, svcMethod string,
+ args, reply interface{},
+ done chan *Call,
+) error {
+ ctx := context.Background()
+ return c.GoContext(ctx, dest, svcName, svcMethod, args, reply, done)
+}
+
+// GoContext performs an RPC call asynchronously. The provided context can be
+// used to cancel the operation. The associated Call will be placed in the
+// provided channel upon completion, holding any Reply or Errors.
+//
+// The args parameter represents the service's method args and must be of
+// exported or builtin type. The reply type will be used to provide a response
+// and must be a pointer to an exported or builtin type. Otherwise a panic
+// will occurr.
+//
+// The provided done channel must be nil, or have capacity for 1 element
+// at least, or a panic will be triggered.
+//
+// If dest is empty ("") or matches the Client's host ID, it will
+// attempt to use the local configured Server when possible.
+func (c *Client) GoContext(
+ ctx context.Context,
+ dest peer.ID,
+ svcName, svcMethod string,
+ args, reply interface{},
+ done chan *Call,
+) error {
+ if done == nil {
+ done = make(chan *Call, 1)
+ } else {
+ if cap(done) == 0 {
+ panic("done channel has no capacity")
+ }
+ }
+ call := newCall(ctx, dest, svcName, svcMethod, args, reply, done)
+ go c.makeCall(call)
+ return nil
+}
+
+// MultiCall performs a CallContext() to multiple destinations, using the same
+// service name, method and arguments. It will not return until all calls have
+// done so. The contexts, destinations and replies must match in length and
+// will be used in order (ctxs[i] is used for dests[i] which obtains
+// replies[i] and error[i]).
+//
+// The calls will be triggered in parallel (with one goroutine for each).
+func (c *Client) MultiCall(
+ ctxs []context.Context,
+ dests []peer.ID,
+ svcName, svcMethod string,
+ args interface{},
+ replies []interface{},
+) []error {
+
+ ok := checkMatchingLengths(
+ len(ctxs),
+ len(dests),
+ len(replies),
+ )
+
+ if !ok {
+ panic("ctxs, dests and replies must match in length")
+ }
+
+ var wg sync.WaitGroup
+ errs := make([]error, len(dests))
+
+ for i := range dests {
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ err := c.CallContext(
+ ctxs[i],
+ dests[i],
+ svcName,
+ svcMethod,
+ args,
+ replies[i])
+ errs[i] = err
+ }(i)
+ }
+ wg.Wait()
+ return errs
+}
+
+// MultiGo performs a GoContext() call to multiple destinations, using the same
+// service name, method and arguments. MultiGo will return as right after
+// performing all the calls. See the Go() documentation for more information.
+//
+// The provided done channels must be nil, or have capacity for 1 element
+// at least, or a panic will be triggered.
+//
+// The contexts, destinations, replies and done channels must match in length
+// and will be used in order (ctxs[i] is used for dests[i] which obtains
+// replies[i] with dones[i] signalled upon completion).
+func (c *Client) MultiGo(
+ ctxs []context.Context,
+ dests []peer.ID,
+ svcName, svcMethod string,
+ args interface{},
+ replies []interface{},
+ dones []chan *Call,
+) error {
+
+ ok := checkMatchingLengths(
+ len(ctxs),
+ len(dests),
+ len(replies),
+ len(dones),
+ )
+ if !ok {
+ panic("ctxs, dests, replies and dones must match in length")
+ }
+
+ for i := range ctxs {
+ c.GoContext(
+ ctxs[i],
+ dests[i],
+ svcName,
+ svcMethod,
+ args,
+ replies[i],
+ dones[i],
+ )
+ }
+
+ return nil
+}
+
+// Stream performs a streaming RPC call. It receives two arguments which both
+// must be channels of exported or builtin types. The first is a channel from
+// which objects are read and sent on the wire. The second is a channel to
+// receive the replies from. Calling with the wrong types will cause a panic.
+//
+// The sending channel should be closed by the caller for successful
+// completion of the call. The replies channel is closed by us when there is
+// nothing else to receive (call finished or an error happened). The sending
+// channel is drained in the background in case of error, so it is recommended
+// that senders diligently close when an error happens to be able to free
+// resources.
+//
+// The function only returns when the operation is finished successful (both
+// channels are closed) or when an error has occurred.
+func (c *Client) Stream(
+ ctx context.Context,
+ dest peer.ID,
+ svcName, svcMethod string,
+ argsChan interface{},
+ repliesChan interface{},
+) error {
+ vArgsChan := reflect.ValueOf(argsChan)
+ vRepliesChan := reflect.ValueOf(repliesChan)
+
+ done := make(chan *Call, 1)
+ call := newStreamingCall(ctx, dest, svcName, svcMethod, vArgsChan, vRepliesChan, done)
+ go c.makeStream(call)
+ <-done
+ return call.getError()
+}
+
+// MultiStream performs parallel Stream() calls to multiple peers using a
+// single arguments channel for arguments and a single replies channel that
+// aggregates all replies. Errors from each destination are provided in the
+// response. Channel types should be exported or builtin, otherwise a panic
+// will be triggered.
+//
+// In order to replicate the argsChan values to several destinations and sed
+// the replies into a single channel, intermediary channels for each call are
+// created. These channels are buffered per the WithMultiStreamBufferSize()
+// option. If the buffers is exausted for one of the sending or the receiving
+// channels, the sending or receiving stalls. Therefore it is recommended to
+// have enough buffering to allow that slower destinations do not delay
+// everyone else.
+func (c *Client) MultiStream(
+ ctx context.Context,
+ dests []peer.ID,
+ svcName, svcMethod string,
+ argsChan interface{},
+ repliesChan interface{},
+) []error {
+ n := len(dests)
+ sID := ServiceID{svcName, svcMethod}
+
+ vArgsChan := reflect.ValueOf(argsChan)
+ vRepliesChan := reflect.ValueOf(repliesChan)
+ argsChanType := reflect.TypeOf(argsChan)
+ repliesChanType := reflect.TypeOf(repliesChan)
+
+ checkChanTypesValid(sID, vArgsChan, reflect.RecvDir)
+ checkChanTypesValid(sID, vRepliesChan, reflect.SendDir)
+
+ // Make slices of N channels of the same type as the argsChan and
+ // repliesChan. We will use them for every Stream() call. They are
+ // buffered per multiStreamBufferSize.
+ vArgsChannels := makeChanSliceOf(argsChanType, n, c.multiStreamBufferSize)
+ vRepliesChannels := makeChanSliceOf(repliesChanType, n, c.multiStreamBufferSize)
+
+ // Make slices of contexts and cancels. We will use them to cancel
+ // sending to channels when a Stream() call has failed.
+ teeCtxs := make([]context.Context, n)
+ teeCancels := make([]context.CancelFunc, n)
+ for i := 0; i < n; i++ {
+ teeCtxs[i], teeCancels[i] = context.WithCancel(ctx)
+ }
+
+ // To hold responses.
+ errs := make([]error, n)
+
+ var wg sync.WaitGroup
+
+ // First, launch N stream calls to every destination using the
+ // channels we created and everything else provided by the caller.
+ // Collect errors in errs, and if they happen, cancel associated
+ // context.
+ wg.Add(n)
+ for i := 0; i < n; i++ {
+ go func(i int) {
+ defer wg.Done()
+ err := c.Stream(
+ ctx,
+ dests[i],
+ svcName,
+ svcMethod,
+ vArgsChannels.Index(i).Interface(),
+ vRepliesChannels.Index(i).Interface(),
+ )
+ errs[i] = err
+ if err != nil {
+ teeCancels[i]() // cancel context for this so that we close the send channel
+ }
+ }(i)
+ }
+
+ // Second, "tee" anything received from the argsChan into the channels
+ // we created.
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ // Close all sending channels when done.
+ defer func() {
+ for i := 0; i < n; i++ {
+ vArgsChannels.Index(i).Close()
+ }
+ }()
+
+ // Make a select with N cases (one per channel).
+ cases := make([]reflect.SelectCase, n)
+ for i := range cases {
+ cases[i].Dir = reflect.SelectSend
+ }
+
+ // While there is something to receive from the argsChan.
+ for {
+ arg, ok := vArgsChan.Recv()
+ if !ok {
+ return
+ }
+
+ // Setup cases. If the context for a channel has not
+ // been cancelled, prepare a send of the argument we
+ // read from argsChan. Otherwise set Chan to nil
+ // (effectively disables that case).
+ validCases := 0
+ for i := range cases {
+ cases[i].Send = arg
+ if teeCtxs[i].Err() == nil {
+ cases[i].Chan = vArgsChannels.Index(i)
+ validCases++
+ } else {
+ cases[i].Chan = reflect.ValueOf(nil)
+ }
+ }
+
+ if validCases == 0 { // all our ops failed.
+ go drainChannel(vArgsChan)
+ return
+ }
+
+ // Make a select for all cases and call it
+ // "validCases" times. This puts the arg value in all
+ // still available channels, potentially blocking if
+ // one of those channels has no buffer left.
+ for i := 0; i < validCases; i++ {
+ chosen, _, _ := reflect.Select(cases)
+ cases[chosen].Chan = reflect.ValueOf(nil) // ignore this case
+ }
+
+ // We continue reading from the channel.
+ // And repeat until no valid cases left.
+ // otherwise we continue just draining the channel
+ }
+ // if we are here argsChan has been closed.
+ }()
+
+ // Third, "multiplex" anything received from the argsChan into the
+ // channels we created.
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+
+ // Make a select with N cases (one per channel).
+ cases := make([]reflect.SelectCase, n)
+ for i := range cases {
+ cases[i].Dir = reflect.SelectRecv
+ cases[i].Chan = vRepliesChannels.Index(i)
+ }
+
+ validChannels := n
+ for validChannels > 0 {
+ chosen, v, ok := reflect.Select(cases)
+ if !ok {
+ cases[chosen].Chan = reflect.ValueOf(nil)
+ validChannels--
+ continue
+ }
+ vRepliesChan.Send(v)
+ }
+
+ // Close the response channels.
+ vRepliesChan.Close()
+ }()
+
+ // Wait for everyone to finish.
+ wg.Wait()
+ return errs
+}
+
+func makeChanSliceOf(typ reflect.Type, cap int, buffer int) reflect.Value {
+ chanSlice := reflect.MakeSlice(reflect.SliceOf(reflect.ChanOf(reflect.BothDir, typ.Elem())), 0, cap)
+ for i := 0; i < cap; i++ {
+ chanSlice = reflect.Append(
+ chanSlice,
+ reflect.MakeChan(reflect.ChanOf(reflect.BothDir, typ.Elem()), buffer),
+ )
+ }
+ return chanSlice
+}
+
+// returns true if all arguments are the same number.
+func checkMatchingLengths(l ...int) bool {
+ if len(l) <= 1 {
+ return true
+ }
+
+ for i := 1; i < len(l); i++ {
+ if l[i-1] != l[i] {
+ return false
+ }
+ }
+ return true
+}
+
+// makeCall decides if a call can be performed. If it's a local
+// call it will use the configured server if set.
+func (c *Client) makeCall(call *Call) {
+ logger.Debugf("makeCall: %s", call.SvcID)
+
+ // Handle local RPC calls
+ if call.Dest == "" || c.host == nil || call.Dest == c.host.ID() {
+ logger.Debugf("local call: %s", call.SvcID)
+ if c.server == nil {
+ err := &clientError{"Cannot make local calls: server not set"}
+ call.doneWithError(err)
+ return
+ }
+ err := c.server.serverCall(call)
+ call.doneWithError(err)
+ return
+ }
+
+ // Handle remote RPC calls
+ if c.host == nil {
+ panic("no host set: cannot perform remote call")
+ }
+ if c.protocol == "" {
+ panic("no protocol set: cannot perform remote call")
+ }
+ c.send(call)
+}
+
+// send makes a REMOTE RPC call by initiating a libp2p stream to the
+// destination and waiting for a response.
+func (c *Client) send(call *Call) {
+ logger.Debug("sending remote call")
+
+ s, err := c.host.NewStream(call.ctx, call.Dest, c.protocol)
+ if err != nil {
+ call.doneWithError(newClientError(err))
+ return
+ }
+
+ go call.watchContextWithStream(s)
+ sWrap := wrapStream(s)
+
+ logger.Debugf("sending RPC %s to %s", call.SvcID, call.Dest)
+ if err := sWrap.enc.Encode(call.SvcID); err != nil {
+ call.doneWithError(newClientError(err))
+ s.Reset()
+ return
+ }
+
+ // In this case, we have a single argument in the channel.
+ if err := sWrap.enc.Encode(call.Args); err != nil {
+ call.doneWithError(newClientError(err))
+ s.Reset()
+ return
+ }
+
+ if err := sWrap.w.Flush(); err != nil {
+ call.doneWithError(newClientError(err))
+ s.Reset()
+ return
+ }
+ err = receiveResponse(sWrap, call)
+ if err != nil {
+ s.Reset()
+ return
+ }
+ s.Close()
+}
+
+// receiveResponse reads a response to an RPC call
+func receiveResponse(s *streamWrap, call *Call) error {
+ logger.Debugf("waiting response for %s to %s", call.SvcID, call.Dest)
+ var resp Response
+ if err := s.dec.Decode(&resp); err != nil {
+ call.doneWithError(newClientError(err))
+ return err
+ }
+
+ if e := resp.Error; e != "" {
+ err := responseError(resp.ErrType, e)
+ call.setError(err)
+ // we still try to read the body if possible
+ }
+
+ if err := s.dec.Decode(call.Reply); err != nil && err != io.EOF {
+ call.doneWithError(newClientError(err))
+ return err
+ }
+ call.done()
+ return nil
+}
+
+// makeSteram performs a streaming call, either local or remote.
+func (c *Client) makeStream(call *Call) {
+ logger.Debugf("stream: %s", call.SvcID)
+
+ // Handle local RPC calls
+ if call.Dest == "" || c.host == nil || call.Dest == c.host.ID() {
+ logger.Debugf("local call: %s", call.SvcID)
+ if c.server == nil {
+ err := &clientError{"Cannot make local calls: server not set"}
+ call.doneWithError(err)
+ return
+ }
+ err := c.server.serverStream(call)
+ if err != nil {
+ go drainChannel(call.StreamArgs)
+ }
+ call.doneWithError(err)
+ return
+ }
+
+ // Handle remote RPC calls
+ if c.host == nil {
+ panic("no host set: cannot perform remote call")
+ }
+ if c.protocol == "" {
+ panic("no protocol set: cannot perform remote call")
+ }
+ c.stream(call)
+}
+
+// stream makes a REMOTE RPC streaming call by initiating a libp2p stream to
+// the destination, writing argument channel objects to it and reading the
+// replies to the replies channel.
+func (c *Client) stream(call *Call) {
+ logger.Debug("streaming remote call")
+
+ s, err := c.host.NewStream(call.ctx, call.Dest, c.protocol)
+ if err != nil {
+ call.doneWithError(newClientError(err))
+ go drainChannel(call.StreamArgs)
+ call.StreamReplies.Close()
+ return
+ }
+
+ go call.watchContextWithStream(s)
+ sWrap := wrapStream(s)
+
+ // Send the service ID first. This may return an authorization error
+ // for example.
+ logger.Debugf("sending stream-RPC %s to %s", call.SvcID, call.Dest)
+ if err := sWrap.enc.Encode(call.SvcID); err != nil {
+ call.doneWithError(newClientError(err))
+ s.Reset()
+ go drainChannel(call.StreamArgs)
+ call.StreamReplies.Close()
+ return
+ }
+
+ // Flush that so that we become ready to read on the other side.
+ if err := sWrap.w.Flush(); err != nil {
+ call.doneWithError(newClientError(err))
+ s.Reset()
+ go drainChannel(call.StreamArgs)
+ call.StreamReplies.Close()
+ return
+ }
+
+ // Now we need to start writing arguments and reading.
+ // Our context watcher will close the streams, we can therefore
+ // not worry about contexts closures in our goroutines.
+ var wg sync.WaitGroup
+ wg.Add(2)
+
+ // This goroutine sends things on the wire. It reads from the
+ // arguments channel, encodes the object and flushes it.
+ // Repeat until done or error.
+ // Arguments channel is drained on error.
+ go func() {
+ // Close stream for writing when done
+ defer wg.Done()
+ defer s.CloseWrite()
+
+ for {
+ v, ok := call.StreamArgs.Recv()
+ if !ok { // closed channel
+ return
+ }
+ if err := sWrap.enc.Encode(v); err != nil {
+ call.doneWithError(newClientError(err))
+ // closing the args channel is responsibility
+ // of the sender.
+ s.Reset()
+ go drainChannel(call.StreamArgs)
+ return
+ }
+
+ // Flush it
+ if err := sWrap.w.Flush(); err != nil {
+ call.doneWithError(newClientError(err))
+ s.Reset()
+ go drainChannel(call.StreamArgs)
+ return
+ }
+ }
+
+ }()
+
+ // This goroutine receives things from the wire. First it reads a
+ // Response (response can be considered reply "headers"). If it is an
+ // error, then it aborts. Then it reads a reply object and sends it on
+ // the reply channel.
+ go func() {
+ defer wg.Done()
+ defer call.StreamReplies.Close()
+ defer s.CloseRead()
+
+ for {
+ var resp Response
+
+ err := sWrap.dec.Decode(&resp)
+ if err == io.EOF {
+ return
+ }
+ if err != nil {
+ call.setError(newClientError(err))
+ s.Reset()
+ return
+ }
+
+ if resp.Error != "" {
+ call.setError(responseError(resp.ErrType, resp.Error))
+ s.Reset()
+ return
+ }
+
+ // Now decode the data
+ reply := reflect.New(call.StreamReplies.Type().Elem()).Elem().Interface()
+ err = sWrap.dec.Decode(&reply)
+ if err != nil {
+ call.setError(newClientError(err))
+ s.Reset()
+ return
+ }
+ // Put element
+ call.StreamReplies.Send(reflect.ValueOf(reply))
+ }
+ }()
+
+ // Wait for send/receive routines to finish, cleanup and then signal
+ // finalization of the Call.
+ wg.Wait()
+ s.Close()
+ call.done()
+}
diff -Naur --color b/vendor/github.com/libp2p/go-libp2p-gorpc/COPYRIGHT a/vendor/github.com/libp2p/go-libp2p-gorpc/COPYRIGHT
--- b/vendor/github.com/libp2p/go-libp2p-gorpc/COPYRIGHT 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/libp2p/go-libp2p-gorpc/COPYRIGHT 2022-11-15 23:06:32.162069380 +0100
@@ -0,0 +1,3 @@
+This library is dual-licensed under Apache 2.0 and MIT terms.
+
+Parts of `server.go` are based on the Golang source code, which is licensed under a BSD-style license (https://github.com/golang/go/blob/master/LICENSE).
diff -Naur --color b/vendor/github.com/libp2p/go-libp2p-gorpc/errors.go a/vendor/github.com/libp2p/go-libp2p-gorpc/errors.go
--- b/vendor/github.com/libp2p/go-libp2p-gorpc/errors.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/libp2p/go-libp2p-gorpc/errors.go 2022-11-15 23:06:32.162069380 +0100
@@ -0,0 +1,121 @@
+package rpc
+
+import "errors"
+
+// ErrorType is an enum type for providing error type
+// information over the wire between rpc server and client.
+type ErrorType int
+
+const (
+ // NonRPCErr is an error that hasn't arisen from the gorpc package.
+ NonRPCErr ErrorType = iota
+ // ServerErr is an error that has arisen on the server side.
+ ServerErr
+ // ClientErr is an error that has arisen on the client side.
+ ClientErr
+ // AuthorizationErr is an error that has arisen because client doesn't
+ // have permissions to make the given rpc request
+ AuthorizationErr
+)
+
+// serverError indicates that error originated in server
+// specific code.
+type serverError struct {
+ msg string
+}
+
+func (s *serverError) Error() string {
+ return s.msg
+}
+
+// newServerError wraps an error in the serverError type.
+func newServerError(err error) error {
+ return &serverError{err.Error()}
+}
+
+// clientError indicates that error originated in client
+// specific code.
+type clientError struct {
+ msg string
+}
+
+func (c *clientError) Error() string {
+ return c.msg
+}
+
+// newClientError wraps an error in the clientError type.
+func newClientError(err error) error {
+ return &clientError{err.Error()}
+}
+
+// authorizationError indicates that error originated because of client not having
+// permissions to make given rpc request
+type authorizationError struct {
+ msg string
+}
+
+func (a *authorizationError) Error() string {
+ return a.msg
+}
+
+// newAuthorizationError wraps an error in the authorizationError type.
+func newAuthorizationError(err error) error {
+ return &authorizationError{err.Error()}
+}
+
+// responseError converts an responseErr and error message string
+// into the appropriate error type.
+func responseError(errType ErrorType, errMsg string) error {
+ switch errType {
+ case ServerErr:
+ return &serverError{errMsg}
+ case ClientErr:
+ return &clientError{errMsg}
+ case AuthorizationErr:
+ return &authorizationError{errMsg}
+ default:
+ return errors.New(errMsg)
+ }
+}
+
+// responseErrorType determines whether an error is of either
+// serverError or clientError type and returns the appropriate
+// responseErr value.
+func responseErrorType(err error) ErrorType {
+ switch err.(type) {
+ case *serverError:
+ return ServerErr
+ case *clientError:
+ return ClientErr
+ case *authorizationError:
+ return AuthorizationErr
+ default:
+ return NonRPCErr
+ }
+}
+
+// IsRPCError returns whether an error is either a serverError
+// or clientError.
+func IsRPCError(err error) bool {
+ switch err.(type) {
+ case *serverError, *clientError, *authorizationError:
+ return true
+ default:
+ return false
+ }
+}
+
+// IsServerError returns whether an error is serverError.
+func IsServerError(err error) bool {
+ return responseErrorType(err) == ServerErr
+}
+
+// IsClientError returns whether an error is clientError.
+func IsClientError(err error) bool {
+ return responseErrorType(err) == ClientErr
+}
+
+// IsAuthorizationError returns whether an error is authorizationError.
+func IsAuthorizationError(err error) bool {
+ return responseErrorType(err) == AuthorizationErr
+}
diff -Naur --color b/vendor/github.com/libp2p/go-libp2p-gorpc/.gitignore a/vendor/github.com/libp2p/go-libp2p-gorpc/.gitignore
--- b/vendor/github.com/libp2p/go-libp2p-gorpc/.gitignore 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/libp2p/go-libp2p-gorpc/.gitignore 2022-11-15 23:06:32.162069380 +0100
@@ -0,0 +1,26 @@
+coverage.out
+
+# Compiled Object files, Static and Dynamic libs (Shared Objects)
+*.o
+*.a
+*.so
+
+# Folders
+_obj
+_test
+
+# Architecture specific extensions/prefixes
+*.[568vq]
+[568vq].out
+
+*.cgo1.go
+*.cgo2.c
+_cgo_defun.c
+_cgo_gotypes.go
+_cgo_export.*
+
+_testmain.go
+
+*.exe
+*.test
+*.prof
diff -Naur --color b/vendor/github.com/libp2p/go-libp2p-gorpc/LICENSE-APACHE a/vendor/github.com/libp2p/go-libp2p-gorpc/LICENSE-APACHE
--- b/vendor/github.com/libp2p/go-libp2p-gorpc/LICENSE-APACHE 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/libp2p/go-libp2p-gorpc/LICENSE-APACHE 2022-11-15 23:06:32.162069380 +0100
@@ -0,0 +1,15 @@
+APACHE License
+
+Copyright 2018 Protocol Labs, Inc
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
\ No newline at end of file
diff -Naur --color b/vendor/github.com/libp2p/go-libp2p-gorpc/LICENSE-MIT a/vendor/github.com/libp2p/go-libp2p-gorpc/LICENSE-MIT
--- b/vendor/github.com/libp2p/go-libp2p-gorpc/LICENSE-MIT 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/libp2p/go-libp2p-gorpc/LICENSE-MIT 2022-11-15 23:06:32.162069380 +0100
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright 2018 Protocol Labs, Inc
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff -Naur --color b/vendor/github.com/libp2p/go-libp2p-gorpc/README.md a/vendor/github.com/libp2p/go-libp2p-gorpc/README.md
--- b/vendor/github.com/libp2p/go-libp2p-gorpc/README.md 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/libp2p/go-libp2p-gorpc/README.md 2022-11-15 23:06:32.162069380 +0100
@@ -0,0 +1,55 @@
+# go-libp2p-gorpc
+
+[![](https://img.shields.io/badge/made%20by-Protocol%20Labs-blue.svg?style=flat-square)](https://protocol.ai)
+[![](https://img.shields.io/badge/project-libp2p-yellow.svg?style=flat-square)](https://libp2p.io)
+[![](https://img.shields.io/badge/freenode-%23libp2p-yellow.svg?style=flat-square)](http://webchat.freenode.net/?channels=%23libp2p)
+[![GoDoc](https://pkg.go.dev/badge/github.com/libp2p/go-libp2p-gorpc)](https://pkg.go.dev/github.com/libp2p/go-libp2p-gorpc)
+[![Codecov](https://codecov.io/gh/libp2p/go-libp2p-gorpc/badge.svg)](https://codecov.io/gh/libp2p/go-libp2p-gorpc)
+[![Discourse posts](https://img.shields.io/discourse/https/discuss.libp2p.io/posts.svg)](https://discuss.libp2p.io)
+
+> Simple Go RPC for libp2p.
+
+`go-libp2p-gorpc` provides RPC support on top of libp2p in the same way that [net/rpc](https://golang.org/pkg/net/rpc) does on HTTP with a few additional features like:
+
+- Streaming RPC calls using channels.
+- Contexts and async calls.
+
+## Table of Contents
+
+- [Install](#install)
+- [Usage](#usage)
+- [Contribute](#contribute)
+- [License](#license)
+
+## Install
+
+This module can be installed with `go get`:
+
+```
+> go get github.com/libp2p/go-libp2p-gorpc
+```
+
+This repo is [gomod](https://github.com/golang/go/wiki/Modules)-compatible, and users of
+go 1.11 and later with modules enabled will automatically pull the latest tagged release
+by referencing this package. Upgrades to future releases can be managed using `go get`,
+or by editing your `go.mod` file as [described by the gomod documentation](https://github.com/golang/go/wiki/Modules#how-to-upgrade-and-downgrade-dependencies).
+
+## Usage
+
+Documentation for this module is maintained in [pkg.go.dev](https://pkg.go.dev/github.com/libp2p/go-libp2p-gorpc).
+
+There are also examples inside the [examples directory](./examples)
+
+## Contribute
+
+PRs accepted.
+
+Small note: If editing the README, please conform to the [standard-readme](https://github.com/RichardLitt/standard-readme) specification.
+
+## License
+
+MIT
+
+---
+
+The last gx published version of this module was: 1.1.4: QmcJCApoEsCJJap2iS1os9GFX5EuRrfuPeZdjCopz2SyPm
diff -Naur --color b/vendor/github.com/libp2p/go-libp2p-gorpc/server.go a/vendor/github.com/libp2p/go-libp2p-gorpc/server.go
--- b/vendor/github.com/libp2p/go-libp2p-gorpc/server.go 1970-01-01 01:00:00.000000000 +0100
+++ a/vendor/github.com/libp2p/go-libp2p-gorpc/server.go 2022-11-15 23:06:32.162069380 +0100
@@ -0,0 +1,950 @@
+// Package rpc is heavily inspired by Go standard net/rpc package. It aims to
+// do the same thing, except it uses libp2p for communication and provides
+// context support for cancelling operations.
+//
+// A server registers an object, making it visible as a service with the name
+// of the type of the object. After registration, exported methods of the
+// object will be accessible remotely. A server may register multiple objects
+// (services) of different types but it is an error to register multiple
+// objects of the same type.
+//
+// Only methods that satisfy these criteria will be made available for remote
+// access; other methods will be ignored:
+// - the method's type is exported.
+// - the method is exported.
+// - the method has 3 arguments.
+// - the method's first argument is a context.
+// - For normal methods:
+// - the method's second and third arguments are both exported (or builtin) types.
+// - the method's second argument is a pointer.
+// - For "streaming" methods:
+// - the method's second argument is a receiving channel (<-chan) of exported (or builtin) type.
+// - the method's third argument is a sending channel (chan<-) of exported (or builtin) type.
+// - the method has return type error.
+//
+//
+// In effect, the method must look schematically like
+//
+// func (t *T) MethodName(ctx context.Context, argType T1, replyType *T2) error
+// or
+// func (t *T) MethodName(ctx context.Context, argChan <-chan T1, replyChan chan<- T2) error
+//
+// where T1 and T2 can be marshaled by github.com/ugorji/go/codec.
+//
+// In normal calls, the method's second argument represents the arguments
+// provided by the caller; the third argument represents the result
+// parameters to be returned to the caller. The function error response is
+// passed to the client accordingly.
+//
+// In streaming calls, the method's second and third arguments are argument
+// and replies channels. The method is expected to read from the argument
+// channel until it is closed. The method is expected to send responses on the
+// replies channel and close it when done. Both channels are transparently and
+// asynchronously streamed on the wire between remote hosts.
+//
+// In order to use this package, a ready-to-go libp2p Host must be provided
+// to clients and servers, along with a protocol.ID. rpc will add a stream
+// handler for the given protocol.
+//
+// Contexts are supported and honored when provided. On the server side,
+// methods must take a context. A closure or reset of the libp2p stream will
+// trigger a cancellation of the context received by the functions.
+// On the client side, the user can optionally provide a context.
+// Cancelling the client's context will cancel the operation both on the
+// client and on the server side (by closing the associated stream).
+package rpc
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "reflect"
+ "sync"
+ "time"
+ "unicode"
+ "unicode/utf8"
+
+ "github.com/libp2p/go-libp2p-core/host"
+ "github.com/libp2p/go-libp2p-core/network"
+ "github.com/libp2p/go-libp2p-core/peer"
+ "github.com/libp2p/go-libp2p-core/protocol"
+
+ logging "github.com/ipfs/go-log/v2"
+ stats "github.com/libp2p/go-libp2p-gorpc/stats"
+)
+
+// ContextKey is special type for using as a key with context.Context
+type ContextKey string
+
+const (
+ // ContextKeyRequestSender is default key for RPC service function context to retrieve peer ID of current request sender
+ ContextKeyRequestSender = ContextKey("request_sender")
+ // MaxServiceIDLength specifies a maximum length for the
+ // "ServiceName.MethodName" so that an attacker cannot send an
+ // arbitrarily large ServiceID.
+ MaxServiceIDLength = 256
+)
+
+var logger = logging.Logger("p2p-gorpc")
+
+// Precompute the reflect type for error. Can't use error directly
+// because Typeof takes an empty interface value. This is annoying.
+var typeOfError = reflect.TypeOf((*error)(nil)).Elem()
+
+type methodType struct {
+ method reflect.Method
+ ArgType reflect.Type
+ streamingArg bool
+ ReplyType reflect.Type
+ streamingReply bool
+}
+
+// service stores information about a service (which is a pointer to a
+// Go struct normally)
+type service struct {
+ name string // name of service
+ rcvr reflect.Value // receiver of methods for the service
+ typ reflect.Type // type of the receiver
+ method map[string]*methodType // registered methods
+}
+
+// ServiceID is a header sent when performing an RPC request
+// which identifies the service and method being called.
+type ServiceID struct {
+ Name string
+ Method string
+}
+
+// String concatenates ServiceID name and method.
+func (svcID ServiceID) String() string {
+ return svcID.Name + "." + svcID.Method
+}
+
+// Response wraps all elements necessary to reply to a call: Service ID, Error
+// and data. Responses are written to the wire in two steps. First the
+// response object (without the data), then the data object. In streaming
+// calls, each reply object is prepended by a Response object, which should be
+// fully empty unless there is an error.
+type Response struct {
+ Service ServiceID `codec:",omitempty"`
+ Error string `codec:",omitempty"` // error, if any.
+ ErrType ErrorType `codec:",omitempty"`
+ Data interface{} `codec:"-"` // Response data
+}
+
+// AuthorizeWithMap returns an authrorization function that follows the
+// strategy as described in the given map(maps "service.method" of a peer to
+// boolean permission).
+func AuthorizeWithMap(p map[peer.ID]map[string]bool) func(pid peer.ID, svc string, method string) bool {
+ return func(pid peer.ID, svc string, method string) bool {
+ // If map is nil, no method would be allowed
+ if p == nil {
+ return false
+ }
+ return p[pid][svc+"."+method]
+ }
+}
+
+// WithAuthorizeFunc adds authorization strategy(A function defining whether
+// the given peer id is allowed to access given method of the given service)
+// to the server using given authorization function.
+func WithAuthorizeFunc(a func(pid peer.ID, name string, method string) bool) ServerOption {
+ return func(s *Server) {
+ s.authorize = a
+ }
+}
+
+// ServerOption allows for functional setting of options on a Server.
+type ServerOption func(*Server)
+
+// WithServerStatsHandler providers a implementation of stats.Handler to be
+// used by the Server.
+func WithServerStatsHandler(h stats.Handler) ServerOption {
+ return func(s *Server) {
+ s.statsHandler = h
+ }
+}
+
+// WithStreamBufferSize sets the channel buffer size for streaming requests.
+func WithStreamBufferSize(size int) ServerOption {
+ return func(s *Server) {
+ s.streamBufferSize = size
+ }
+}
+
+// Server is an LibP2P RPC server. It can register services which comply to the
+// limitations outlined in the package description and it will call the relevant
+// methods when receiving requests from a Client.
+//
+// A server needs a LibP2P host and a protocol, which must match the one used
+// by the client. The LibP2P host must be already correctly configured to
+// be able to handle connections from clients.
+type Server struct {
+ host host.Host
+ protocol protocol.ID
+
+ statsHandler stats.Handler
+ streamBufferSize int
+
+ mu sync.RWMutex // protects the serviceMap
+ serviceMap map[string]*service
+
+ // authorize defines authorization strategy of the server
+ // If Authorization function is not provided, all methods would be allowed.
+ authorize func(peer.ID, string, string) bool
+}
+
+// NewServer creates a Server object with the given LibP2P host
+// and protocol.
+func NewServer(h host.Host, p protocol.ID, opts ...ServerOption) *Server {
+ s := &Server{
+ host: h,
+ protocol: p,
+ }
+
+ for _, opt := range opts {
+ opt(s)
+ }
+
+ if h != nil {
+ h.SetStreamHandler(p, func(stream network.Stream) {
+ sWrap := wrapStream(stream)
+ defer stream.Close()
+ s.handle(sWrap)
+ })
+ }
+ return s
+}
+
+// ID returns the peer.ID of the host associated with this server.
+func (server *Server) ID() peer.ID {
+ if server.host == nil {
+ return ""
+ }
+ return server.host.ID()
+}
+
+func (server *Server) handle(s *streamWrap) {
+ logger.Debugf("%s: handling remote RPC from %s", server.host.ID().Pretty(), s.stream.Conn().RemotePeer())
+ var svcID ServiceID
+ ctx := context.Background()
+
+ // First, read the header which tells us which service we are hoping
+ // to run. Using limDec so that a client does not potentially DDOS us
+ // with a huge header for what ends up being an unauthorized method.
+ err := s.dec.Decode(&svcID)
+ if err != nil {
+ sendError(s, ServiceID{}, newServerError(fmt.Errorf("error reading service ID: %w", err)))
+ }
+
+ // stats ----------------------
+ sh := server.statsHandler
+ if sh != nil {
+ ctx = sh.TagRPC(ctx, &stats.RPCTagInfo{FullMethodName: "/" + svcID.String()})
+ beginTime := time.Now()
+ begin := &stats.Begin{
+ BeginTime: beginTime,
+ }
+ sh.HandleRPC(ctx, begin)
+
+ defer func() {
+ end := &stats.End{
+ BeginTime: beginTime,
+ EndTime: time.Now(),
+ }
+ if err != nil && err != io.EOF {
+ end.Error = newServerError(err)
+ }
+ sh.HandleRPC(ctx, end)
+ }()
+ }
+ // stats end -------------------------
+
+ logger.Debugf("RPC ServiceID is %s", svcID)
+
+ // The service needs to have been registered with us.
+ service, mtype, err := server.getService(svcID)
+ if err != nil {
+ sendError(s, svcID, newServerError(err))
+ return
+ }
+
+ // Ensure the remote peer has permission to run this by calling authorize().
+ remotePeer := s.stream.Conn().RemotePeer()
+ if server.authorize != nil && !server.authorize(remotePeer, svcID.Name, svcID.Method) {
+ errMsg := fmt.Sprintf("client does not have permissions to call %s", svcID)
+ sendError(s, svcID, newAuthorizationError(errors.New(errMsg)))
+ return
+ }
+ // Right now both must be true or false, which is checked somewhere
+ // else.
+ if mtype.streamingArg || mtype.streamingReply {
+ service.streamCall(ctx, s, mtype, svcID, server.streamBufferSize)
+ return
+ }
+
+ err = service.methodCall(ctx, s, mtype, svcID)
+ if err != nil {
+ logger.Warning(err)
+ sendError(s, svcID, err)
+ return
+ }
+}
+
+// Call a method by reading a single argument from the wire and return the
+// response.
+func (s *service) methodCall(ctx context.Context, sw *streamWrap, mtype *methodType, svcID ServiceID) error {
+ ctx = context.WithValue(ctx, ContextKeyRequestSender, sw.stream.Conn().RemotePeer())
+ ctx, cancel := context.WithCancel(ctx)
+ defer cancel()
+
+ argv, err := readArgFromStream(sw, mtype.ArgType)
+ if err != nil {
+ return err
+ }
+
+ // Replies are always pointers, so need Elem() to get the value.
+ replyv := reflect.New(mtype.ReplyType.Elem())
+
+ ctxv := reflect.ValueOf(ctx)
+
+ // TODO(lanzafame): once I figure out a
+ // good to get the size of the payload.
+ // inPayload := &stats.InPayload{
+ // Length: ,
+ // RecvTime: beginTime,
+ // }
+ // sh.HandleRPC(ctx, inPayload)
+
+ // This is a connection watchdog. We do not
+ // need to read from this stream anymore.
+ // However we'd like to know if the other side is closed
+ // (or reset). In that case, we need to cancel our
+ // context. Note this will also happen at the end
+ // of a successful operation when we close the stream
+ // on our side.
+ go func() {
+ p := make([]byte, 1)
+ _, err := sw.stream.Read(p)
+ if err != nil {
+ cancel()
+ }
+ }()
+
+ function := mtype.method.Func
+ // Invoke the method, providing a new value for the reply.
+ returnValues := function.Call([]reflect.Value{s.rcvr, ctxv, argv, replyv})
+ // The return value for the method is an error.
+ errInter := returnValues[0].Interface()
+ errmsg := ""
+ if errInter != nil {
+ errmsg = errInter.(error).Error()
+ }
+ resp := Response{svcID, errmsg, NonRPCErr, replyv.Interface()}
+
+ return sendResponse(sw, resp)
+}
+
+func (s *service) streamCall(ctx context.Context, sw *streamWrap, mtype *methodType, svcID ServiceID, size int) {
+ ctx = context.WithValue(ctx, ContextKeyRequestSender, sw.stream.Conn().RemotePeer())
+ ctx, cancel := context.WithCancel(ctx)
+
+ // we will need a goroutine that reads from the stream and decodes on
+ // mtype.ArgTypes and sends them on channel. And we will need
+ // goroutine that reads mtype.ReplyType replies, wraps themencodes them and
+ // writes them to the stream.
+
+ // Then we will need to call the things.
+ argsChan := reflect.MakeChan(reflect.ChanOf(reflect.BothDir, mtype.ArgType), size)
+ repliesChan := reflect.MakeChan(reflect.ChanOf(reflect.BothDir, mtype.ReplyType), size)
+ ctxv := reflect.ValueOf(ctx)
+ done := reflect.ValueOf(ctx.Done())
+
+ var wg sync.WaitGroup
+ wg.Add(2)
+ // Read from stream
+ go func() {
+ defer wg.Done()
+ // when done, close stream for reading.
+ defer sw.stream.CloseRead()
+
+ for {
+ // This ensures that we don't attempt to read if the
+ // context is cancelled.
+ select {
+ case <-ctx.Done():
+ logger.Warningf("%s: reading arguments cancelled: %s", svcID, ctx.Err())
+ argsChan.Close()
+ return
+ default:
+ }
+
+ argv, err := readArgFromStream(sw, mtype.ArgType)
+ if err == io.EOF { // stream closed, no more to read.
+ argsChan.Close()
+ return
+ } else if err != nil { // abort
+ logger.Warning(err)
+ cancel() // signal everyone to abort.
+ argsChan.Close()
+ return
+ }
+
+ // This ensures that we don't deadlock on send when
+ // there is no one receiving if the context is
+ // cancelled.
+ chosen, _, _ := reflect.Select([]reflect.SelectCase{
+ {
+ Dir: reflect.SelectRecv,
+ Chan: done, // chan done
+ },
+ {
+ Dir: reflect.SelectSend,
+ Chan: argsChan,
+ Send: argv,
+ },
+ })
+ if chosen == 0 {
+ logger.Warningf("%s: reading arguments cancelled: %s", svcID, ctx.Err())
+ argsChan.Close()
+ return
+ }
+ }
+ }()
+
+ // Read from replies
+ go func() {
+ defer wg.Done()
+
+ for {
+ // This ensures that we don't deadlock on reading
+ // replies if they are not sent and the context is
+ // cancelled.
+ chosen, v, ok := reflect.Select([]reflect.SelectCase{
+ {
+ Dir: reflect.SelectRecv,
+ Chan: done, // chan done
+ },
+ {
+ Dir: reflect.SelectRecv,
+ Chan: repliesChan,
+ },
+ })
+
+ if chosen == 0 { // context cancelled
+ logger.Warningf("%s: reading replies cancelled: %s", svcID, ctx.Err())
+ go drainChannel(repliesChan)
+ return
+ }
+
+ if !ok { // repliesChanClosed
+ logger.Debugf("%s: reply channel closed", svcID)
+ return
+ }
+
+ // This ensures that we don't attempt to send a reply
+ // on the wire if the context is cancelled.
+ select {
+ case <-ctx.Done():
+ logger.Warningf("%s: reading replies cancelled: %s", svcID, ctx.Err())
+ go drainChannel(repliesChan)
+ return
+ default:
+ }
+
+ err := sendResponse(sw, Response{
+ Service: svcID,
+ Data: v.Interface(),
+ })
+ if err != nil {
+ logger.Warning(err)
+ cancel() // signal everyone to abort
+ go drainChannel(repliesChan)
+ return
+ }
+ }
+ }()
+
+ // Finally, we need to call the actual function
+ function := mtype.method.Func
+ // Invoke the method, providing a new value for the reply. This
+ // hangs. The function will do its job. The only way we can signal
+ // that it should stop doings its job is by cancelling ctxv or by closing argsChan.
+ returnValues := function.Call([]reflect.Value{s.rcvr, ctxv, argsChan, repliesChan})
+ errInter := returnValues[0].Interface()
+ if errInter != nil {
+ cancel()
+ wg.Wait()
+ err := errInter.(error)
+ logger.Debugf("%s: attempt to send error: %s", svcID, err)
+ sendError(sw, svcID, err)
+ sw.stream.Close()
+ return
+ }
+
+ logger.Debugf("%s function call finished cleanly", svcID)
+
+ // This means everything went well, OR an error happened with the
+ // stream, the receiving or sending goroutines Reseted it, closed the
+ // arguments channel and the function exited cleanly. In this case the
+ // sending site may have received a stream reset at least, and we
+ // should have logged something.
+ wg.Wait() // wait for things to exist cleanly if they haven't
+ sw.stream.Close()
+ cancel()
+}
+
+func readArgFromStream(sw *streamWrap, argType reflect.Type) (reflect.Value, error) {
+ var argv reflect.Value
+ argIsValue := false
+
+ if argType.Kind() == reflect.Ptr {
+ argv = reflect.New(argType.Elem())
+ } else {
+ argv = reflect.New(argType) // pointer to ArgType
+ argIsValue = true
+ }
+ // argv guaranteed to be a pointer now, so we can decode on top.
+ if err := sw.dec.Decode(argv.Interface()); err != nil {
+ if err == io.EOF {
+ return reflect.ValueOf(nil), err
+ }
+ return argv, newServerError(err)
+ }
+ if argIsValue {
+ argv = argv.Elem()
+ }
+ return argv, nil
+}
+
+// sendResponse sends a Response by first serializing the Response object and
+// then serializing the Response.Data object directly.
+func sendResponse(s *streamWrap, resp Response) error {
+ if err := s.enc.Encode(resp); err != nil {
+ s.stream.Reset()
+ return fmt.Errorf("error encoding response: %w", err)
+ }
+
+ if err := s.enc.Encode(resp.Data); err != nil {
+ s.stream.Reset()
+ return fmt.Errorf("error encoding body: %w", err)
+ }
+
+ if err := s.w.Flush(); err != nil {
+ s.stream.Reset()
+ return fmt.Errorf("error flushing response/body: %w", err)
+ }
+ return nil
+}
+
+func sendError(s *streamWrap, svcID ServiceID, err error) error {
+ return sendResponse(s, Response{
+ Service: svcID,
+ Error: err.Error(),
+ ErrType: responseErrorType(err),
+ Data: nil,
+ })
+}
+
+// Call allows a server to process a Call directly and act like a client
+// to itself. This is mostly useful because libp2p does not allow to
+// create streams between a server and a client which share the same
+// host. See NewClientWithServer() for more info.
+func (server *Server) serverCall(call *Call) error {
+ var err error
+
+ // metrics ---------------------------------------
+ sh := server.statsHandler
+ if sh != nil {
+ call.ctx = sh.TagRPC(call.ctx, &stats.RPCTagInfo{FullMethodName: "/" + call.SvcID.String()})
+ beginTime := time.Now()
+ begin := &stats.Begin{
+ BeginTime: beginTime,
+ }
+ sh.HandleRPC(call.ctx, begin)
+
+ inPayload := &stats.InPayload{
+ Payload: call,
+ Length: int(reflect.TypeOf(call.Args).Size()),
+ RecvTime: beginTime,
+ }
+ sh.HandleRPC(call.ctx, inPayload)
+ defer func() {
+ end := &stats.End{
+ BeginTime: beginTime,
+ EndTime: time.Now(),
+ }
+ if err != nil && err != io.EOF {
+ end.Error = newServerError(err)
+ }
+ sh.HandleRPC(call.ctx, end)
+ }()
+ }
+ // metrics -----------------------------------------------
+
+ var argv, replyv reflect.Value
+ service, mtype, err := server.getService(call.SvcID)
+ if err != nil {
+ return newServerError(err)
+ }
+
+ ctx := context.WithValue(call.ctx, ContextKeyRequestSender, server.ID()) // add local peer id as request sender
+
+ // Use the context value from the call directly
+ ctxv := reflect.ValueOf(ctx)
+
+ // Decode the argument value.
+ argIsValue := false // if true, need to indirect before calling.
+ if mtype.ArgType.Kind() == reflect.Ptr {
+ if reflect.TypeOf(call.Args).Kind() != reflect.Ptr {
+ return fmt.Errorf("%s is being called with the wrong arg type", call.SvcID)
+ }
+ argv = reflect.New(mtype.ArgType.Elem())
+ argv.Elem().Set(reflect.ValueOf(call.Args).Elem())
+ } else {
+ if reflect.TypeOf(call.Args).Kind() == reflect.Ptr {
+ return fmt.Errorf("%s is being called with the wrong arg type", call.SvcID)
+ }
+ argv = reflect.New(mtype.ArgType)
+ argv.Elem().Set(reflect.ValueOf(call.Args))
+ argIsValue = true
+ }
+ // argv guaranteed to be a pointer here.
+ // need dereference if the method actually takes a value.
+ if argIsValue {
+ argv = argv.Elem()
+ }
+
+ replyv = reflect.New(mtype.ReplyType.Elem())
+
+ // Call service and respond
+ function := mtype.method.Func
+
+ // Invoke the method, providing a new value for the reply.
+ returnValues := function.Call(
+ []reflect.Value{
+ service.rcvr,
+ ctxv, // context
+ argv, // argument
+ replyv,
+ },
+ ) // reply
+
+ creplyv := reflect.ValueOf(call.Reply)
+ creplyv.Elem().Set(replyv.Elem())
+
+ // The return value for the method is an error.
+ errInter := returnValues[0].Interface()
+ if errInter != nil {
+ return errInter.(error)
+ }
+ return nil
+}
+
+// Stream allows a server to process a streaming Call directly and act like a
+// client to itself. This is mostly useful because libp2p does not allow to
+// create streams between a server and a client which share the same host. See
+// NewClientWithServer() for more info.
+func (server *Server) serverStream(call *Call) error {
+ service, mtype, err := server.getService(call.SvcID)
+ if err != nil {
+ return newServerError(err)
+ }
+
+ ctx := context.WithValue(call.ctx, ContextKeyRequestSender, server.ID()) // add local peer id as request sender
+
+ if !mtype.streamingArg || !mtype.streamingReply {
+ return fmt.Errorf("%s is not a streaming method", call.SvcID)
+ }
+
+ if call.StreamArgs.Type().Elem() != mtype.ArgType {
+ return fmt.Errorf("%s send channel is of wrong type", call.SvcID)
+ }
+
+ if call.StreamReplies.Type().Elem() != mtype.ReplyType {
+ return fmt.Errorf("%s receive channel is of wrong type", call.SvcID)
+ }
+
+ // This is easier than streaming as we can just plug the calls arguments
+ // into the function and let it deal with it.
+ ctxv := reflect.ValueOf(ctx)
+
+ function := mtype.method.Func
+ returnValues := function.Call([]reflect.Value{service.rcvr, ctxv, call.StreamArgs, call.StreamReplies})
+
+ // The return value for the method is an error.
+ errInter := returnValues[0].Interface()
+ if errInter != nil {
+ return errInter.(error)
+ }
+ return nil
+}
+
+func (server *Server) getService(id ServiceID) (*service, *methodType, error) {
+ // Look up the request.
+ server.mu.RLock()
+ service := server.serviceMap[id.Name]
+ server.mu.RUnlock()
+ if service == nil {
+ err := errors.New("rpc: can't find service " + id.Name)
+ return nil, nil, newServerError(err)
+ }
+ mtype := service.method[id.Method]
+ if mtype == nil {
+ err := errors.New("rpc: can't find method " + id.Method)
+ return nil, nil, newServerError(err)
+ }
+ return service, mtype, nil
+}
+
+func drainChannel(ch reflect.Value) {
+ for {
+ if _, ok := ch.Recv(); !ok {
+ return
+ }
+ }
+}
+
+// All code below is provided under:
+// Copyright (c) 2009 The Go Authors. All rights reserved.
+// and the corresponding license. See LICENSE for more details.
+
+// Is this an exported - upper case - name?
+func isExported(name string) bool {
+ rune, _ := utf8.DecodeRuneInString(name)
+ return unicode.IsUpper(rune)
+}
+
+// Is this type exported or a builtin?
+func isExportedOrBuiltinType(t reflect.Type) bool {
+ for t.Kind() == reflect.Ptr {
+ t = t.Elem()
+ }
+ // PkgPath will be non-empty even for an exported type,
+ // so we need to check the type name as well.
+ return isExported(t.Name()) || t.PkgPath() == ""
+}
+
+// Register publishes in the server the set of methods of the
+// receiver value that satisfy the following conditions:
+// - exported method of exported type
+// - context as first argument
+// - input as second argument: exported type or channel of exported type
+// - output as third argument: a pointer to a exported type, or a channel of exported type
+// - one return value, of type error.
+// It returns an error if the receiver is not an exported type or has
+// no suitable methods. It also logs the error using package log.
+// The client accesses each method using a string of the form "Type.Method",
+// where Type is the receiver's concrete type.
+func (server *Server) Register(rcvr interface{}) error {
+ return server.register(rcvr, "", false)
+}
+
+// RegisterName is like Register but uses the provided name for the type
+// instead of the receiver's concrete type.
+func (server *Server) RegisterName(name string, rcvr interface{}) error {
+ return server.register(rcvr, name, true)
+}
+
+func (server *Server) register(rcvr interface{}, name string, useName bool) error {
+ server.mu.Lock()
+ defer server.mu.Unlock()
+ if server.serviceMap == nil {
+ server.serviceMap = make(map[string]*service)
+ }
+ s := new(service)
+ s.typ = reflect.TypeOf(rcvr)
+ s.rcvr = reflect.ValueOf(rcvr)
+ sname := reflect.Indirect(s.rcvr).Type().Name()
+ if useName {
+ sname = name
+ }
+ if sname == "" {
+ s := "rpc.Register: no service name for type " + s.typ.String()
+ logger.Error(s)
+ return errors.New(s)
+ }
+ if !isExported(sname) && !useName {
+ s := "rpc.Register: type " + sname + " is not exported"
+ logger.Error(s)
+ return errors.New(s)
+ }
+ if _, present := server.serviceMap[sname]; present {
+ return errors.New("rpc: service already defined: " + sname)
+ }
+ s.name = sname
+
+ // Install the methods
+ s.method = suitableMethods(s.name, s.typ, true)
+
+ if len(s.method) == 0 {
+ str := ""
+
+ // To help the user, see if a pointer receiver would work.
+ method := suitableMethods(s.name, reflect.PtrTo(s.typ), false)
+ if len(method) != 0 {
+ str = "rpc.Register: type " + sname + " has no exported methods of suitable type (hint: pass a pointer to value of that type)"
+ } else {
+ str = "rpc.Register: type " + sname + " has no exported methods of suitable type"
+ }
+ logger.Error(str)
+ return errors.New(str)
+ }
+ server.serviceMap[s.name] = s
+ return nil
+}
+
+// suitableMethods returns suitable Rpc methods of typ, it will report
+// error using log if reportErr is true.
+func suitableMethods(sname string, typ reflect.Type, reportErr bool) map[string]*methodType {
+ methods := make(map[string]*methodType)
+ for m := 0; m < typ.NumMethod(); m++ {
+ method := typ.Method(m)
+ mtype := method.Type
+ mname := method.Name
+ // Method must be exported.
+ if method.PkgPath != "" {
+ continue
+ }
+ // Method needs four ins: receiver, context.Context, *args, *reply.
+ if mtype.NumIn() != 4 {
+ if reportErr {
+ logger.Error("method ", mname, " has wrong number of ins: ", mtype.NumIn())
+ }
+ continue
+ }
+
+ // First argument needs to be a context
+ ctxType := mtype.In(1)
+ ctxIntType := reflect.TypeOf((*context.Context)(nil)).Elem()
+ if !ctxType.Implements(ctxIntType) {
+ if reportErr {
+ logger.Error(mname, "first argument is not a context.Context: ", ctxType)
+ }
+ continue
+ }
+
+ // Second arg must be exported or a channel with an exported type.
+ argType := mtype.In(2)
+ argTypeKind := argType.Kind()
+ streamingArg := false
+
+ switch argTypeKind {
+ case reflect.Chan:
+ aElem := argType.Elem()
+ if !isExportedOrBuiltinType(aElem) {
+ if reportErr {
+ logger.Error(mname, " argument channel type not exported: ", aElem)
+ }
+ continue
+ }
+ if argType.ChanDir() != reflect.RecvDir {
+ if reportErr {
+ logger.Error("method ", mname, " argument channel is not a receive-only channel")
+ }
+ continue
+ }
+ argType = aElem
+ streamingArg = true
+ default:
+ if !isExportedOrBuiltinType(argType) {
+ if reportErr {
+ logger.Error(mname, " argument type not exported: ", argType)
+ }
+ continue
+ }
+ }
+ // Third arg must be a pointer or a channel with an exported type.
+ replyType := mtype.In(3)
+ replyTypeKind := replyType.Kind()
+ streamingReply := false
+ switch replyTypeKind {
+ case reflect.Chan:
+ rElem := replyType.Elem()
+ if !isExportedOrBuiltinType(rElem) {
+ if reportErr {
+ logger.Error("method ", mname, " reply channel type not exp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment