tendermint: github.com/tendermint/tendermint/libs/common Index | Files

package common

import "github.com/tendermint/tendermint/libs/common"

nolint: dupl dupl is reading this as the same file as crypto/merkle/result.go

Index

Package Files

async.go bit_array.go bytes.go byteslice.go cmap.go errors.go int.go kvpair.go math.go net.go nil.go os.go random.go result.go service.go string.go tempfile.go throttle_timer.go types.pb.go

Variables

var (
    // ErrAlreadyStarted is returned when somebody tries to start an already
    // running service.
    ErrAlreadyStarted = errors.New("already started")
    // ErrAlreadyStopped is returned when somebody tries to stop an already
    // stopped service (without resetting it).
    ErrAlreadyStopped = errors.New("already stopped")
    // ErrNotStarted is returned when somebody tries to stop a not running
    // service.
    ErrNotStarted = errors.New("not started")
)
var (
    ErrInvalidLengthTypes = fmt.Errorf("proto: negative length found during unmarshaling")
    ErrIntOverflowTypes   = fmt.Errorf("proto: integer overflow")
)

func ASCIITrim Uses

func ASCIITrim(s string) string

NOTE: Assumes that s is ASCII as per IsASCIIText(), otherwise panics.

func Connect Uses

func Connect(protoAddr string) (net.Conn, error)

Connect dials the given address and returns a net.Conn. The protoAddr argument should be prefixed with the protocol, eg. "tcp://127.0.0.1:8080" or "unix:///tmp/test.sock"

func EnsureDir Uses

func EnsureDir(dir string, mode os.FileMode) error

func Exit Uses

func Exit(s string)

func FileExists Uses

func FileExists(filePath string) bool

func Fingerprint Uses

func Fingerprint(slice []byte) []byte

Fingerprint returns the first 6 bytes of a byte slice. If the slice is less than 6 bytes, the fingerprint contains trailing zeroes.

func GetFreePort Uses

func GetFreePort() (int, error)

GetFreePort gets a free port from the operating system. Ripped from https://github.com/phayes/freeport. BSD-licensed.

func IntInSlice Uses

func IntInSlice(a int, list []int) bool

IntInSlice returns true if a is found in the list.

func IsASCIIText Uses

func IsASCIIText(s string) bool

Returns true if s is a non-empty printable non-tab ascii character.

func IsEmpty Uses

func IsEmpty(o interface{}) bool

Returns true if it has zero length.

func IsTypedNil Uses

func IsTypedNil(o interface{}) bool

Go lacks a simple and safe way to see if something is a typed nil. See:

- https://dave.cheney.net/2017/08/09/typed-nils-in-go-2
- https://groups.google.com/forum/#!topic/golang-nuts/wnH302gBa4I/discussion
- https://github.com/golang/go/issues/21538

func Kill Uses

func Kill() error

Kill the running process by sending itself SIGTERM.

func MaxInt Uses

func MaxInt(a, b int) int

func MaxInt64 Uses

func MaxInt64(a, b int64) int64

func MinInt Uses

func MinInt(a, b int) int

func MinInt64 Uses

func MinInt64(a, b int64) int64

func MustReadFile Uses

func MustReadFile(filePath string) []byte

func MustWriteFile Uses

func MustWriteFile(filePath string, contents []byte, mode os.FileMode)

func ProtocolAndAddress Uses

func ProtocolAndAddress(listenAddr string) (string, string)

ProtocolAndAddress splits an address into the protocol and address components. For instance, "tcp://127.0.0.1:8080" will be split into "tcp" and "127.0.0.1:8080". If the address has no protocol prefix, the default is "tcp".

func RandBool Uses

func RandBool() bool

func RandBytes Uses

func RandBytes(n int) []byte

func RandFloat32 Uses

func RandFloat32() float32

func RandFloat64 Uses

func RandFloat64() float64

func RandInt Uses

func RandInt() int

func RandInt16 Uses

func RandInt16() int16

func RandInt31 Uses

func RandInt31() int32

func RandInt31n Uses

func RandInt31n(n int32) int32

func RandInt32 Uses

