bosun.org@v0.0.0-20210513094433-e25bc3e69a1f/cmd/bosun/database/config_data.go (about)

     1  package database
     2  
     3  import (
     4  	"crypto/md5"
     5  	"encoding/base64"
     6  	"fmt"
     7  
     8  	"github.com/garyburd/redigo/redis"
     9  
    10  	"bosun.org/slog"
    11  )
    12  
    13  type ConfigDataAccess interface {
    14  	SaveTempConfig(text string) (hash string, err error)
    15  	GetTempConfig(hash string) (text string, err error)
    16  
    17  	ShortenLink(fullURL string) (id int, err error)
    18  	GetShortLink(id int) (fullURL string, err error)
    19  }
    20  
    21  func (d *dataAccess) Configs() ConfigDataAccess {
    22  	return d
    23  }
    24  
    25  const configLifetime = 60 * 24 * 14 // 2 weeks
    26  
    27  func (d *dataAccess) SaveTempConfig(text string) (string, error) {
    28  	conn := d.Get()
    29  	defer conn.Close()
    30  
    31  	sig := md5.Sum([]byte(text))
    32  	b64 := base64.StdEncoding.EncodeToString(sig[0:8])
    33  	if d.isRedis {
    34  		_, err := conn.Do("SET", "tempConfig:"+b64, text, "EX", configLifetime)
    35  		return b64, slog.Wrap(err)
    36  	}
    37  	_, err := conn.Do("SETEX", "tempConfig:"+b64, configLifetime, text)
    38  	return b64, slog.Wrap(err)
    39  }
    40  
    41  func (d *dataAccess) GetTempConfig(hash string) (string, error) {
    42  	conn := d.Get()
    43  	defer conn.Close()
    44  
    45  	key := "tempConfig:" + hash
    46  	dat, err := redis.String(conn.Do("GET", key))
    47  	if err != nil {
    48  		return "", slog.Wrap(err)
    49  	}
    50  	_, err = conn.Do("EXPIRE", key, configLifetime)
    51  	return dat, slog.Wrap(err)
    52  }
    53  
    54  const (
    55  	shortLinkCounterKey = "shortlinkCount"
    56  	shortLinksKey       = "shortLinks"
    57  )
    58  
    59  func (d *dataAccess) ShortenLink(fullURL string) (id int, err error) {
    60  	conn := d.Get()
    61  	defer conn.Close()
    62  
    63  	newID, err := redis.Int(conn.Do("INCR", shortLinkCounterKey))
    64  	if err != nil {
    65  		return 0, slog.Wrap(err)
    66  	}
    67  	if _, err := conn.Do("HSET", shortLinksKey, fmt.Sprint(newID), fullURL); err != nil {
    68  		return 0, slog.Wrap(err)
    69  	}
    70  	return newID, nil
    71  }
    72  
    73  func (d *dataAccess) GetShortLink(id int) (fullURL string, err error) {
    74  	conn := d.Get()
    75  	defer conn.Close()
    76  
    77  	s, err := redis.String(conn.Do("HGET", shortLinksKey, fmt.Sprint(id)))
    78  	if err != nil {
    79  		return "", slog.Wrap(err)
    80  	}
    81  	return s, nil
    82  }