2017-11-20 16:21:40 +00:00
|
|
|
package redis
|
2016-12-04 08:08:06 +00:00
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"fmt"
|
2017-11-20 16:21:40 +00:00
|
|
|
"os"
|
2016-12-04 08:08:06 +00:00
|
|
|
|
2017-11-20 16:21:40 +00:00
|
|
|
redis "gopkg.in/redis.v5"
|
2016-12-04 08:08:06 +00:00
|
|
|
)
|
|
|
|
|
|
2017-11-20 16:21:40 +00:00
|
|
|
const localhost = "127.0.0.1:6379"
|
|
|
|
|
|
2017-11-20 17:37:30 +00:00
|
|
|
// New returns a checkpoint that uses Redis for underlying storage
|
|
|
|
|
func New(appName, streamName string) (*Checkpoint, error) {
|
2017-11-20 16:21:40 +00:00
|
|
|
addr := os.Getenv("REDIS_URL")
|
|
|
|
|
if addr == "" {
|
|
|
|
|
addr = localhost
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
client := redis.NewClient(&redis.Options{Addr: addr})
|
|
|
|
|
|
|
|
|
|
// verify we can ping server
|
|
|
|
|
_, err := client.Ping().Result()
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return &Checkpoint{
|
|
|
|
|
AppName: appName,
|
|
|
|
|
StreamName: streamName,
|
|
|
|
|
client: client,
|
|
|
|
|
}, nil
|
|
|
|
|
}
|
|
|
|
|
|
2017-11-20 17:37:30 +00:00
|
|
|
// Checkpoint stores and retreives the last evaluated key from a DDB scan
|
2017-11-20 16:21:40 +00:00
|
|
|
type Checkpoint struct {
|
2016-12-04 08:08:06 +00:00
|
|
|
AppName string
|
|
|
|
|
StreamName string
|
|
|
|
|
|
2017-11-20 17:37:30 +00:00
|
|
|
client *redis.Client
|
2016-12-04 08:08:06 +00:00
|
|
|
}
|
|
|
|
|
|
2017-11-20 17:37:30 +00:00
|
|
|
// Get determines if a checkpoint for a particular Shard exists.
|
2016-12-04 08:08:06 +00:00
|
|
|
// Typically used to determine whether we should start processing the shard with
|
|
|
|
|
// TRIM_HORIZON or AFTER_SEQUENCE_NUMBER (if checkpoint exists).
|
2017-11-20 17:37:30 +00:00
|
|
|
func (c *Checkpoint) Get(shardID string) (string, error) {
|
|
|
|
|
return c.client.Get(c.key(shardID)).Result()
|
2016-12-04 08:08:06 +00:00
|
|
|
}
|
|
|
|
|
|
2017-11-20 17:37:30 +00:00
|
|
|
// Set stores a checkpoint for a shard (e.g. sequence number of last record processed by application).
|
2016-12-04 08:08:06 +00:00
|
|
|
// Upon failover, record processing is resumed from this point.
|
2017-11-20 17:37:30 +00:00
|
|
|
func (c *Checkpoint) Set(shardID string, sequenceNumber string) error {
|
2016-12-04 08:08:06 +00:00
|
|
|
err := c.client.Set(c.key(shardID), sequenceNumber, 0).Err()
|
|
|
|
|
if err != nil {
|
2017-11-20 17:37:30 +00:00
|
|
|
return fmt.Errorf("redis checkpoint error: %v", err)
|
2016-12-04 08:08:06 +00:00
|
|
|
}
|
2017-11-20 17:37:30 +00:00
|
|
|
return nil
|
2016-12-04 08:08:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// key generates a unique Redis key for storage of Checkpoint.
|
2017-11-20 16:21:40 +00:00
|
|
|
func (c *Checkpoint) key(shardID string) string {
|
2016-12-04 08:08:06 +00:00
|
|
|
return fmt.Sprintf("%v:checkpoint:%v:%v", c.AppName, c.StreamName, shardID)
|
|
|
|
|
}
|