func RandInt32() int32

func RandInt63 Uses

func RandInt63() int64

func RandInt63n Uses

func RandInt63n(n int64) int64

func RandInt64 Uses

func RandInt64() int64

func RandIntn Uses

func RandIntn(n int) int

func RandPerm Uses

func RandPerm(n int) []int

func RandStr Uses

func RandStr(length int) string

func RandTime Uses

func RandTime() time.Time

func RandUint Uses

func RandUint() uint

func RandUint16 Uses

func RandUint16() uint16

func RandUint32 Uses

func RandUint32() uint32

func RandUint64 Uses

func RandUint64() uint64

func ReadFile Uses

func ReadFile(filePath string) ([]byte, error)

func Seed Uses

func Seed(seed int64)

func SplitAndTrim Uses

func SplitAndTrim(s, sep, cutset string) []string

SplitAndTrim slices s into all subslices separated by sep and returns a slice of the string s with all leading and trailing Unicode code points contained in cutset removed. If sep is empty, SplitAndTrim splits after each UTF-8 sequence. First part is equivalent to strings.SplitN with a count of -1.

func StringInSlice Uses

func StringInSlice(a string, list []string) bool

StringInSlice returns true if a is found the list.

func StringSliceEqual Uses

func StringSliceEqual(a, b []string) bool

StringSliceEqual checks if string slices a and b are equal

func TrapSignal Uses

func TrapSignal(logger logger, cb func())

TrapSignal catches the SIGTERM/SIGINT and executes cb function. After that it exits with code 0.

func WriteFile Uses

func WriteFile(filePath string, contents []byte, mode os.FileMode) error

func WriteFileAtomic Uses

func WriteFileAtomic(filename string, data []byte, perm os.FileMode) (err error)

WriteFileAtomic creates a temporary file with data and provided perm and swaps it atomically with filename if successful.

type BaseService Uses

type BaseService struct {
    Logger log.Logger
    // contains filtered or unexported fields
}

Classical-inheritance-style service declarations. Services can be started, then stopped, then optionally restarted.

Users can override the OnStart/OnStop methods. In the absence of errors, these methods are guaranteed to be called at most once. If OnStart returns an error, service won't be marked as started, so the user can call Start again.

A call to Reset will panic, unless OnReset is overwritten, allowing OnStart/OnStop to be called again.

The caller must ensure that Start and Stop are not called concurrently.

It is ok to call Stop without calling Start first.

Typical usage:

type FooService struct {
	BaseService
	// private fields
}

func NewFooService() *FooService {
	fs := &FooService{
		// init
	}
	fs.BaseService = *NewBaseService(log, "FooService", fs)
	return fs
}

func (fs *FooService) OnStart() error {
	fs.BaseService.OnStart() // Always call the overridden method.
	// initialize private fields
	// start subroutines, etc.
}

func (fs *FooService) OnStop() error {
	fs.BaseService.OnStop() // Always call the overridden method.
	// close/destroy private fields
	// stop subroutines, etc.
}

func NewBaseService Uses

func NewBaseService(logger log.Logger, name string, impl Service) *BaseService

NewBaseService creates a new BaseService.

func (*BaseService) IsRunning Uses

func (bs *BaseService) IsRunning() bool

IsRunning implements Service by returning true or false depending on the service's state.

func (*BaseService) OnReset Uses

func (bs *BaseService) OnReset() error

OnReset implements Service by panicking.

func (*BaseService) OnStart Uses

func (bs *BaseService) OnStart() error

OnStart implements Service by doing nothing. NOTE: Do not put anything in here, that way users don't need to call BaseService.OnStart()

func (*BaseService) OnStop Uses

func (bs *BaseService) OnStop()

OnStop implements Service by doing nothing. NOTE: Do not put anything in here, that way users don't need to call BaseService.OnStop()

func (*BaseService) Quit Uses

func (bs *BaseService) Quit() <-chan struct{}

Quit Implements Service by returning a quit channel.

func (*BaseService) Reset Uses

func (bs *BaseService) Reset() error

Reset implements Service by calling OnReset callback (if defined). An error will be returned if the service is running.

