github.com/juju/juju@v0.0.0-20240430160146-1752b71fcf00/core/quota/bson.go (about) 1 // Copyright 2020 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package quota 5 6 import ( 7 "github.com/juju/errors" 8 ) 9 10 var _ Checker = (*BSONTotalSizeChecker)(nil) 11 12 // BSONTotalSizeChecker can be used to verify that the total bson-encoded size 13 // of one or more items does not exceed a particular limit. 14 type BSONTotalSizeChecker struct { 15 maxSize int 16 total int 17 lastErr error 18 } 19 20 // NewBSONTotalSizeChecker returns a BSONTotalSizeChecker instance with the 21 // specified maxSize limit. The maxSize parameter may also be set to zero to 22 // disable quota checks. 23 func NewBSONTotalSizeChecker(maxSize int) *BSONTotalSizeChecker { 24 return &BSONTotalSizeChecker{ 25 maxSize: maxSize, 26 } 27 } 28 29 // Check adds the serialized size of v to the current tally and updates the 30 // checker's error state. 31 func (c *BSONTotalSizeChecker) Check(v interface{}) { 32 if c.lastErr != nil { 33 return 34 } 35 36 size, err := effectiveSize(v) 37 if err != nil { 38 c.lastErr = err 39 return 40 } else if c.maxSize > 0 && c.total+size > c.maxSize { 41 c.lastErr = errors.QuotaLimitExceededf("max allowed size (%d) exceeded", c.maxSize) 42 } 43 44 c.total += size 45 } 46 47 // Outcome returns the check outcome or whether an error occurred within a call 48 // to the Check method. 49 func (c *BSONTotalSizeChecker) Outcome() error { 50 return c.lastErr 51 }