File: ExtMongoDBCache.php

package info (click to toggle)
php-matomo-doctrine-cache 1.10.4-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 996 kB
  • sloc: php: 3,638; makefile: 17; sh: 9
file content (198 lines) | stat: -rw-r--r-- 5,315 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
<?php

declare(strict_types=1);

namespace Doctrine\Common\Cache;

use DateTime;
use MongoDB\BSON\Binary;
use MongoDB\BSON\UTCDateTime;
use MongoDB\Collection;
use MongoDB\Database;
use MongoDB\Driver\Exception\Exception;
use MongoDB\Model\BSONDocument;
use function serialize;
use function time;
use function unserialize;

/**
 * MongoDB cache provider for ext-mongodb
 *
 * @internal Do not use - will be removed in 2.0. Use MongoDBCache instead
 */
class ExtMongoDBCache extends CacheProvider
{
    /** @var Database */
    private $database;

    /** @var Collection */
    private $collection;

    /** @var bool */
    private $expirationIndexCreated = false;

    /**
     * This provider will default to the write concern and read preference
     * options set on the Database instance (or inherited from MongoDB or
     * Client). Using an unacknowledged write concern (< 1) may make the return
     * values of delete() and save() unreliable. Reading from secondaries may
     * make contain() and fetch() unreliable.
     *
     * @see http://www.php.net/manual/en/mongo.readpreferences.php
     * @see http://www.php.net/manual/en/mongo.writeconcerns.php
     */
    public function __construct(Collection $collection)
    {
        // Ensure there is no typemap set - we want to use our own
        $this->collection = $collection->withOptions(['typeMap' => null]);
        $this->database   = new Database($collection->getManager(), $collection->getDatabaseName());
    }

    /**
     * {@inheritdoc}
     */
    protected function doFetch($id)
    {
        $document = $this->collection->findOne(['_id' => $id], [MongoDBCache::DATA_FIELD, MongoDBCache::EXPIRATION_FIELD]);

        if ($document === null) {
            return false;
        }

        if ($this->isExpired($document)) {
            $this->createExpirationIndex();
            $this->doDelete($id);

            return false;
        }

        return unserialize($document[MongoDBCache::DATA_FIELD]->getData());
    }

    /**
     * {@inheritdoc}
     */
    protected function doContains($id)
    {
        $document = $this->collection->findOne(['_id' => $id], [MongoDBCache::EXPIRATION_FIELD]);

        if ($document === null) {
            return false;
        }

        if ($this->isExpired($document)) {
            $this->createExpirationIndex();
            $this->doDelete($id);

            return false;
        }

        return true;
    }

    /**
     * {@inheritdoc}
     */
    protected function doSave($id, $data, $lifeTime = 0)
    {
        try {
            $this->collection->updateOne(
                ['_id' => $id],
                [
                    '$set' => [
                        MongoDBCache::EXPIRATION_FIELD => ($lifeTime > 0 ? new UTCDateTime((time() + $lifeTime) * 1000): null),
                        MongoDBCache::DATA_FIELD => new Binary(serialize($data), Binary::TYPE_GENERIC),
                    ],
                ],
                ['upsert' => true]
            );
        } catch (Exception $e) {
            return false;
        }

        return true;
    }

    /**
     * {@inheritdoc}
     */
    protected function doDelete($id)
    {
        try {
            $this->collection->deleteOne(['_id' => $id]);
        } catch (Exception $e) {
            return false;
        }

        return true;
    }

    /**
     * {@inheritdoc}
     */
    protected function doFlush()
    {
        try {
            // Use remove() in lieu of drop() to maintain any collection indexes
            $this->collection->deleteMany([]);
        } catch (Exception $e) {
            return false;
        }

        return true;
    }

    /**
     * {@inheritdoc}
     */
    protected function doGetStats()
    {
        $uptime      = null;
        $memoryUsage = null;

        try {
            $serverStatus = $this->database->command([
                'serverStatus' => 1,
                'locks' => 0,
                'metrics' => 0,
                'recordStats' => 0,
                'repl' => 0,
            ])->toArray()[0];
            $uptime       = $serverStatus['uptime'] ?? null;
        } catch (Exception $e) {
        }

        try {
            $collStats   = $this->database->command(['collStats' => $this->collection->getCollectionName()])->toArray()[0];
            $memoryUsage = $collStats['size'] ?? null;
        } catch (Exception $e) {
        }

        return [
            Cache::STATS_HITS => null,
            Cache::STATS_MISSES => null,
            Cache::STATS_UPTIME => $uptime,
            Cache::STATS_MEMORY_USAGE => $memoryUsage,
            Cache::STATS_MEMORY_AVAILABLE  => null,
        ];
    }

    /**
     * Check if the document is expired.
     */
    private function isExpired(BSONDocument $document) : bool
    {
        return isset($document[MongoDBCache::EXPIRATION_FIELD]) &&
            $document[MongoDBCache::EXPIRATION_FIELD] instanceof UTCDateTime &&
            $document[MongoDBCache::EXPIRATION_FIELD]->toDateTime() < new DateTime();
    }

    private function createExpirationIndex() : void
    {
        if ($this->expirationIndexCreated) {
            return;
        }

        $this->collection->createIndex([MongoDBCache::EXPIRATION_FIELD => 1], ['background' => true, 'expireAfterSeconds' => 0]);
    }
}