ExtMongoDBCache.php 5.2 KB

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