func (*BaseService) SetLogger Uses

func (bs *BaseService) SetLogger(l log.Logger)

SetLogger implements Service by setting a logger.

func (*BaseService) Start Uses

func (bs *BaseService) Start() error

Start implements Service by calling OnStart (if defined). An error will be returned if the service is already running or stopped. Not to start the stopped service, you need to call Reset.

func (*BaseService) Stop Uses

func (bs *BaseService) Stop() error

Stop implements Service by calling OnStop (if defined) and closing quit channel. An error will be returned if the service is already stopped.

func (*BaseService) String Uses

func (bs *BaseService) String() string

String implements Service by returning a string representation of the service.

func (*BaseService) Wait Uses

func (bs *BaseService) Wait()

Wait blocks until the service is stopped.

type BitArray Uses

type BitArray struct {
    Bits  int      `json:"bits"`  // NOTE: persisted via reflect, must be exported
    Elems []uint64 `json:"elems"` // NOTE: persisted via reflect, must be exported
    // contains filtered or unexported fields
}

BitArray is a thread-safe implementation of a bit array.

func NewBitArray Uses

func NewBitArray(bits int) *BitArray

NewBitArray returns a new bit array. It returns nil if the number of bits is zero.

func (*BitArray) And Uses

func (bA *BitArray) And(o *BitArray) *BitArray

And returns a bit array resulting from a bitwise AND of the two bit arrays. If the two bit-arrys have different lengths, this truncates the larger of the two bit-arrays from the right. Thus the size of the return value is the minimum of the two provided bit arrays.

func (*BitArray) Bytes Uses

func (bA *BitArray) Bytes() []byte

Bytes returns the byte representation of the bits within the bitarray.

func (*BitArray) Copy Uses

func (bA *BitArray) Copy() *BitArray

Copy returns a copy of the provided bit array.

func (*BitArray) GetIndex Uses

func (bA *BitArray) GetIndex(i int) bool

GetIndex returns the bit at index i within the bit array. The behavior is undefined if i >= bA.Bits

func (*BitArray) IsEmpty Uses

func (bA *BitArray) IsEmpty() bool

IsEmpty returns true iff all bits in the bit array are 0

func (*BitArray) IsFull Uses

func (bA *BitArray) IsFull() bool

IsFull returns true iff all bits in the bit array are 1.

func (*BitArray) MarshalJSON Uses

func (bA *BitArray) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler interface by marshaling bit array using a custom format: a string of '-' or 'x' where 'x' denotes the 1 bit.

func (*BitArray) Not Uses

func (bA *BitArray) Not() *BitArray

Not returns a bit array resulting from a bitwise Not of the provided bit array.

func (*BitArray) Or Uses

func (bA *BitArray) Or(o *BitArray) *BitArray

Or returns a bit array resulting from a bitwise OR of the two bit arrays. If the two bit-arrys have different lengths, Or right-pads the smaller of the two bit-arrays with zeroes. Thus the size of the return value is the maximum of the two provided bit arrays.

func (*BitArray) PickRandom Uses

func (bA *BitArray) PickRandom() (int, bool)

PickRandom returns a random index for a set bit in the bit array. If there is no such value, it returns 0, false. It uses the global randomness in `random.go` to get this index.

func (*BitArray) SetIndex Uses

func (bA *BitArray) SetIndex(i int, v bool) bool

SetIndex sets the bit at index i within the bit array. The behavior is undefined if i >= bA.Bits

func (*BitArray) Size Uses

func (bA *BitArray) Size() int

Size returns the number of bits in the bitarray

func (*BitArray) String Uses

func (bA *BitArray) String() string

String returns a string representation of BitArray: BA{<bit-string>}, where <bit-string> is a sequence of 'x' (1) and '_' (0). The <bit-string> includes spaces and newlines to help people. For a simple sequence of 'x' and '_' characters with no spaces or newlines, see the MarshalJSON() method. Example: "BA{_x_}" or "nil-BitArray" for nil.

func (*BitArray) StringIndented Uses

func (bA *BitArray) StringIndented(indent string) string

