| 1 |
package sturdyc |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"reflect" |
| 6 |
"strconv" |
| 7 |
"strings" |
| 8 |
"time" |
| 9 |
) |
| 10 |
|
| 11 |
func handleSlice(v reflect.Value) string { |
| 12 |
// If the value is a pointer to a slice, get the actual slice |
| 13 |
if v.Kind() == reflect.Ptr { |
| 14 |
v = v.Elem() |
| 15 |
} |
| 16 |
|
| 17 |
if v.Len() < 1 { |
| 18 |
return "empty" |
| 19 |
} |
| 20 |
|
| 21 |
var sliceStrings []string |
| 22 |
for i := 0; i < v.Len(); i++ { |
| 23 |
sliceStrings = append(sliceStrings, fmt.Sprintf("%v", v.Index(i).Interface())) |
| 24 |
} |
| 25 |
|
| 26 |
return strings.Join(sliceStrings, ",") |
| 27 |
} |
| 28 |
|
| 29 |
func extractPermutation(cacheKey string) string { |
| 30 |
idIndex := strings.LastIndex(cacheKey, "ID-") |
| 31 |
|
| 32 |
// "ID-" not found, return the original cache key. |
| 33 |
if idIndex == -1 { |
| 34 |
return cacheKey |
| 35 |
} |
| 36 |
|
| 37 |
// Find the last "-" before "ID-" to ensure we include "ID-" in the result |
| 38 |
lastDashIndex := strings.LastIndex(cacheKey[:idIndex], "-") |
| 39 |
// "-" not found before "ID-", return original string |
| 40 |
if lastDashIndex == -1 { |
| 41 |
return cacheKey |
| 42 |
} |
| 43 |
|
| 44 |
return cacheKey[:lastDashIndex+1] |
| 45 |
} |
| 46 |
|
| 47 |
func (c *Client[T]) relativeTime(t time.Time) string { |
| 48 |
now := c.clock.Now().Truncate(c.keyTruncation) |
| 49 |
target := t.Truncate(c.keyTruncation) |
| 50 |
var diff time.Duration |
| 51 |
var direction string |
| 52 |
if target.After(now) { |
| 53 |
diff = target.Sub(now) |
| 54 |
direction = "(+)" // Time is in the future |
| 55 |
} else { |
| 56 |
diff = now.Sub(target) |
| 57 |
direction = "(-)" // Time is in the past |
| 58 |
} |
| 59 |
hours := int(diff.Hours()) |
| 60 |
minutes := int(diff.Minutes()) % 60 |
| 61 |
seconds := int(diff.Seconds()) % 60 |
| 62 |
return fmt.Sprintf("%s%dh%02dm%02ds", direction, hours, minutes, seconds) |
| 63 |
} |
| 64 |
|
| 65 |
// handleTime turns the time.Time into an epoch string. |
| 66 |
func (c *Client[T]) handleTime(v reflect.Value) string { |
| 67 |
if timestamp, ok := v.Interface().(time.Time); ok { |
| 68 |
if !timestamp.IsZero() { |
| 69 |
if c.useRelativeTimeKeyFormat { |
| 70 |
return c.relativeTime(timestamp) |
| 71 |
} |
| 72 |
return strconv.FormatInt(timestamp.Unix(), 10) |
| 73 |
} |
| 74 |
} |
| 75 |
|
| 76 |
return "empty-time" |
| 77 |
} |
| 78 |
|
| 79 |
// PermutatedKey takes a prefix and a struct where the fields are concatenated |
| 80 |
// in order to create a unique cache key. Passing anything but a struct for |
| 81 |
// "permutationStruct" will result in a panic. The cache will only use the |
| 82 |
// EXPORTED fields of the struct to construct the key. The permutation struct |
| 83 |
// should be FLAT, with no nested structs. The fields can be any of the basic |
| 84 |
// types, as well as slices and time.Time values. |
| 85 |
// |
| 86 |
// Parameters: |
| 87 |
// |
| 88 |
// prefix - The prefix for the cache key. |
| 89 |
// permutationStruct - A struct whose fields are concatenated to form a unique cache key. |
| 90 |
// Only exported fields are used. |
| 91 |
// |
| 92 |
// Returns: |
| 93 |
// |
| 94 |
// A string to be used as the cache key. |
| 95 |
// |
| 96 |
// Example usage: |
| 97 |
// |
| 98 |
// type queryParams struct { |
| 99 |
// City string |
| 100 |
// Country string |
| 101 |
// } |
| 102 |
// params := queryParams{"Stockholm", "Sweden"} |
| 103 |
// key := c.PermutatedKey("prefix",, params) // prefix-Stockholm-Sweden-1 |
| 104 |
func (c *Client[T]) PermutatedKey(prefix string, permutationStruct interface{}) string { |
| 105 |
var sb strings.Builder |
| 106 |
sb.WriteString(prefix) |
| 107 |
sb.WriteString("-") |
| 108 |
|
| 109 |
// Get the value of the interface |
| 110 |
v := reflect.ValueOf(permutationStruct) |
| 111 |
|
| 112 |
if v.Kind() == reflect.Ptr { |
| 113 |
v = v.Elem() |
| 114 |
} |
| 115 |
|
| 116 |
if v.Kind() != reflect.Struct { |
| 117 |
panic("val must be a struct") |
| 118 |
} |
| 119 |
|
| 120 |
for i := 0; i < v.NumField(); i++ { |
| 121 |
field := v.Field(i) |
| 122 |
|
| 123 |
// Check if the field is exported, and if so skip it. |
| 124 |
if !field.CanInterface() { |
| 125 |
message := fmt.Sprintf( |
| 126 |
"sturdyc: permutationStruct contains unexported field: %s which won't be part of the cache key", |
| 127 |
v.Type().Field(i).Name, |
| 128 |
) |
| 129 |
c.log.Warn(message) |
| 130 |
continue |
| 131 |
} |
| 132 |
|
| 133 |
if i > 0 { |
| 134 |
sb.WriteString("-") |
| 135 |
} |
| 136 |
|
| 137 |
if field.Kind() == reflect.Ptr { |
| 138 |
if field.IsNil() { |
| 139 |
sb.WriteString("nil") |
| 140 |
continue |
| 141 |
} |
| 142 |
// If it's not nil we'll dereference the pointer to handle its value. |
| 143 |
field = field.Elem() |
| 144 |
} |
| 145 |
|
| 146 |
//nolint:exhaustive // We only need special logic for slices and time.Time values. |
| 147 |
switch field.Kind() { |
| 148 |
case reflect.Slice: |
| 149 |
if field.IsNil() { |
| 150 |
sb.WriteString("nil") |
| 151 |
} else { |
| 152 |
sliceString := handleSlice(field) |
| 153 |
sb.WriteString(sliceString) |
| 154 |
} |
| 155 |
case reflect.Struct: |
| 156 |
if field.Type() == reflect.TypeOf(time.Time{}) { |
| 157 |
sb.WriteString(c.handleTime(field)) |
| 158 |
continue |
| 159 |
} |
| 160 |
sb.WriteString(fmt.Sprintf("%v", field.Interface())) |
| 161 |
default: |
| 162 |
sb.WriteString(fmt.Sprintf("%v", field.Interface())) |
| 163 |
} |
| 164 |
} |
| 165 |
|
| 166 |
return sb.String() |
| 167 |
} |
| 168 |
|
| 169 |
// BatchKeyFn provides a function that can be used in conjunction with |
| 170 |
// "GetOrFetchBatch". It takes in a prefix and returns a function that will use |
| 171 |
// the prefix, add a -ID- separator, and then append the ID as a suffix for |
| 172 |
// each item. |
| 173 |
// |
| 174 |
// Parameters: |
| 175 |
// |
| 176 |
// prefix - The prefix to be used for each cache key. |
| 177 |
// |
| 178 |
// Returns: |
| 179 |
// |
| 180 |
// A function that takes an ID and returns a cache key string with the given prefix and ID. |
| 181 |
// |
| 182 |
// Example usage: |
| 183 |
// |
| 184 |
// fn := c.BatchKeyFn("some-prefix") |
| 185 |
// key := fn("1234") // some-prefix-ID-1234 |
| 186 |
func (c *Client[T]) BatchKeyFn(prefix string) KeyFn { |
| 187 |
return func(id string) string { |
| 188 |
return fmt.Sprintf("%s-ID-%s", prefix, id) |
| 189 |
} |
| 190 |
} |
| 191 |
|
| 192 |
// PermutatedBatchKeyFn provides a function that can be used in conjunction |
| 193 |
// with GetOrFetchBatch. It takes a prefix and a struct where the fields are |
| 194 |
// concatenated with the ID in order to make a unique cache key. Passing |
| 195 |
// anything but a struct for "permutationStruct" will result in a panic. The |
| 196 |
// cache will only use the EXPORTED fields of the struct to construct the key. |
| 197 |
// The permutation struct should be FLAT, with no nested structs. The fields |
| 198 |
// can be any of the basic types, as well as slices and time.Time values. |
| 199 |
// |
| 200 |
// Parameters: |
| 201 |
// |
| 202 |
// prefix - The prefix for the cache key. |
| 203 |
// permutationStruct - A struct whose fields are concatenated to form a unique cache key. Only exported fields are used. |
| 204 |
// |
| 205 |
// Returns: |
| 206 |
// |
| 207 |
// A function that takes an ID and returns a cache key string with the given prefix, permutation struct fields, and ID. |
| 208 |
// |
| 209 |
// Example usage: |
| 210 |
// |
| 211 |
// type queryParams struct { |
| 212 |
// City string |
| 213 |
// Country string |
| 214 |
// } |
| 215 |
// params := queryParams{"Stockholm", "Sweden"} |
| 216 |
// cacheKeyFunc := c.PermutatedBatchKeyFn("prefix", params) |
| 217 |
// key := cacheKeyFunc("1") // prefix-Stockholm-Sweden-ID-1 |
| 218 |
func (c *Client[T]) PermutatedBatchKeyFn(prefix string, permutationStruct interface{}) KeyFn { |
| 219 |
return func(id string) string { |
| 220 |
key := c.PermutatedKey(prefix, permutationStruct) |
| 221 |
return fmt.Sprintf("%s-ID-%s", key, id) |
| 222 |
} |
| 223 |
} |