github.com/sethvargo/go-limiter@v1.0.0/store.go (about) 1 package limiter 2 3 import ( 4 "context" 5 "fmt" 6 "time" 7 ) 8 9 // ErrStopped is the error returned when the store is stopped. All implementers 10 // should return this error for stoppable stores. 11 var ErrStopped = fmt.Errorf("store is stopped") 12 13 // Store is an interface for limiter storage backends. 14 // 15 // Keys should be hash, sanitized, or otherwise scrubbed of identifiable 16 // information they will be given to the store in plaintext. If you're rate 17 // limiting by IP address, for example, the IP address would be stored in the 18 // storage system in plaintext. This may be undesirable in certain situations, 19 // like when the store is a public database. In those cases, you should hash or 20 // HMAC the key before passing giving it to the store. If you want to encrypt 21 // the value, you must use homomorphic encryption to ensure the value always 22 // encrypts to the same ciphertext. 23 type Store interface { 24 // Take takes a token from the given key if available, returning: 25 // 26 // - the configured limit size 27 // - the number of remaining tokens in the interval 28 // - the server time when new tokens will be available 29 // - whether the take was successful 30 // - any errors that occurred while performing the take - these should be 31 // backend errors (e.g. connection failures); Take() should never return an 32 // error for an bucket. 33 // 34 // If "ok" is false, the take was unsuccessful and the caller should NOT 35 // service the request. 36 // 37 // See the note about keys on the interface documentation. 38 Take(ctx context.Context, key string) (tokens, remaining, reset uint64, ok bool, err error) 39 40 // Get gets the current limit and remaining tokens for the provided key. It 41 // does not change any of the values. 42 Get(ctx context.Context, key string) (tokens, remaining uint64, err error) 43 44 // Set configures the limit at the provided key. If a limit already exists, it 45 // is overwritten. This also sets the number of tokens in the bucket to the 46 // limit. 47 Set(ctx context.Context, key string, tokens uint64, interval time.Duration) error 48 49 // Burst adds more tokens to the key's current bucket until the next interval 50 // tick. This will allow the current bucket tick to exceed the maximum number 51 // maximum ticks until the next interval. 52 Burst(ctx context.Context, key string, tokens uint64) error 53 54 // Close terminates the store and cleans up any data structures or connections 55 // that may remain open. After a store is stopped, Take() should always return 56 // zero values. 57 Close(ctx context.Context) error 58 }