DynamoDbStore.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. <?php
  2. namespace Illuminate\Cache;
  3. use Aws\DynamoDb\DynamoDbClient;
  4. use Aws\DynamoDb\Exception\DynamoDbException;
  5. use Illuminate\Contracts\Cache\LockProvider;
  6. use Illuminate\Contracts\Cache\Store;
  7. use Illuminate\Support\Carbon;
  8. use Illuminate\Support\InteractsWithTime;
  9. use Illuminate\Support\Str;
  10. use RuntimeException;
  11. class DynamoDbStore implements LockProvider, Store
  12. {
  13. use InteractsWithTime;
  14. /**
  15. * The DynamoDB client instance.
  16. *
  17. * @var \Aws\DynamoDb\DynamoDbClient
  18. */
  19. protected $dynamo;
  20. /**
  21. * The table name.
  22. *
  23. * @var string
  24. */
  25. protected $table;
  26. /**
  27. * The name of the attribute that should hold the key.
  28. *
  29. * @var string
  30. */
  31. protected $keyAttribute;
  32. /**
  33. * The name of the attribute that should hold the value.
  34. *
  35. * @var string
  36. */
  37. protected $valueAttribute;
  38. /**
  39. * The name of the attribute that should hold the expiration timestamp.
  40. *
  41. * @var string
  42. */
  43. protected $expirationAttribute;
  44. /**
  45. * A string that should be prepended to keys.
  46. *
  47. * @var string
  48. */
  49. protected $prefix;
  50. /**
  51. * Create a new store instance.
  52. *
  53. * @param \Aws\DynamoDb\DynamoDbClient $dynamo
  54. * @param string $table
  55. * @param string $keyAttribute
  56. * @param string $valueAttribute
  57. * @param string $expirationAttribute
  58. * @param string $prefix
  59. * @return void
  60. */
  61. public function __construct(DynamoDbClient $dynamo,
  62. $table,
  63. $keyAttribute = 'key',
  64. $valueAttribute = 'value',
  65. $expirationAttribute = 'expires_at',
  66. $prefix = '')
  67. {
  68. $this->table = $table;
  69. $this->dynamo = $dynamo;
  70. $this->keyAttribute = $keyAttribute;
  71. $this->valueAttribute = $valueAttribute;
  72. $this->expirationAttribute = $expirationAttribute;
  73. $this->setPrefix($prefix);
  74. }
  75. /**
  76. * Retrieve an item from the cache by key.
  77. *
  78. * @param string $key
  79. * @return mixed
  80. */
  81. public function get($key)
  82. {
  83. $response = $this->dynamo->getItem([
  84. 'TableName' => $this->table,
  85. 'ConsistentRead' => false,
  86. 'Key' => [
  87. $this->keyAttribute => [
  88. 'S' => $this->prefix.$key,
  89. ],
  90. ],
  91. ]);
  92. if (! isset($response['Item'])) {
  93. return;
  94. }
  95. if ($this->isExpired($response['Item'])) {
  96. return;
  97. }
  98. if (isset($response['Item'][$this->valueAttribute])) {
  99. return $this->unserialize(
  100. $response['Item'][$this->valueAttribute]['S'] ??
  101. $response['Item'][$this->valueAttribute]['N'] ??
  102. null
  103. );
  104. }
  105. }
  106. /**
  107. * Retrieve multiple items from the cache by key.
  108. *
  109. * Items not found in the cache will have a null value.
  110. *
  111. * @param array $keys
  112. * @return array
  113. */
  114. public function many(array $keys)
  115. {
  116. if (count($keys) === 0) {
  117. return [];
  118. }
  119. $prefixedKeys = array_map(function ($key) {
  120. return $this->prefix.$key;
  121. }, $keys);
  122. $response = $this->dynamo->batchGetItem([
  123. 'RequestItems' => [
  124. $this->table => [
  125. 'ConsistentRead' => false,
  126. 'Keys' => collect($prefixedKeys)->map(function ($key) {
  127. return [
  128. $this->keyAttribute => [
  129. 'S' => $key,
  130. ],
  131. ];
  132. })->all(),
  133. ],
  134. ],
  135. ]);
  136. $now = Carbon::now();
  137. return array_merge(collect(array_flip($keys))->map(function () {
  138. //
  139. })->all(), collect($response['Responses'][$this->table])->mapWithKeys(function ($response) use ($now) {
  140. if ($this->isExpired($response, $now)) {
  141. $value = null;
  142. } else {
  143. $value = $this->unserialize(
  144. $response[$this->valueAttribute]['S'] ??
  145. $response[$this->valueAttribute]['N'] ??
  146. null
  147. );
  148. }
  149. return [Str::replaceFirst($this->prefix, '', $response[$this->keyAttribute]['S']) => $value];
  150. })->all());
  151. }
  152. /**
  153. * Determine if the given item is expired.
  154. *
  155. * @param array $item
  156. * @param \DateTimeInterface|null $expiration
  157. * @return bool
  158. */
  159. protected function isExpired(array $item, $expiration = null)
  160. {
  161. $expiration = $expiration ?: Carbon::now();
  162. return isset($item[$this->expirationAttribute]) &&
  163. $expiration->getTimestamp() >= $item[$this->expirationAttribute]['N'];
  164. }
  165. /**
  166. * Store an item in the cache for a given number of seconds.
  167. *
  168. * @param string $key
  169. * @param mixed $value
  170. * @param int $seconds
  171. * @return bool
  172. */
  173. public function put($key, $value, $seconds)
  174. {
  175. $this->dynamo->putItem([
  176. 'TableName' => $this->table,
  177. 'Item' => [
  178. $this->keyAttribute => [
  179. 'S' => $this->prefix.$key,
  180. ],
  181. $this->valueAttribute => [
  182. $this->type($value) => $this->serialize($value),
  183. ],
  184. $this->expirationAttribute => [
  185. 'N' => (string) $this->toTimestamp($seconds),
  186. ],
  187. ],
  188. ]);
  189. return true;
  190. }
  191. /**
  192. * Store multiple items in the cache for a given number of seconds.
  193. *
  194. * @param array $values
  195. * @param int $seconds
  196. * @return bool
  197. */
  198. public function putMany(array $values, $seconds)
  199. {
  200. if (count($values) === 0) {
  201. return true;
  202. }
  203. $expiration = $this->toTimestamp($seconds);
  204. $this->dynamo->batchWriteItem([
  205. 'RequestItems' => [
  206. $this->table => collect($values)->map(function ($value, $key) use ($expiration) {
  207. return [
  208. 'PutRequest' => [
  209. 'Item' => [
  210. $this->keyAttribute => [
  211. 'S' => $this->prefix.$key,
  212. ],
  213. $this->valueAttribute => [
  214. $this->type($value) => $this->serialize($value),
  215. ],
  216. $this->expirationAttribute => [
  217. 'N' => (string) $expiration,
  218. ],
  219. ],
  220. ],
  221. ];
  222. })->values()->all(),
  223. ],
  224. ]);
  225. return true;
  226. }
  227. /**
  228. * Store an item in the cache if the key doesn't exist.
  229. *
  230. * @param string $key
  231. * @param mixed $value
  232. * @param int $seconds
  233. * @return bool
  234. */
  235. public function add($key, $value, $seconds)
  236. {
  237. try {
  238. $this->dynamo->putItem([
  239. 'TableName' => $this->table,
  240. 'Item' => [
  241. $this->keyAttribute => [
  242. 'S' => $this->prefix.$key,
  243. ],
  244. $this->valueAttribute => [
  245. $this->type($value) => $this->serialize($value),
  246. ],
  247. $this->expirationAttribute => [
  248. 'N' => (string) $this->toTimestamp($seconds),
  249. ],
  250. ],
  251. 'ConditionExpression' => 'attribute_not_exists(#key) OR #expires_at < :now',
  252. 'ExpressionAttributeNames' => [
  253. '#key' => $this->keyAttribute,
  254. '#expires_at' => $this->expirationAttribute,
  255. ],
  256. 'ExpressionAttributeValues' => [
  257. ':now' => [
  258. 'N' => (string) $this->currentTime(),
  259. ],
  260. ],
  261. ]);
  262. return true;
  263. } catch (DynamoDbException $e) {
  264. if (str_contains($e->getMessage(), 'ConditionalCheckFailed')) {
  265. return false;
  266. }
  267. throw $e;
  268. }
  269. }
  270. /**
  271. * Increment the value of an item in the cache.
  272. *
  273. * @param string $key
  274. * @param mixed $value
  275. * @return int|bool
  276. */
  277. public function increment($key, $value = 1)
  278. {
  279. try {
  280. $response = $this->dynamo->updateItem([
  281. 'TableName' => $this->table,
  282. 'Key' => [
  283. $this->keyAttribute => [
  284. 'S' => $this->prefix.$key,
  285. ],
  286. ],
  287. 'ConditionExpression' => 'attribute_exists(#key) AND #expires_at > :now',
  288. 'UpdateExpression' => 'SET #value = #value + :amount',
  289. 'ExpressionAttributeNames' => [
  290. '#key' => $this->keyAttribute,
  291. '#value' => $this->valueAttribute,
  292. '#expires_at' => $this->expirationAttribute,
  293. ],
  294. 'ExpressionAttributeValues' => [
  295. ':now' => [
  296. 'N' => (string) $this->currentTime(),
  297. ],
  298. ':amount' => [
  299. 'N' => (string) $value,
  300. ],
  301. ],
  302. 'ReturnValues' => 'UPDATED_NEW',
  303. ]);
  304. return (int) $response['Attributes'][$this->valueAttribute]['N'];
  305. } catch (DynamoDbException $e) {
  306. if (str_contains($e->getMessage(), 'ConditionalCheckFailed')) {
  307. return false;
  308. }
  309. throw $e;
  310. }
  311. }
  312. /**
  313. * Decrement the value of an item in the cache.
  314. *
  315. * @param string $key
  316. * @param mixed $value
  317. * @return int|bool
  318. */
  319. public function decrement($key, $value = 1)
  320. {
  321. try {
  322. $response = $this->dynamo->updateItem([
  323. 'TableName' => $this->table,
  324. 'Key' => [
  325. $this->keyAttribute => [
  326. 'S' => $this->prefix.$key,
  327. ],
  328. ],
  329. 'ConditionExpression' => 'attribute_exists(#key) AND #expires_at > :now',
  330. 'UpdateExpression' => 'SET #value = #value - :amount',
  331. 'ExpressionAttributeNames' => [
  332. '#key' => $this->keyAttribute,
  333. '#value' => $this->valueAttribute,
  334. '#expires_at' => $this->expirationAttribute,
  335. ],
  336. 'ExpressionAttributeValues' => [
  337. ':now' => [
  338. 'N' => (string) $this->currentTime(),
  339. ],
  340. ':amount' => [
  341. 'N' => (string) $value,
  342. ],
  343. ],
  344. 'ReturnValues' => 'UPDATED_NEW',
  345. ]);
  346. return (int) $response['Attributes'][$this->valueAttribute]['N'];
  347. } catch (DynamoDbException $e) {
  348. if (str_contains($e->getMessage(), 'ConditionalCheckFailed')) {
  349. return false;
  350. }
  351. throw $e;
  352. }
  353. }
  354. /**
  355. * Store an item in the cache indefinitely.
  356. *
  357. * @param string $key
  358. * @param mixed $value
  359. * @return bool
  360. */
  361. public function forever($key, $value)
  362. {
  363. return $this->put($key, $value, Carbon::now()->addYears(5)->getTimestamp());
  364. }
  365. /**
  366. * Get a lock instance.
  367. *
  368. * @param string $name
  369. * @param int $seconds
  370. * @param string|null $owner
  371. * @return \Illuminate\Contracts\Cache\Lock
  372. */
  373. public function lock($name, $seconds = 0, $owner = null)
  374. {
  375. return new DynamoDbLock($this, $this->prefix.$name, $seconds, $owner);
  376. }
  377. /**
  378. * Restore a lock instance using the owner identifier.
  379. *
  380. * @param string $name
  381. * @param string $owner
  382. * @return \Illuminate\Contracts\Cache\Lock
  383. */
  384. public function restoreLock($name, $owner)
  385. {
  386. return $this->lock($name, 0, $owner);
  387. }
  388. /**
  389. * Remove an item from the cache.
  390. *
  391. * @param string $key
  392. * @return bool
  393. */
  394. public function forget($key)
  395. {
  396. $this->dynamo->deleteItem([
  397. 'TableName' => $this->table,
  398. 'Key' => [
  399. $this->keyAttribute => [
  400. 'S' => $this->prefix.$key,
  401. ],
  402. ],
  403. ]);
  404. return true;
  405. }
  406. /**
  407. * Remove all items from the cache.
  408. *
  409. * @return bool
  410. *
  411. * @throws \RuntimeException
  412. */
  413. public function flush()
  414. {
  415. throw new RuntimeException('DynamoDb does not support flushing an entire table. Please create a new table.');
  416. }
  417. /**
  418. * Get the UNIX timestamp for the given number of seconds.
  419. *
  420. * @param int $seconds
  421. * @return int
  422. */
  423. protected function toTimestamp($seconds)
  424. {
  425. return $seconds > 0
  426. ? $this->availableAt($seconds)
  427. : $this->currentTime();
  428. }
  429. /**
  430. * Serialize the value.
  431. *
  432. * @param mixed $value
  433. * @return mixed
  434. */
  435. protected function serialize($value)
  436. {
  437. return is_numeric($value) ? (string) $value : serialize($value);
  438. }
  439. /**
  440. * Unserialize the value.
  441. *
  442. * @param mixed $value
  443. * @return mixed
  444. */
  445. protected function unserialize($value)
  446. {
  447. if (filter_var($value, FILTER_VALIDATE_INT) !== false) {
  448. return (int) $value;
  449. }
  450. if (is_numeric($value)) {
  451. return (float) $value;
  452. }
  453. return unserialize($value);
  454. }
  455. /**
  456. * Get the DynamoDB type for the given value.
  457. *
  458. * @param mixed $value
  459. * @return string
  460. */
  461. protected function type($value)
  462. {
  463. return is_numeric($value) ? 'N' : 'S';
  464. }
  465. /**
  466. * Get the cache key prefix.
  467. *
  468. * @return string
  469. */
  470. public function getPrefix()
  471. {
  472. return $this->prefix;
  473. }
  474. /**
  475. * Set the cache key prefix.
  476. *
  477. * @param string $prefix
  478. * @return void
  479. */
  480. public function setPrefix($prefix)
  481. {
  482. $this->prefix = ! empty($prefix) ? $prefix.':' : '';
  483. }
  484. /**
  485. * Get the DynamoDb Client instance.
  486. *
  487. * @return \Aws\DynamoDb\DynamoDbClient
  488. */
  489. public function getClient()
  490. {
  491. return $this->dynamo;
  492. }
  493. }