StringIndented returns the same thing as String(), but applies the indent at every 10th bit, and twice at every 50th bit.

func (*BitArray) Sub Uses

func (bA *BitArray) Sub(o *BitArray) *BitArray

Sub subtracts the two bit-arrays bitwise, without carrying the bits. Note that carryless subtraction of a - b is (a and not b). The output is the same as bA, regardless of o's size. If bA is longer than o, o is right padded with zeroes

func (*BitArray) UnmarshalJSON Uses

func (bA *BitArray) UnmarshalJSON(bz []byte) error

UnmarshalJSON implements json.Unmarshaler interface by unmarshaling a custom JSON description.

func (*BitArray) Update Uses

func (bA *BitArray) Update(o *BitArray)

Update sets the bA's bits to be that of the other bit array. The copying begins from the begin of both bit arrays.

type CMap Uses

type CMap struct {
    // contains filtered or unexported fields
}

CMap is a goroutine-safe map

func NewCMap Uses

func NewCMap() *CMap

func (*CMap) Clear Uses

func (cm *CMap) Clear()

func (*CMap) Delete Uses

func (cm *CMap) Delete(key string)

func (*CMap) Get Uses

func (cm *CMap) Get(key string) interface{}

func (*CMap) Has Uses

func (cm *CMap) Has(key string) bool

func (*CMap) Keys Uses

func (cm *CMap) Keys() []string

func (*CMap) Set Uses

func (cm *CMap) Set(key string, value interface{})

func (*CMap) Size Uses

func (cm *CMap) Size() int

func (*CMap) Values Uses

func (cm *CMap) Values() []interface{}

type Error Uses

type Error interface {
    Error() string
    Stacktrace() Error
    Trace(offset int, format string, args ...interface{}) Error
    Data() interface{}
}

Usage with arbitrary error data:

“`go

// Error construction
type MyError struct{}
var err1 error = NewErrorWithData(MyError{}, "my message")
...
// Wrapping
var err2 error  = ErrorWrap(err1, "another message")
if (err1 != err2) { panic("should be the same")
...
// Error handling
switch err2.Data().(type){
	case MyError: ...
    default: ...
}

“`

func ErrorWrap Uses

func ErrorWrap(cause interface{}, format string, args ...interface{}) Error

func NewError Uses

func NewError(format string, args ...interface{}) Error

New Error with formatted message. The Error's Data will be a FmtError type.

func NewErrorWithData Uses

func NewErrorWithData(data interface{}) Error

New Error with specified data.

type FmtError Uses

type FmtError struct {
    // contains filtered or unexported fields
}

FmtError is the data type for NewError() (e.g. NewError().Data().(FmtError)) Theoretically it could be used to switch on the format string.

“`go

// Error construction
var err1 error = NewError("invalid username %v", "BOB")
var err2 error = NewError("another kind of error")
...
// Error handling
switch err1.Data().(cmn.FmtError).Format() {
	case "invalid username %v": ...
	case "another kind of error": ...
    default: ...
}

“`

func (FmtError) Error Uses

func (fe FmtError) Error() string

func (FmtError) Format Uses

func (fe FmtError) Format() string

func (FmtError) String Uses

func (fe FmtError) String() string

type HexBytes Uses

type HexBytes []byte

The main purpose of HexBytes is to enable HEX-encoding for json/encoding.

func (HexBytes) Bytes Uses

func (bz HexBytes) Bytes() []byte

Allow it to fulfill various interfaces in light-client, etc...

func (HexBytes) Format Uses

func (bz HexBytes) Format(s fmt.State, verb rune)

func (HexBytes) Marshal Uses

func (bz HexBytes) Marshal() ([]byte, error)

Marshal needed for protobuf compatibility

func (HexBytes) MarshalJSON Uses

func (bz HexBytes) MarshalJSON() ([]byte, error)

This is the point of Bytes.

func (HexBytes) String Uses

func (bz HexBytes) String() string

func (*HexBytes) Unmarshal Uses

func (bz *HexBytes) Unmarshal(data []byte) error

Unmarshal needed for protobuf compatibility

