|
| 1 | +/* |
| 2 | + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"). |
| 5 | + * You may not use this file except in compliance with the License. |
| 6 | + * A copy of the License is located at |
| 7 | + * |
| 8 | + * http://aws.amazon.com/apache2.0 |
| 9 | + * |
| 10 | + * or in the "license" file accompanying this file. This file is distributed |
| 11 | + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either |
| 12 | + * express or implied. See the License for the specific language governing |
| 13 | + * permissions and limitations under the License. |
| 14 | + */ |
| 15 | + |
| 16 | +package software.amazon.awssdk.enhanced.dynamodb.extensions; |
| 17 | + |
| 18 | +import java.time.Duration; |
| 19 | +import java.time.Instant; |
| 20 | +import java.time.LocalDate; |
| 21 | +import java.time.LocalDateTime; |
| 22 | +import java.time.LocalTime; |
| 23 | +import java.time.ZoneOffset; |
| 24 | +import java.time.ZonedDateTime; |
| 25 | +import java.time.temporal.ChronoUnit; |
| 26 | +import java.time.temporal.TemporalUnit; |
| 27 | +import java.util.Collections; |
| 28 | +import java.util.HashMap; |
| 29 | +import java.util.Map; |
| 30 | +import java.util.function.Consumer; |
| 31 | +import software.amazon.awssdk.annotations.SdkPublicApi; |
| 32 | +import software.amazon.awssdk.annotations.ThreadSafe; |
| 33 | +import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; |
| 34 | +import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension; |
| 35 | +import software.amazon.awssdk.enhanced.dynamodb.DynamoDbExtensionContext; |
| 36 | +import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; |
| 37 | +import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTag; |
| 38 | +import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableMetadata; |
| 39 | +import software.amazon.awssdk.services.dynamodb.model.AttributeValue; |
| 40 | +import software.amazon.awssdk.utils.StringUtils; |
| 41 | +import software.amazon.awssdk.utils.Validate; |
| 42 | + |
| 43 | +@SdkPublicApi |
| 44 | +@ThreadSafe |
| 45 | +public final class TimeToLiveExtension implements DynamoDbEnhancedClientExtension { |
| 46 | + |
| 47 | + public static final String CUSTOM_METADATA_KEY = "TimeToLiveExtension:TimeToLiveAttribute"; |
| 48 | + |
| 49 | + private TimeToLiveExtension() { |
| 50 | + } |
| 51 | + |
| 52 | + public static TimeToLiveExtension.Builder builder() { |
| 53 | + return new TimeToLiveExtension.Builder(); |
| 54 | + } |
| 55 | + |
| 56 | + /** |
| 57 | + * @return an Instance of {@link TimeToLiveExtension} |
| 58 | + */ |
| 59 | + public static TimeToLiveExtension create() { |
| 60 | + return new TimeToLiveExtension(); |
| 61 | + } |
| 62 | + |
| 63 | + @Override |
| 64 | + public WriteModification beforeWrite(DynamoDbExtensionContext.BeforeWrite context) { |
| 65 | + Map<String, ?> customTTLMetadata = context.tableMetadata() |
| 66 | + .customMetadataObject(CUSTOM_METADATA_KEY, Map.class).orElse(null); |
| 67 | + |
| 68 | + if (customTTLMetadata != null) { |
| 69 | + String ttlAttributeName = (String) customTTLMetadata.get("attributeName"); |
| 70 | + String baseFieldName = (String) customTTLMetadata.get("baseField"); |
| 71 | + Long duration = (Long) customTTLMetadata.get("duration"); |
| 72 | + TemporalUnit unit = (TemporalUnit) customTTLMetadata.get("unit"); |
| 73 | + |
| 74 | + Map<String, AttributeValue> itemToTransform = new HashMap<>(context.items()); |
| 75 | + |
| 76 | + if (!itemToTransform.containsKey(ttlAttributeName) && StringUtils.isNotBlank(baseFieldName) |
| 77 | + && itemToTransform.containsKey(baseFieldName)) { |
| 78 | + Object baseFieldValue = context.tableSchema().converterForAttribute(baseFieldName) |
| 79 | + .transformTo(itemToTransform.get(baseFieldName)); |
| 80 | + Long ttlEpochSeconds = computeTTLFromBase(baseFieldValue, duration, unit); |
| 81 | + itemToTransform.put(ttlAttributeName, AttributeValue.builder().n(String.valueOf(ttlEpochSeconds)).build()); |
| 82 | + |
| 83 | + return WriteModification.builder().transformedItem(Collections.unmodifiableMap(itemToTransform)).build(); |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + return WriteModification.builder().build(); |
| 88 | + } |
| 89 | + |
| 90 | + private static Long computeTTLFromBase(Object baseValue, long duration, TemporalUnit unit) { |
| 91 | + if (baseValue instanceof Instant) { |
| 92 | + return ((Instant) baseValue).plus(duration, unit).getEpochSecond(); |
| 93 | + } |
| 94 | + if (baseValue instanceof LocalDate) { |
| 95 | + return ((LocalDate) baseValue).atStartOfDay(ZoneOffset.UTC).plus(duration, unit).toEpochSecond(); |
| 96 | + } |
| 97 | + if (baseValue instanceof LocalDateTime) { |
| 98 | + return ((LocalDateTime) baseValue).plus(duration, unit).toEpochSecond(ZoneOffset.UTC); |
| 99 | + } |
| 100 | + if (baseValue instanceof LocalTime) { |
| 101 | + return LocalDate.now().atTime((LocalTime) baseValue).plus(duration, unit).toEpochSecond(ZoneOffset.UTC); |
| 102 | + } |
| 103 | + if (baseValue instanceof ZonedDateTime) { |
| 104 | + return ((ZonedDateTime) baseValue).plus(duration, unit).toEpochSecond(); |
| 105 | + } |
| 106 | + if (baseValue instanceof Long) { |
| 107 | + return (Long) baseValue + Duration.of(duration, unit).getSeconds(); |
| 108 | + } |
| 109 | + |
| 110 | + throw new IllegalArgumentException("Unsupported base field type for TTL computation: " + baseValue.getClass().getName()); |
| 111 | + } |
| 112 | + |
| 113 | + public static final class Builder { |
| 114 | + private Builder() { |
| 115 | + } |
| 116 | + |
| 117 | + public TimeToLiveExtension build() { |
| 118 | + return new TimeToLiveExtension(); |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + public static final class AttributeTags { |
| 123 | + private AttributeTags() { |
| 124 | + } |
| 125 | + |
| 126 | + /** |
| 127 | + * Used to explicitly designate an attribute to determine the TTL on the table. |
| 128 | + * |
| 129 | + * <p><b>How this works</b></p> |
| 130 | + * <ul> |
| 131 | + * <li>If a TTL attribute is set, it takes precedence over <i>baseField</i>.</li> |
| 132 | + * <li>If no TTL attribute is set, it checks for <i>baseField</i>.</li> |
| 133 | + * <li>If <i>baseField</i> is present, the TTL is calculated using its value, <i>duration</i>, and <i>unit</i>.</li> |
| 134 | + * <li>The final TTL value is converted to epoch seconds before storing in DynamoDB.</li> |
| 135 | + * </ul> |
| 136 | + * |
| 137 | + * @param baseField Optional attribute name used to determine the TTL value. |
| 138 | + * @param duration Additional long value used for TTL calculation. |
| 139 | + * @param unit {@link ChronoUnit} value specifying the TTL duration unit. |
| 140 | + */ |
| 141 | + public static StaticAttributeTag timeToLiveAttribute(String baseField, long duration, ChronoUnit unit) { |
| 142 | + return new TimeToLiveAttribute(baseField, duration, unit); |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + private static final class TimeToLiveAttribute implements StaticAttributeTag { |
| 147 | + |
| 148 | + public String baseField; |
| 149 | + public long duration; |
| 150 | + public ChronoUnit unit; |
| 151 | + |
| 152 | + private TimeToLiveAttribute(String baseField, long duration, ChronoUnit unit) { |
| 153 | + this.baseField = baseField; |
| 154 | + this.duration = duration; |
| 155 | + this.unit = unit; |
| 156 | + } |
| 157 | + |
| 158 | + @Override |
| 159 | + public <R> void validateType(String attributeName, EnhancedType<R> type, |
| 160 | + AttributeValueType attributeValueType) { |
| 161 | + |
| 162 | + Validate.notNull(type, "type is null"); |
| 163 | + Validate.notNull(type.rawClass(), "rawClass is null"); |
| 164 | + Validate.notNull(attributeValueType, "attributeValueType is null"); |
| 165 | + |
| 166 | + if (!type.rawClass().equals(Long.class)) { |
| 167 | + throw new IllegalArgumentException(String.format( |
| 168 | + "Attribute '%s' of type %s is not a suitable type to be used as a TTL attribute. Only type Long " + |
| 169 | + "is supported.", attributeName, type.rawClass())); |
| 170 | + } |
| 171 | + } |
| 172 | + |
| 173 | + @Override |
| 174 | + public Consumer<StaticTableMetadata.Builder> modifyMetadata(String attributeName, |
| 175 | + AttributeValueType attributeValueType) { |
| 176 | + Map<String, Object> customMetadataMap = new HashMap<>(); |
| 177 | + customMetadataMap.put("attributeName", attributeName); |
| 178 | + customMetadataMap.put("baseField", baseField); |
| 179 | + customMetadataMap.put("duration", duration); |
| 180 | + customMetadataMap.put("unit", unit); |
| 181 | + |
| 182 | + return metadata -> metadata.addCustomMetadataObject(CUSTOM_METADATA_KEY, |
| 183 | + Collections.unmodifiableMap(customMetadataMap)); |
| 184 | + } |
| 185 | + } |
| 186 | +} |
0 commit comments