8
8
use AsyncAws \DynamoDb \ValueObject \AttributeValue ;
9
9
use AsyncAws \DynamoDb \ValueObject \KeysAndAttributes ;
10
10
use DateInterval ;
11
+ use LogicException ;
11
12
use Psr \Cache \CacheItemInterface ;
12
13
use Psr \Cache \CacheItemPoolInterface ;
13
14
use Psr \SimpleCache \CacheInterface ;
23
24
final class DynamoDbCache implements CacheItemPoolInterface, CacheInterface
24
25
{
25
26
private const RESERVED_CHARACTERS = '{}()/\@: ' ;
27
+ private const MAX_KEY_LENGTH = 2048 ;
26
28
27
29
/**
28
30
* @var string
@@ -107,6 +109,11 @@ public function __construct(
107
109
);
108
110
}
109
111
$ this ->converter = $ converter ;
112
+ if ($ prefix !== null && strlen ($ prefix ) >= self ::MAX_KEY_LENGTH ) {
113
+ throw new LogicException (
114
+ sprintf ('The prefix cannot be longer or equal to the maximum length: %d bytes ' , self ::MAX_KEY_LENGTH )
115
+ );
116
+ }
110
117
$ this ->prefix = $ prefix ;
111
118
}
112
119
@@ -123,8 +130,13 @@ public function getItem($key)
123
130
throw $ exception ;
124
131
}
125
132
133
+ $ finalKey = $ this ->getKey ($ key );
134
+ if (strlen ($ finalKey ) > self ::MAX_KEY_LENGTH ) {
135
+ $ finalKey = $ this ->generateCompliantKey ($ key );
136
+ }
137
+
126
138
try {
127
- $ item = $ this ->getRawItem ($ this -> getKey ( $ key ) );
139
+ $ item = $ this ->getRawItem ($ finalKey );
128
140
if (!isset ($ item [$ this ->valueField ])) {
129
141
throw new CacheItemNotFoundException ();
130
142
}
@@ -133,7 +145,7 @@ public function getItem($key)
133
145
assert (method_exists ($ this ->clock ->now (), 'setTimestamp ' ));
134
146
135
147
return new DynamoCacheItem (
136
- $ this -> getKey ( $ key ) ,
148
+ $ finalKey ,
137
149
$ data !== null ,
138
150
$ data !== null ? $ this ->encoder ->decode ($ data ) : null ,
139
151
isset ($ item [$ this ->ttlField ]) && $ item [$ this ->ttlField ]->getN () !== null
@@ -144,7 +156,7 @@ public function getItem($key)
144
156
);
145
157
} catch (CacheItemNotFoundException $ e ) {
146
158
return new DynamoCacheItem (
147
- $ this -> getKey ( $ key ) ,
159
+ $ finalKey ,
148
160
false ,
149
161
null ,
150
162
null ,
@@ -575,4 +587,16 @@ private function getRawItem(string $key): array
575
587
576
588
return $ item ->getItem ();
577
589
}
590
+
591
+ private function generateCompliantKey (string $ key ): string
592
+ {
593
+ $ key = $ this ->getKey ($ key );
594
+ $ suffix = '_trunc_ ' . md5 ($ key );
595
+
596
+ return substr (
597
+ $ this ->getKey ($ key ),
598
+ 0 ,
599
+ self ::MAX_KEY_LENGTH - strlen ($ suffix )
600
+ ) . $ suffix ;
601
+ }
578
602
}
0 commit comments