ExtMongoDBCache.php 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. <?php
  2. declare(strict_types=1);
  3. namespace Doctrine\Common\Cache;
  4. use DateTime;
  5. use MongoDB\BSON\Binary;
  6. use MongoDB\BSON\UTCDateTime;
  7. use MongoDB\Collection;
  8. use MongoDB\Database;
  9. use MongoDB\Driver\Exception\Exception;
  10. use MongoDB\Model\BSONDocument;
  11. use function serialize;
  12. use function time;
  13. use function unserialize;
  14. /**
  15. * MongoDB cache provider for ext-mongodb
  16. *
  17. * @internal Do not use - will be removed in 2.0. Use MongoDBCache instead
  18. */
  19. class ExtMongoDBCache extends CacheProvider
  20. {
  21. /** @var Database */
  22. private $database;
  23. /** @var Collection */
  24. private $collection;
  25. /** @var bool */
  26. private $expirationIndexCreated = false;
  27. /**
  28. * This provider will default to the write concern and read preference
  29. * options set on the Database instance (or inherited from MongoDB or
  30. * Client). Using an unacknowledged write concern (< 1) may make the return
  31. * values of delete() and save() unreliable. Reading from secondaries may
  32. * make contain() and fetch() unreliable.
  33. *
  34. * @see http://www.php.net/manual/en/mongo.readpreferences.php
  35. * @see http://www.php.net/manual/en/mongo.writeconcerns.php
  36. */
  37. public function __construct(Collection $collection)
  38. {
  39. // Ensure there is no typemap set - we want to use our own
  40. $this->collection = $collection->withOptions(['typeMap' => null]);
  41. $this->database = new Database($collection->getManager(), $collection->getDatabaseName());
  42. }
  43. /**
  44. * {@inheritdoc}
  45. */
  46. protected function doFetch($id)
  47. {
  48. $document = $this->collection->findOne(['_id' => $id], [MongoDBCache::DATA_FIELD, MongoDBCache::EXPIRATION_FIELD]);
  49. if ($document === null) {
  50. return false;
  51. }
  52. if ($this->isExpired($document)) {
  53. $this->createExpirationIndex();
  54. $this->doDelete($id);
  55. return false;
  56. }
  57. return unserialize($document[MongoDBCache::DATA_FIELD]->getData());
  58. }
  59. /**
  60. * {@inheritdoc}
  61. */
  62. protected function doContains($id)
  63. {
  64. $document = $this->collection->findOne(['_id' => $id], [MongoDBCache::EXPIRATION_FIELD]);
  65. if ($document === null) {
  66. return false;
  67. }
  68. if ($this->isExpired($document)) {
  69. $this->createExpirationIndex();
  70. $this->doDelete($id);
  71. return false;
  72. }
  73. return true;
  74. }
  75. /**
  76. * {@inheritdoc}
  77. */
  78. protected function doSave($id, $data, $lifeTime = 0)
  79. {
  80. try {
  81. $this->collection->updateOne(
  82. ['_id' => $id],
  83. [
  84. '$set' => [
  85. MongoDBCache::EXPIRATION_FIELD => ($lifeTime > 0 ? new UTCDateTime((time() + $lifeTime) * 1000): null),
  86. MongoDBCache::DATA_FIELD => new Binary(serialize($data), Binary::TYPE_GENERIC),
  87. ],
  88. ],
  89. ['upsert' => true]
  90. );
  91. } catch (Exception $e) {
  92. return false;
  93. }
  94. return true;
  95. }
  96. /**
  97. * {@inheritdoc}
  98. */
  99. protected function doDelete($id)
  100. {
  101. try {
  102. $this->collection->deleteOne(['_id' => $id]);
  103. } catch (Exception $e) {
  104. return false;
  105. }
  106. return true;
  107. }
  108. /**
  109. * {@inheritdoc}
  110. */
  111. protected function doFlush()
  112. {
  113. try {
  114. // Use remove() in lieu of drop() to maintain any collection indexes
  115. $this->collection->deleteMany([]);
  116. } catch (Exception $e) {
  117. return false;
  118. }
  119. return true;
  120. }
  121. /**
  122. * {@inheritdoc}
  123. */
  124. protected function doGetStats()
  125. {
  126. $uptime = null;
  127. $memoryUsage = null;
  128. try {
  129. $serverStatus = $this->database->command([
  130. 'serverStatus' => 1,
  131. 'locks' => 0,
  132. 'metrics' => 0,
  133. 'recordStats' => 0,
  134. 'repl' => 0,
  135. ])->toArray()[0];
  136. $uptime = $serverStatus['uptime'] ?? null;
  137. } catch (Exception $e) {
  138. }
  139. try {
  140. $collStats = $this->database->command(['collStats' => $this->collection->getCollectionName()])->toArray()[0];
  141. $memoryUsage = $collStats['size'] ?? null;
  142. } catch (Exception $e) {
  143. }
  144. return [
  145. Cache::STATS_HITS => null,
  146. Cache::STATS_MISSES => null,
  147. Cache::STATS_UPTIME => $uptime,
  148. Cache::STATS_MEMORY_USAGE => $memoryUsage,
  149. Cache::STATS_MEMORY_AVAILABLE => null,
  150. ];
  151. }
  152. /**
  153. * Check if the document is expired.
  154. */
  155. private function isExpired(BSONDocument $document) : bool
  156. {
  157. return isset($document[MongoDBCache::EXPIRATION_FIELD]) &&
  158. $document[MongoDBCache::EXPIRATION_FIELD] instanceof UTCDateTime &&
  159. $document[MongoDBCache::EXPIRATION_FIELD]->toDateTime() < new DateTime();
  160. }
  161. private function createExpirationIndex() : void
  162. {
  163. if ($this->expirationIndexCreated) {
  164. return;
  165. }
  166. $this->collection->createIndex([MongoDBCache::EXPIRATION_FIELD => 1], ['background' => true, 'expireAfterSeconds' => 0]);
  167. }
  168. }