Skip to content

Commit 8c9c5af

Browse files
authored
Merge branch 'master' into master
2 parents 61bb9c2 + a072ff3 commit 8c9c5af

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

state/cassandra/cassandra.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ const (
3333
defaultTable = "items"
3434
defaultKeyspace = "dapr"
3535
defaultPort = 9042
36+
metadataTTLKey = "ttlInSeconds"
3637
)
3738

3839
// Cassandra is a state store implementation for Apache Cassandra
@@ -286,6 +287,15 @@ func (c *Cassandra) Set(req *state.SetRequest) error {
286287
session = sess
287288
}
288289

290+
ttl, err := parseTTL(req.Metadata)
291+
if err != nil {
292+
return fmt.Errorf("error parsing TTL from Metadata: %s", err)
293+
}
294+
295+
if ttl != nil {
296+
return session.Query("INSERT INTO ? (key, value) VALUES (?, ?) USING TTL ?", c.table, req.Key, bt, *ttl).Exec()
297+
}
298+
289299
return session.Query("INSERT INTO ? (key, value) VALUES (?, ?)", c.table, req.Key, bt).Exec()
290300
}
291301

@@ -303,3 +313,17 @@ func (c *Cassandra) createSession(consistency gocql.Consistency) (*gocql.Session
303313

304314
return session, nil
305315
}
316+
317+
func parseTTL(requestMetadata map[string]string) (*int, error) {
318+
if val, found := requestMetadata[metadataTTLKey]; found && val != "" {
319+
parsedVal, err := strconv.ParseInt(val, 10, 0)
320+
if err != nil {
321+
return nil, err
322+
}
323+
parsedInt := int(parsedVal)
324+
325+
return &parsedInt, nil
326+
}
327+
328+
return nil, nil
329+
}

state/cassandra/cassandra_test.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
package cassandra
77

88
import (
9+
"strconv"
910
"testing"
1011

1112
"github.com/dapr/components-contrib/state"
@@ -98,3 +99,35 @@ func TestGetCassandraMetadata(t *testing.T) {
9899
assert.NotNil(t, err)
99100
})
100101
}
102+
103+
func TestParseTTL(t *testing.T) {
104+
t.Run("TTL Not an integer", func(t *testing.T) {
105+
ttlInSeconds := "not an integer"
106+
ttl, err := parseTTL(map[string]string{
107+
"ttlInSeconds": ttlInSeconds,
108+
})
109+
assert.Error(t, err)
110+
assert.Nil(t, ttl)
111+
})
112+
t.Run("TTL specified with wrong key", func(t *testing.T) {
113+
ttlInSeconds := 12345
114+
ttl, err := parseTTL(map[string]string{
115+
"expirationTime": strconv.Itoa(ttlInSeconds),
116+
})
117+
assert.NoError(t, err)
118+
assert.Nil(t, ttl)
119+
})
120+
t.Run("TTL is a number", func(t *testing.T) {
121+
ttlInSeconds := 12345
122+
ttl, err := parseTTL(map[string]string{
123+
"ttlInSeconds": strconv.Itoa(ttlInSeconds),
124+
})
125+
assert.NoError(t, err)
126+
assert.Equal(t, *ttl, ttlInSeconds)
127+
})
128+
t.Run("TTL not set", func(t *testing.T) {
129+
ttl, err := parseTTL(map[string]string{})
130+
assert.NoError(t, err)
131+
assert.Nil(t, ttl)
132+
})
133+
}

0 commit comments

Comments
 (0)