func (*HexBytes) UnmarshalJSON Uses

func (bz *HexBytes) UnmarshalJSON(data []byte) error

This is the point of Bytes.

type KI64Pair Uses

type KI64Pair struct {
    Key                  []byte   `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"`
    Value                int64    `protobuf:"varint,2,opt,name=value,proto3" json:"value,omitempty"`
    XXX_NoUnkeyedLiteral struct{} `json:"-"`
    XXX_unrecognized     []byte   `json:"-"`
    XXX_sizecache        int32    `json:"-"`
}

Define these here for compatibility but use tmlibs/common.KI64Pair.

func NewPopulatedKI64Pair Uses

func NewPopulatedKI64Pair(r randyTypes, easy bool) *KI64Pair

func (*KI64Pair) Descriptor Uses

func (*KI64Pair) Descriptor() ([]byte, []int)

func (*KI64Pair) Equal Uses

func (this *KI64Pair) Equal(that interface{}) bool

func (*KI64Pair) GetKey Uses

func (m *KI64Pair) GetKey() []byte

func (*KI64Pair) GetValue Uses

func (m *KI64Pair) GetValue() int64

func (*KI64Pair) Marshal Uses

func (m *KI64Pair) Marshal() (dAtA []byte, err error)

func (*KI64Pair) MarshalJSON Uses

func (r *KI64Pair) MarshalJSON() ([]byte, error)

func (*KI64Pair) MarshalTo Uses

func (m *KI64Pair) MarshalTo(dAtA []byte) (int, error)

func (*KI64Pair) MarshalToSizedBuffer Uses

func (m *KI64Pair) MarshalToSizedBuffer(dAtA []byte) (int, error)

func (*KI64Pair) ProtoMessage Uses

func (*KI64Pair) ProtoMessage()

func (*KI64Pair) Reset Uses

func (m *KI64Pair) Reset()

func (*KI64Pair) Size Uses

func (m *KI64Pair) Size() (n int)

func (*KI64Pair) String Uses

func (m *KI64Pair) String() string

func (*KI64Pair) Unmarshal Uses

func (m *KI64Pair) Unmarshal(dAtA []byte) error

func (*KI64Pair) UnmarshalJSON Uses

func (r *KI64Pair) UnmarshalJSON(b []byte) error

func (*KI64Pair) XXX_DiscardUnknown Uses

func (m *KI64Pair) XXX_DiscardUnknown()

func (*KI64Pair) XXX_Marshal Uses

func (m *KI64Pair) XXX_Marshal(b []byte, deterministic bool) ([]byte, error)

func (*KI64Pair) XXX_Merge Uses

func (m *KI64Pair) XXX_Merge(src proto.Message)

func (*KI64Pair) XXX_Size Uses

func (m *KI64Pair) XXX_Size() int

func (*KI64Pair) XXX_Unmarshal Uses

func (m *KI64Pair) XXX_Unmarshal(b []byte) error

type KI64Pairs Uses

type KI64Pairs []KI64Pair

func (KI64Pairs) Len Uses

func (kvs KI64Pairs) Len() int

Sorting

func (KI64Pairs) Less Uses

func (kvs KI64Pairs) Less(i, j int) bool

func (KI64Pairs) Sort Uses

func (kvs KI64Pairs) Sort()

func (KI64Pairs) Swap Uses

func (kvs KI64Pairs) Swap(i, j int)

type KVPair Uses

type KVPair struct {
    Key                  []byte   `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"`
    Value                []byte   `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`
    XXX_NoUnkeyedLiteral struct{} `json:"-"`
    XXX_unrecognized     []byte   `json:"-"`
    XXX_sizecache        int32    `json:"-"`
}

Define these here for compatibility but use tmlibs/common.KVPair.

func NewPopulatedKVPair Uses

func NewPopulatedKVPair(r randyTypes, easy bool) *KVPair

func (*KVPair) Descriptor Uses

func (*KVPair) Descriptor() ([]byte, []int)

func (*KVPair) Equal Uses

func (this *KVPair) Equal(that interface{}) bool

func (*KVPair) GetKey Uses

