Skip to content

Commit 0670e2f

Browse files
committed
Global ttlInSeconds metadata configuration for DynamoDb
Signed-off-by: Zeynel Koca <[email protected]>
1 parent 1d759c9 commit 0670e2f

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

state/aws/dynamodb/dynamodb.go

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ type StateStore struct {
4848
table string
4949
ttlAttributeName string
5050
partitionKey string
51+
ttlInSeconds *int
5152

5253
dynamodbClient *dynamodb.Client
5354
}
@@ -64,6 +65,7 @@ type dynamoDBMetadata struct {
6465
Table string `json:"table"`
6566
TTLAttributeName string `json:"ttlAttributeName"`
6667
PartitionKey string `json:"partitionKey"`
68+
TTLInSeconds *int `json:"ttlInSeconds" mapstructure:"ttlInSeconds"`
6769
}
6870

6971
type putData struct {
@@ -117,6 +119,7 @@ func (d *StateStore) Init(ctx context.Context, metadata state.Metadata) error {
117119
d.table = meta.Table
118120
d.ttlAttributeName = meta.TTLAttributeName
119121
d.partitionKey = meta.PartitionKey
122+
d.ttlInSeconds = meta.TTLInSeconds
120123

121124
if err := d.validateTableAccess(ctx); err != nil {
122125
return fmt.Errorf("error validating DynamoDB table '%s' access: %w", d.table, err)
@@ -425,6 +428,11 @@ func (d *StateStore) parseTTL(req *state.SetRequest) (*int64, error) {
425428

426429
return &expirationTime, nil
427430
}
431+
// apply global TTL if no explicit TTL in request metadata
432+
if d.ttlInSeconds != nil {
433+
expirationTime := time.Now().Unix() + int64(*d.ttlInSeconds)
434+
return &expirationTime, nil
435+
}
428436
}
429437

430438
return nil, nil
@@ -471,7 +479,26 @@ func (d *StateStore) Multi(ctx context.Context, request *state.TransactionalStat
471479
if err != nil {
472480
return fmt.Errorf("dynamodb error: failed to marshal value for key %s: %w", req.Key, err)
473481
}
474-
twi.Put = pd.ToPut()
482+
ttl, err := d.parseTTL(&req)
483+
if err != nil {
484+
return fmt.Errorf("dynamodb error: failed to parse ttlInSeconds: %w", err)
485+
}
486+
twi.Put = &types.Put{
487+
TableName: ptr.Of(d.table),
488+
Item: map[string]types.AttributeValue{
489+
d.partitionKey: &types.AttributeValueMemberS{
490+
Value: req.Key,
491+
},
492+
"value": &types.AttributeValueMemberS{
493+
Value: value,
494+
},
495+
},
496+
}
497+
if ttl != nil {
498+
twi.Put.Item[d.ttlAttributeName] = &types.AttributeValueMemberN{
499+
Value: strconv.FormatInt(*ttl, 10),
500+
}
501+
}
475502

476503
case state.DeleteRequest:
477504
twi.Delete = &types.Delete{

0 commit comments

Comments
 (0)