forked from ryandotsmith/ddbsync
-
Notifications
You must be signed in to change notification settings - Fork 5
/
db.go
91 lines (78 loc) · 2.29 KB
/
db.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package ddbsync
import (
"errors"
"strconv"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
)
var (
ErrLocked = errors.New("key is locked")
)
type Database struct {
client AWSDynamoer
tableName string
}
func NewDatabase(tableName string, region string, endpoint string, disableSSL bool) *Database {
cfg := aws.Config{
Endpoint: &endpoint,
Region: ®ion,
DisableSSL: &disableSSL,
}
sess := session.Must(session.NewSession(&cfg))
return &Database{
client: dynamodb.New(sess),
tableName: tableName,
}
}
var _ DBer = (*Database)(nil) // Forces compile time checking of the interface
var _ AWSDynamoer = (*dynamodb.DynamoDB)(nil) // Forces compile time checking of the interface
type DBer interface {
Acquire(string, time.Duration) error
Delete(string) error
}
type AWSDynamoer interface {
UpdateItem(*dynamodb.UpdateItemInput) (*dynamodb.UpdateItemOutput, error)
DeleteItem(*dynamodb.DeleteItemInput) (*dynamodb.DeleteItemOutput, error)
}
func (db *Database) Acquire(name string, ttl time.Duration) error {
now := time.Now()
_, err := db.client.UpdateItem(&dynamodb.UpdateItemInput{
TableName: aws.String(db.tableName),
Key: key(name),
ExpressionAttributeNames: map[string]*string{
"#N": aws.String("Name"),
"#C": aws.String("Created"),
},
ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
":now": dynamoTime(now),
":cutoff": dynamoTime(now.Add(-ttl)),
},
ConditionExpression: aws.String(`attribute_not_exists(#N) OR #C < :cutoff`),
UpdateExpression: aws.String(`SET #C = :now`),
})
var awsErr awserr.Error
if errors.As(err, &awsErr) && awsErr.Code() == dynamodb.ErrCodeConditionalCheckFailedException {
return ErrLocked
}
return err
}
func (db *Database) Delete(name string) error {
_, err := db.client.DeleteItem(&dynamodb.DeleteItemInput{
TableName: aws.String(db.tableName),
Key: key(name),
})
return err
}
func dynamoTime(t time.Time) *dynamodb.AttributeValue {
return &dynamodb.AttributeValue{
N: aws.String(strconv.FormatInt(t.UnixMilli(), 10)),
}
}
func key(name string) map[string]*dynamodb.AttributeValue {
return map[string]*dynamodb.AttributeValue{
"Name": {S: aws.String(name)},
}
}