<commit_before>//  Copyright (c) 2015 Couchbase, 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.

// +build debug

// Package metrics provides a bleve.store.KVStore implementation that
// wraps another, real KVStore implementation, and uses go-metrics to
// track runtime performance metrics.
package metrics

import (
	"container/list"
	"encoding/json"
	"fmt"
	"io"
	"sync"
	"time"

	"github.com/blevesearch/bleve/index/store"
	"github.com/blevesearch/bleve/registry"

	"github.com/rcrowley/go-metrics"
)

const Name = "metrics"
const MaxErrors = 100

func init() {
	registry.RegisterKVStore(Name, StoreConstructor)
}

func StoreConstructor(config map[string]interface{}) (store.KVStore, error) {
	name, ok := config["kvStoreName_actual"].(string)
	if !ok || name == "" {
		return nil, fmt.Errorf("metrics: missing kvStoreName_actual,"+
			" config: %#v", config)
	}

	if name == Name {
		return nil, fmt.Errorf("metrics: circular kvStoreName_actual")
	}

	ctr := registry.KVStoreConstructorByName(name)
	if ctr == nil {
		return nil, fmt.Errorf("metrics: no kv store constructor,"+
			" kvStoreName_actual: %s", name)
	}

	kvs, err := ctr(config)
	if err != nil {
		return nil, err
	}

	return NewBleveMetricsStore(kvs), nil
}

func NewBleveMetricsStore(o store.KVStore) *Store {
	return &Store{
		o: o,

		TimerReaderGet:         metrics.NewTimer(),
		TimerReaderIterator:    metrics.NewTimer(),
		TimerWriterGet:         metrics.NewTimer(),
		TimerWriterIterator:    metrics.NewTimer(),
		TimerWriterSet:         metrics.NewTimer(),
		TimerWriterDelete:      metrics.NewTimer(),
		TimerIteratorSeekFirst: metrics.NewTimer(),
		TimerIteratorSeek:      metrics.NewTimer(),
		TimerIteratorNext:      metrics.NewTimer(),
		TimerBatchMerge:        metrics.NewTimer(),
		TimerBatchExecute:      metrics.NewTimer(),

		errors: list.New(),
	}
}

// The following structs are wrappers around "real" bleve kvstore
// implementations.

type Store struct {
	o store.KVStore

	TimerReaderGet         metrics.Timer
	TimerReaderIterator    metrics.Timer
	TimerWriterGet         metrics.Timer
	TimerWriterIterator    metrics.Timer
	TimerWriterSet         metrics.Timer
	TimerWriterDelete      metrics.Timer
	TimerIteratorSeekFirst metrics.Timer
	TimerIteratorSeek      metrics.Timer
	TimerIteratorNext      metrics.Timer
	TimerBatchMerge        metrics.Timer
	TimerBatchExecute      metrics.Timer

	m      sync.Mutex // Protects the fields that follow.
	errors *list.List // Capped list of StoreError's.
}

type StoreError struct {
	Time string
	Op   string
	Err  string
	Key  string
}

type Reader struct {
	s *Store
	o store.KVReader
}

type Writer struct {
	s *Store
	o store.KVWriter
}

type Iterator struct {
	s *Store
	o store.KVIterator
}

type Batch struct {
	s *Store
	o store.KVBatch
}

func (s *Store) Close() error {
	return s.o.Close()
}

func (s *Store) Reader() (store.KVReader, error) {
	o, err := s.o.Reader()
	if err != nil {
		s.AddError("Reader", err, nil)
		return nil, err
	}
	return &Reader{s: s, o: o}, nil
}

func (s *Store) Writer() (store.KVWriter, error) {
	o, err := s.o.Writer()
	if err != nil {
		s.AddError("Writer", err, nil)
		return nil, err
	}
	return &Writer{s: s, o: o}, nil
}

func (s *Store) Actual() store.KVStore {
	return s.o
}

func (w *Reader) BytesSafeAfterClose() bool {
	return w.o.BytesSafeAfterClose()
}

func (w *Reader) Get(key []byte) (v []byte, err error) {
	w.s.TimerReaderGet.Time(func() {
		v, err = w.o.Get(key)
		if err != nil {
			w.s.AddError("Reader.Get", err, key)
		}
	})
	return
}

func (w *Reader) Iterator(key []byte) (i store.KVIterator) {
	w.s.TimerReaderIterator.Time(func() {
		i = &Iterator{s: w.s, o: w.o.Iterator(key)}
	})
	return
}

func (w *Reader) Close() error {
	err := w.o.Close()
	if err != nil {
		w.s.AddError("Reader.Close", err, nil)
	}
	return err
}

func (w *Writer) BytesSafeAfterClose() bool {
	return w.BytesSafeAfterClose()
}

func (w *Writer) Get(key []byte) (v []byte, err error) {
	w.s.TimerWriterGet.Time(func() {
		v, err = w.o.Get(key)
		if err != nil {
			w.s.AddError("Writer.Get", err, key)
		}
	})
	return
}

func (w *Writer) Iterator(key []byte) (i store.KVIterator) {
	w.s.TimerWriterIterator.Time(func() {
		i = &Iterator{s: w.s, o: w.o.Iterator(key)}
	})
	return
}

func (w *Writer) Close() error {
	err := w.o.Close()
	if err != nil {
		w.s.AddError("Writer.Close", err, nil)
	}
	return err
}<commit_msg>fix another metrics BytesSafeAfterClose() loop closes #184<commit_after>//  Copyright (c) 2015 Couchbase, 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.

// +build debug