func (m *KVPair) GetKey() []byte

func (*KVPair) GetValue Uses

func (m *KVPair) GetValue() []byte

func (*KVPair) Marshal Uses

func (m *KVPair) Marshal() (dAtA []byte, err error)

func (*KVPair) MarshalJSON Uses

func (r *KVPair) MarshalJSON() ([]byte, error)

func (*KVPair) MarshalTo Uses

func (m *KVPair) MarshalTo(dAtA []byte) (int, error)

func (*KVPair) MarshalToSizedBuffer Uses

func (m *KVPair) MarshalToSizedBuffer(dAtA []byte) (int, error)

func (*KVPair) ProtoMessage Uses

func (*KVPair) ProtoMessage()

func (*KVPair) Reset Uses

func (m *KVPair) Reset()

func (*KVPair) Size Uses

func (m *KVPair) Size() (n int)

func (*KVPair) String Uses

func (m *KVPair) String() string

func (*KVPair) Unmarshal Uses

func (m *KVPair) Unmarshal(dAtA []byte) error

func (*KVPair) UnmarshalJSON Uses

func (r *KVPair) UnmarshalJSON(b []byte) error

func (*KVPair) XXX_DiscardUnknown Uses

func (m *KVPair) XXX_DiscardUnknown()

func (*KVPair) XXX_Marshal Uses

func (m *KVPair) XXX_Marshal(b []byte, deterministic bool) ([]byte, error)

func (*KVPair) XXX_Merge Uses

func (m *KVPair) XXX_Merge(src proto.Message)

func (*KVPair) XXX_Size Uses

func (m *KVPair) XXX_Size() int

func (*KVPair) XXX_Unmarshal Uses

func (m *KVPair) XXX_Unmarshal(b []byte) error

type KVPairs Uses

type KVPairs []KVPair

func (KVPairs) Len Uses

func (kvs KVPairs) Len() int

Sorting

func (KVPairs) Less Uses

func (kvs KVPairs) Less(i, j int) bool

func (KVPairs) Sort Uses

func (kvs KVPairs) Sort()

func (KVPairs) Swap Uses

func (kvs KVPairs) Swap(i, j int)

type Rand Uses

type Rand struct {
    sync.Mutex
    // contains filtered or unexported fields
}

Rand is a prng, that is seeded with OS randomness. The OS randomness is obtained from crypto/rand, however none of the provided methods are suitable for cryptographic usage. They all utilize math/rand's prng internally.

All of the methods here are suitable for concurrent use. This is achieved by using a mutex lock on all of the provided methods.

func NewRand Uses

func NewRand() *Rand

func (*Rand) Bool Uses

func (r *Rand) Bool() bool

Bool returns a uniformly random boolean

func (*Rand) Bytes Uses

func (r *Rand) Bytes(n int) []byte

Bytes returns n random bytes generated from the internal prng.

func (*Rand) Float32 Uses

func (r *Rand) Float32() float32

func (*Rand) Float64 Uses

func (r *Rand) Float64() float64

func (*Rand) Int Uses

func (r *Rand) Int() int

func (*Rand) Int16 Uses

func (r *Rand) Int16() int16

func (*Rand) Int31 Uses

func (r *Rand) Int31() int32

func (*Rand) Int31n Uses

func (r *Rand) Int31n(n int32) int32

func (*Rand) Int32 Uses

func (r *Rand) Int32() int32

func (*Rand) Int63 Uses

func (r *Rand) Int63() int64

func (*Rand) Int63n Uses

func (r *Rand) Int63n(n int64) int64

func (*Rand) Int64 Uses

func (r *Rand) Int64() int64

func (*Rand) Intn Uses

func (r *Rand) Intn(n int) int

Intn returns, as an int, a uniform pseudo-random number in the range [0, n). It panics if n <= 0.

func (*Rand) Perm Uses

func (r *Rand) Perm(n int) []int

Perm returns a pseudo-random permutation of n integers in [0, n).

func (*Rand) Seed Uses

func (r *Rand) Seed(seed int64)

func (*Rand) Str Uses

