gitee.com/lh-her-team/common@v1.5.1/birdsnest/rules.go (about)

     1  // Package birdsnest rules
     2  package birdsnest
     3  
     4  import (
     5  	"errors"
     6  	"time"
     7  )
     8  
     9  type Rule interface {
    10  	Validate(Key) error
    11  }
    12  
    13  var (
    14  	// ErrKeyItsSoLongAgoError key it's so long ago error
    15  	ErrKeyItsSoLongAgoError = errors.New("key is out of the range")
    16  )
    17  
    18  // AbsoluteExpireTimeRule absolute expire time rule
    19  type AbsoluteExpireTimeRule struct {
    20  	absoluteExpireTime int64
    21  	log                Logger
    22  }
    23  
    24  // Validate timestamp key
    25  func (r AbsoluteExpireTimeRule) Validate(key Key) error {
    26  	nano := key.GetNano()
    27  	seconds := time.Now().UnixNano()
    28  	start := seconds - r.absoluteExpireTime
    29  	end := seconds + r.absoluteExpireTime
    30  	if nano < start || nano > end {
    31  		r.log.Warnf("key %v is out of the range %v-%v", key.String(), start, end)
    32  		return ErrKeyItsSoLongAgoError
    33  	}
    34  	return nil
    35  }
    36  
    37  // NewAETRule new absolute expire time rule
    38  func NewAETRule(absoluteExpireTime int64, logger Logger) AbsoluteExpireTimeRule {
    39  	return AbsoluteExpireTimeRule{absoluteExpireTime: absoluteExpireTime * time.Second.Nanoseconds(), log: logger}
    40  }