Completed
Pull Request — master (#14)
by Chad
01:49
created

ProcessRegistry   A

Complexity

Total Complexity 23

Size/Duplication

Total Lines 193
Duplicated Lines 7.25 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 23
lcom 1
cbo 2
dl 14
loc 193
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
D add() 7 84 17
A remove() 0 10 1
B reset() 7 24 3
A _getEncodedHostname() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * Defines the ProcessRegistry class which uses MongoDB as a backend.
4
 */
5
6
namespace DominionEnterprises\Cronus;
7
8
use MongoDB\BSON\ObjectID;
9
use MongoDB\BSON\UTCDateTime;
10
use MongoDB\Collection;
11
12
/**
13
 * Class that adds/removes from a process registry.
14
 */
15
final class ProcessRegistry implements ProcessRegistryInterface
16
{
17
    /** example doc:
18
     * {
19
     *     '_id': 'a unique id',
20
     *     'hosts': {
21
     *         'a hostname' : {
22
     *             'a pid': UTCDateTime(expire time),
23
     *             ...
24
     *         },
25
     *         ...
26
     *     },
27
     *     'version' => ObjectID(an id),
28
     * }
29
     */
30
31
    const MONGO_INT32_MAX = 2147483647;//2147483648 can overflow in php mongo without using the MongoInt64
32
33
    /**
34
     * MongoDB collection containing the process information.
35
     *
36
     * @var Collection
37
     */
38
    private $collection;
39
40
    /**
41
     * Construct a new instance of the registry.
42
     *
43
     * @param Collection $collection The MongoDB collection containing the process information.
44
     */
45
    public function __construct(Collection $collection)
46
    {
47
        $this->collection = $collection;
48
    }
49
50
    /**
51
     * Add to process registry. Adds based on $maxGlobalProcesses and $maxHostProcesses after a process registry
52
     * cleaning.
53
     *
54
     * @param string  $id                 A unique id.
55
     * @param integer $minsBeforeExpire   Number of minutes before a process is considered expired.
56
     * @param integer $maxGlobalProcesses Max processes of an id allowed to run across all hosts.
57
     * @param integer $maxHostProcesses   Max processes of an id allowed to run across a single host.
58
     *
59
     * @return boolean true if the process was added, false if not or there is too much concurrency at the moment.
60
     */
61
    public function add(
0 ignored issues
show
Coding Style introduced by
Function's nesting level (4) exceeds 2; consider refactoring the function
Loading history...
Coding Style introduced by
Unknown type hint "string" found for $id
Loading history...
Coding Style introduced by
Unknown type hint "int" found for $minsBeforeExpire
Loading history...
Coding Style introduced by
Unknown type hint "int" found for $maxGlobalProcesses
Loading history...
Coding Style introduced by
Unknown type hint "int" found for $maxHostProcesses
Loading history...
62
        string $id,
63
        int $minsBeforeExpire = PHP_INT_MAX,
64
        int $maxGlobalProcesses = 1,
65
        int $maxHostProcesses = 1
66
    ) : bool {
67
        $thisHostName = self::_getEncodedHostname();
68
        $thisPid = getmypid();
69
70
        //loop in case the update fails its optimistic concurrency check
71
        for ($i = 0; $i < 5; ++$i) {
72
            $this->collection->findOneAndUpdate(
73
                ['_id' => $id],
74
                ['$setOnInsert' => ['hosts' => [], 'version' => new ObjectID()]],
75
                ['upsert' => true]
76
            );
77
            $existing = $this->collection->findOne(
78
                ['_id' => $id],
79
                ['typeMap' => ['root' => 'array', 'document' => 'array', 'array' => 'array']]
80
            );
81
82
            $replacement = $existing;
83
            $replacement['version'] = new ObjectID();
84
85
            //clean $replacement based on their pids and expire times
86
            foreach ($existing['hosts'] as $hostname => $pids) {
87
                foreach ($pids as $pid => $expires) {
88
                    //our machine and not running
89
                    //the task expired
90
                    //our machine and pid is recycled (should rarely happen)
91
                    if (($hostname === $thisHostName && !file_exists("/proc/{$pid}"))
92
                        || time() > $expires->toDateTime()->getTimestamp()
93
                        || ($hostname === $thisHostName && $pid === $thisPid)
94
                    ) {
95
                        unset($replacement['hosts'][$hostname][$pid]);
96
                    }
97
                }
98
99
                if (empty($replacement['hosts'][$hostname])) {
100
                    unset($replacement['hosts'][$hostname]);
101
                }
102
            }
103
104
            $totalPidCount = 0;
105
            foreach ($replacement['hosts'] as $hostname => $pids) {
106
                $totalPidCount += count($pids);
107
            }
108
109
            $thisHostPids = array_key_exists($thisHostName, $replacement['hosts']) ? $replacement['hosts'][$thisHostName] : [];
110
111
            if ($totalPidCount >= $maxGlobalProcesses || count($thisHostPids) >= $maxHostProcesses) {
112
                return false;
113
            }
114
115
            // add our process
116
            $expireSecs = time() + $minsBeforeExpire * 60;
117 View Code Duplication
            if (!is_int($expireSecs)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
118
                if ($minsBeforeExpire > 0) {
119
                    $expireSecs = self::MONGO_INT32_MAX;
120
                } else {
121
                    $expireSecs = 0;
122
                }
123
            }
124
125
            $thisHostPids[$thisPid] = new UTCDateTime($expireSecs * 1000);
126
            $replacement['hosts'][$thisHostName] = $thisHostPids;
127
128
            $status = $this->collection->replaceOne(
129
                ['_id' => $existing['_id'], 'version' => $existing['version']],
130
                $replacement,
131
                ['writeConcern' => new \MongoDB\Driver\WriteConcern(1, 100, true)]
132
            );
133
            if ($status->getMatchedCount() === 1) {
134
                return true;
135
            }
136
137
            //@codeCoverageIgnoreStart
138
            //hard to test the optimistic concurrency check
139
        }
140
141
        //too much concurrency at the moment, return false to signify not added.
142
        return false;
143
        //@codeCoverageIgnoreEnd
144
    }
145
146
    /**
147
     * Removes from process registry. Does not do anything needed for use of the add() method. Most will only use at the
148
     * end of their script so the mongo collection is up to date.
149
     *
150
     * @param string $id A unique id.
151
     *
152
     * @return void
153
     */
154
    public function remove(string $id)
0 ignored issues
show
Coding Style introduced by
Unknown type hint "string" found for $id
Loading history...
155
    {
156
        $thisHostName = self::_getEncodedHostname();
157
        $thisPid = getmypid();
158
159
        $this->collection->updateOne(
160
            ['_id' => $id],
161
            ['$unset' => ["hosts.{$thisHostName}.{$thisPid}" => ''], '$set' => ['version' => new ObjectID()]]
162
        );
163
    }
164
165
    /**
166
     * Reset a process expire time in the registry.
167
     *
168
     * @param string  $id               A unique id.
169
     * @param integer $minsBeforeExpire Number of minutes before a process is considered expired.
170
     *
171
     * @return void
172
     */
173
    public function reset(string $id, int $minsBeforeExpire)
0 ignored issues
show
Coding Style introduced by
Unknown type hint "string" found for $id
Loading history...
Coding Style introduced by
Unknown type hint "int" found for $minsBeforeExpire
Loading history...
174
    {
175
        $expireSecs = time() + $minsBeforeExpire * 60;
176 View Code Duplication
        if (!is_int($expireSecs)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
177
            if ($minsBeforeExpire > 0) {
178
                $expireSecs = self::MONGO_INT32_MAX;
179
            } else {
180
                $expireSecs = 0;
181
            }
182
        }
183
184
        $thisHostName = self::_getEncodedHostname();
185
        $thisPid = getmypid();
186
187
        $this->collection->updateOne(
188
            ['_id' => $id],
189
            [
190
                '$set' => [
191
                    "hosts.{$thisHostName}.{$thisPid}" => new UTCDateTime($expireSecs * 1000),
192
                    'version' => new ObjectID(),
193
                ],
194
            ]
195
        );
196
    }
197
198
    /**
199
     * Encodes '.' and '$' to be used as a mongo field name.
200
     *
201
     * @return string the encoded hostname from gethostname().
202
     */
203
    private static function _getEncodedHostname() : string
204
    {
205
        return str_replace(['.', '$'], ['_DOT_', '_DOLLAR_'], gethostname());
206
    }
207
}
208