2019-05-06 00:56:27 +00:00
|
|
|
package repositories
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
|
|
|
|
"github.com/mediocregopher/radix/v3"
|
2019-07-20 08:12:58 +00:00
|
|
|
|
2019-07-11 02:33:22 +00:00
|
|
|
"github.com/mitchell/selfpass/services/credentials/types"
|
2019-05-06 00:56:27 +00:00
|
|
|
)
|
|
|
|
|
2019-05-22 15:22:40 +00:00
|
|
|
func NewRedisConn(networkType, address string, connCount uint, options ...radix.PoolOpt) (c RedisConn, err error) {
|
|
|
|
p, err := radix.NewPool(networkType, address, int(connCount), options...)
|
2019-05-06 00:56:27 +00:00
|
|
|
return RedisConn{p: p}, err
|
|
|
|
}
|
|
|
|
|
|
|
|
type RedisConn struct {
|
|
|
|
p *radix.Pool
|
|
|
|
}
|
|
|
|
|
|
|
|
func (conn RedisConn) GetAllMetadata(ctx context.Context, sourceHost string, errch chan<- error) (output <-chan types.Metadata) {
|
|
|
|
mdch := make(chan types.Metadata, 1)
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
defer close(mdch)
|
|
|
|
|
|
|
|
var key string
|
2019-07-20 08:12:58 +00:00
|
|
|
scr := radix.NewScanner(conn.p, radix.ScanAllKeys)
|
2019-05-06 00:56:27 +00:00
|
|
|
|
|
|
|
for scr.Next(&key) {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return
|
|
|
|
default:
|
2019-05-22 15:22:40 +00:00
|
|
|
}
|
2019-05-06 00:56:27 +00:00
|
|
|
|
2019-05-22 15:22:40 +00:00
|
|
|
var md types.Metadata
|
2019-05-06 00:56:27 +00:00
|
|
|
|
2019-05-22 15:22:40 +00:00
|
|
|
if err := conn.p.Do(radix.Cmd(&md, hGetAll, key)); err != nil {
|
|
|
|
errch <- err
|
|
|
|
return
|
2019-05-06 00:56:27 +00:00
|
|
|
}
|
2019-05-22 15:22:40 +00:00
|
|
|
|
2019-07-20 08:12:58 +00:00
|
|
|
if sourceHost == "" || sourceHost == md.SourceHost {
|
|
|
|
mdch <- md
|
|
|
|
}
|
2019-05-06 00:56:27 +00:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return mdch
|
|
|
|
}
|
|
|
|
|
|
|
|
func (conn RedisConn) Get(ctx context.Context, id string) (output types.Credential, err error) {
|
2019-05-22 15:22:40 +00:00
|
|
|
err = conn.p.Do(radix.Cmd(&output, hGetAll, id))
|
2019-05-06 00:56:27 +00:00
|
|
|
return output, err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (conn RedisConn) Put(ctx context.Context, c types.Credential) (err error) {
|
2019-05-22 15:22:40 +00:00
|
|
|
err = conn.p.Do(radix.FlatCmd(nil, hMSet, c.ID, c))
|
2019-05-06 00:56:27 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (conn RedisConn) Delete(ctx context.Context, id string) (err error) {
|
2019-05-22 15:22:40 +00:00
|
|
|
err = conn.p.Do(radix.Cmd(nil, del, id))
|
2019-05-06 00:56:27 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
const (
|
|
|
|
hGetAll = "HGETALL"
|
|
|
|
hMSet = "HMSET"
|
|
|
|
del = "DEL"
|
|
|
|
)
|