go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/gae/filter/count/count.go (about)

     1  // Copyright 2015 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // Package count contains 'counter' filters for all the gae services. This
    16  // serves as a set of simple example filters, and also enables other filters
    17  // to test to see if certain underlying APIs are called when they should be
    18  // (e.g. for the datastore mcache filter, for example).
    19  package count
    20  
    21  import (
    22  	"fmt"
    23  	"sync/atomic"
    24  )
    25  
    26  type counter struct {
    27  	value int32
    28  }
    29  
    30  func (c *counter) increment() {
    31  	atomic.AddInt32(&c.value, 1)
    32  }
    33  
    34  func (c *counter) get() int {
    35  	return int(atomic.LoadInt32(&c.value))
    36  }
    37  
    38  // Entry is a success/fail pair for a single API method. It's returned
    39  // by the Counter interface.
    40  type Entry struct {
    41  	successes counter
    42  	errors    counter
    43  }
    44  
    45  func (e *Entry) String() string {
    46  	return fmt.Sprintf("{Successes:%d, Errors:%d}", e.Successes(), e.Errors())
    47  }
    48  
    49  // Total is a convenience function for getting the total number of calls to
    50  // this API. It's Successes+Errors.
    51  func (e *Entry) Total() int64 { return int64(e.Successes()) + int64(e.Errors()) }
    52  
    53  // Successes returns the number of successful invocations for this Entry.
    54  func (e *Entry) Successes() int {
    55  	return e.successes.get()
    56  }
    57  
    58  // Errors returns the number of unsuccessful invocations for this Entry.
    59  func (e *Entry) Errors() int {
    60  	return e.errors.get()
    61  }
    62  
    63  func (e *Entry) up(errs ...error) error {
    64  	err := error(nil)
    65  	if len(errs) > 0 {
    66  		err = errs[0]
    67  	}
    68  	if err == nil {
    69  		e.successes.increment()
    70  	} else {
    71  		e.errors.increment()
    72  	}
    73  	return err
    74  }