func (r *Rand) Str(length int) string

Str constructs a random alphanumeric string of given length.

func (*Rand) Time Uses

func (r *Rand) Time() time.Time

func (*Rand) Uint Uses

func (r *Rand) Uint() uint

func (*Rand) Uint16 Uses

func (r *Rand) Uint16() uint16

func (*Rand) Uint32 Uses

func (r *Rand) Uint32() uint32

func (*Rand) Uint64 Uses

func (r *Rand) Uint64() uint64

type Service Uses

type Service interface {
    // Start the service.
    // If it's already started or stopped, will return an error.
    // If OnStart() returns an error, it's returned by Start()
    Start() error
    OnStart() error

    // Stop the service.
    // If it's already stopped, will return an error.
    // OnStop must never error.
    Stop() error
    OnStop()

    // Reset the service.
    // Panics by default - must be overwritten to enable reset.
    Reset() error
    OnReset() error

    // Return true if the service is running
    IsRunning() bool

    // Quit returns a channel, which is closed once service is stopped.
    Quit() <-chan struct{}

    // String representation of the service
    String() string

    // SetLogger sets a logger.
    SetLogger(log.Logger)
}

Service defines a service that can be started, stopped, and reset.

type Task Uses

type Task func(i int) (val interface{}, err error, abort bool)

val: the value returned after task execution. err: the error returned during task completion. abort: tells Parallel to return, whether or not all tasks have completed.

type TaskResult Uses

type TaskResult struct {
    Value interface{}
    Error error
}

type TaskResultCh Uses

type TaskResultCh <-chan TaskResult

type TaskResultSet Uses

type TaskResultSet struct {
    // contains filtered or unexported fields
}

func Parallel Uses

func Parallel(tasks ...Task) (trs *TaskResultSet, ok bool)

Run tasks in parallel, with ability to abort early. Returns ok=false iff any of the tasks returned abort=true. NOTE: Do not implement quit features here. Instead, provide convenient concurrent quit-like primitives, passed implicitly via Task closures. (e.g. it's not Parallel's concern how you quit/abort your tasks).

func (*TaskResultSet) Channels Uses

func (trs *TaskResultSet) Channels() []TaskResultCh

func (*TaskResultSet) FirstError Uses

func (trs *TaskResultSet) FirstError() error

Returns the firstmost (by task index) error as discovered by all previous Reap() calls.

func (*TaskResultSet) FirstValue Uses

func (trs *TaskResultSet) FirstValue() interface{}

Returns the firstmost (by task index) error as discovered by all previous Reap() calls.

func (*TaskResultSet) LatestResult Uses

func (trs *TaskResultSet) LatestResult(index int) (TaskResult, bool)

func (*TaskResultSet) Reap Uses

func (trs *TaskResultSet) Reap() *TaskResultSet

NOTE: Not concurrency safe. Writes results to trs.results without waiting for all tasks to complete.

func (*TaskResultSet) Wait Uses

func (trs *TaskResultSet) Wait() *TaskResultSet

NOTE: Not concurrency safe. Like Reap() but waits until all tasks have returned or panic'd.

type ThrottleTimer Uses

type ThrottleTimer struct {
    Name string
    Ch   chan struct{}
    // contains filtered or unexported fields
}

ThrottleTimer fires an event at most "dur" after each .Set() call. If a short burst of .Set() calls happens, ThrottleTimer fires once. If a long continuous burst of .Set() calls happens, ThrottleTimer fires at most once every "dur".

func NewThrottleTimer Uses

func NewThrottleTimer(name string, dur time.Duration) *ThrottleTimer

func (*ThrottleTimer) Set Uses

func (t *ThrottleTimer) Set()

func (*ThrottleTimer) Stop Uses

func (t *ThrottleTimer) Stop() bool

For ease of .Stop()'ing services before .Start()'ing them, we ignore .Stop()'s on nil ThrottleTimers

func (*ThrottleTimer) Unset Uses

func (t *ThrottleTimer) Unset()

Package common imports 31 packages (graph) and is imported by 314 packages. Updated 2019-10-17. Refresh now. Tools for package owners.