// Package metrics provides a bleve.store.KVStore implementation that
// wraps another, real KVStore implementation, and uses go-metrics to
// track runtime performance metrics.
package metrics

import (
	"container/list"
	"encoding/json"
	"fmt"
	"io"
	"sync"
	"time"

	"github.com/blevesearch/bleve/index/store"
	"github.com/blevesearch/bleve/registry"

	"github.com/rcrowley/go-metrics"
)

const Name = "metrics"
const MaxErrors = 100

func init() {
	registry.RegisterKVStore(Name, StoreConstructor)
}

func StoreConstructor(config map[string]interface{}) (store.KVStore, error) {
	name, ok := config["kvStoreName_actual"].(string)
	if !ok || name == "" {
		return nil, fmt.Errorf("metrics: missing kvStoreName_actual,"+
			" config: %#v", config)
	}

	if name == Name {
		return nil, fmt.Errorf("metrics: circular kvStoreName_actual")
	}

	ctr := registry.KVStoreConstructorByName(name)
	if ctr == nil {
		return nil, fmt.Errorf("metrics: no kv store constructor,"+
			" kvStoreName_actual: %s", name)
	}

	kvs, err := ctr(config)
	if err != nil {
		return nil, err
	}

	return NewBleveMetricsStore(kvs), nil
}

func NewBleveMetricsStore(o store.KVStore) *Store {
	return &Store{
		o: o,

		TimerReaderGet:         metrics.NewTimer(),
		TimerReaderIterator:    metrics.NewTimer(),
		TimerWriterGet:         metrics.NewTimer(),
		TimerWriterIterator:    metrics.NewTimer(),
		TimerWriterSet:         metrics.NewTimer(),
		TimerWriterDelete:      metrics.NewTimer(),
		TimerIteratorSeekFirst: metrics.NewTimer(),
		TimerIteratorSeek:      metrics.NewTimer(),
		TimerIteratorNext:      metrics.NewTimer(),
		TimerBatchMerge:        metrics.NewTimer(),
		TimerBatchExecute:      metrics.NewTimer(),

		errors: list.New(),
	}
}

// The following structs are wrappers around "real" bleve kvstore
// implementations.

type Store struct {
	o store.KVStore

	TimerReaderGet         metrics.Timer
	TimerReaderIterator    metrics.Timer
	TimerWriterGet         metrics.Timer
	TimerWriterIterator    metrics.Timer
	TimerWriterSet         metrics.Timer
	TimerWriterDelete      metrics.Timer
	TimerIteratorSeekFirst metrics.Timer
	TimerIteratorSeek      metrics.Timer
	TimerIteratorNext      metrics.Timer
	TimerBatchMerge        metrics.Timer
	TimerBatchExecute      metrics.Timer

	m      sync.Mutex // Protects the fields that follow.
	errors *list.List // Capped list of StoreError's.
}

type StoreError struct {
	Time string
	Op   string
	Err  string
	Key  string
}

type Reader struct {
	s *Store
	o store.KVReader
}

type Writer struct {
	s *Store
	o store.KVWriter
}

type Iterator struct {
	s *Store
	o store.KVIterator
}

type Batch struct {
	s *Store
	o store.KVBatch
}

func (s *Store) Close() error {
	return s.o.Close()
}

func (s *Store) Reader() (store.KVReader, error) {
	o, err := s.o.Reader()
	if err != nil {
		s.AddError("Reader", err, nil)
		return nil, err
	}
	return &Reader{s: s, o: o}, nil
}

func (s *Store) Writer() (store.KVWriter, error) {
	o, err := s.o.Writer()
	if err != nil {
		s.AddError("Writer", err, nil)
		return nil, err
	}
	return &Writer{s: s, o: o}, nil
}

func (s *Store) Actual() store.KVStore {
	return s.o
}

func (w *Reader) BytesSafeAfterClose() bool {
	return w.o.BytesSafeAfterClose()
}

func (w *Reader) Get(key []byte) (v []byte, err error) {
	w.s.TimerReaderGet.Time(func() {
		v, err = w.o.Get(key)
		if err != nil {
			w.s.AddError("Reader.Get", err, key)
		}
	})
	return
}

func (w *Reader) Iterator(key []byte) (i store.KVIterator) {
	w.s.TimerReaderIterator.Time(func() {
		i = &Iterator{s: w.s, o: w.o.Iterator(key)}
	})
	return
}

func (w *Reader) Close() error {
	err := w.o.Close()
	if err != nil {
		w.s.AddError("Reader.Close", err, nil)
	}
	return err
}

func (w *Writer) BytesSafeAfterClose() bool {
	return w.o.BytesSafeAfterClose()
}

func (w *Writer) Get(key []byte) (v []byte, err error) {
	w.s.TimerWriterGet.Time(func() {
		v, err = w.o.Get(key)
		if err != nil {
			w.s.AddError("Writer.Get", err, key)
		}
	})
	return
}

func (w *Writer) Iterator(key []byte) (i store.KVIterator) {
	w.s.TimerWriterIterator.Time(func() {
		i = &Iterator{s: w.s, o: w.o.Iterator(key)}
	})
	return
}

func (w *Writer) Close() error {
	err := w.o.Close()
	if err != nil {
		w.s.AddError("Writer.Close", err, nil)
	}
	return err
}
{'fraction_non_alphanumeric': 0.13071233154321613, 'fraction_numerical': 0.00253318471982977, 'mean_word_length': 3.535845588235294, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2205257', 'n_tokens_mistral': 3522, 'n_tokens_neox': 3403, 'n_words': 960}