forked from danog/MadelineProto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGarbageCollector.php
193 lines (173 loc) · 7.14 KB
/
GarbageCollector.php
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
<?php declare(strict_types=1);
/**
* This file is part of MadelineProto.
* MadelineProto is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
* MadelineProto is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU General Public License along with MadelineProto.
* If not, see <http://www.gnu.org/licenses/>.
*
* @author Daniil Gentili <daniil@daniil.it>
* @copyright 2016-2023 Daniil Gentili <daniil@daniil.it>
* @license https://opensource.org/licenses/AGPL-3.0 AGPLv3
* @link https://docs.madelineproto.xyz MadelineProto documentation
*/
namespace danog\MadelineProto;
use Amp\Http\Client\HttpClientBuilder;
use Amp\Http\Client\Request;
use Amp\SignalException;
use AssertionError;
use ReflectionFiber;
use Revolt\EventLoop;
use Throwable;
use WeakMap;
use const LOCK_EX;
use const LOCK_NB;
use function Amp\File\move;
use function Amp\File\read;
use function Amp\File\write;
/**
* @internal
*
* @psalm-suppress UndefinedConstant
*/
final class GarbageCollector
{
/**
* Ensure only one instance of GarbageCollector exists
* when multiple instances of MadelineProto are running.
*/
private static bool $started = false;
/**
* Next cleanup will be triggered when memory consumption will increase by this amount.
*/
public static int $memoryDiffMb = 1;
/**
* Memory consumption after last cleanup.
*/
private static int $memoryConsumption = 0;
public static function start(): void
{
if (self::$started) {
return;
}
self::$started = true;
EventLoop::unreference(EventLoop::repeat(1, static function (): void {
$currentMemory = self::getMemoryConsumption();
if ($currentMemory > self::$memoryConsumption + self::$memoryDiffMb) {
gc_collect_cycles();
self::$memoryConsumption = self::getMemoryConsumption();
$cleanedMemory = $currentMemory - self::$memoryConsumption;
if (!Magic::$suspendPeriodicLogging) {
Logger::log("gc_collect_cycles done. Cleaned memory: $cleanedMemory Mb", Logger::VERBOSE);
}
}
}));
if (!\defined('MADELINE_RELEASE_URL')) {
return;
}
$client = HttpClientBuilder::buildDefault();
$id = null;
$cb = function () use ($client, &$id): void {
try {
$request = new Request(MADELINE_RELEASE_URL);
$latest = $client->request($request);
Magic::$latest_release = trim($latest->getBody()->buffer());
if (API::RELEASE !== Magic::$latest_release) {
$old = API::RELEASE;
$new = Magic::$latest_release;
Logger::log("!!!!!!!!!!!!! An update of MadelineProto is required (old=$old, new=$new)! !!!!!!!!!!!!!", Logger::FATAL_ERROR);
$contents = $client->request(new Request("https://phar.madelineproto.xyz/phar.php?v=new".rand(0, PHP_INT_MAX)))
->getBody()
->buffer();
if (!str_starts_with($contents, '<?php')) {
throw new AssertionError("phar.php is not a PHP file!");
}
if ($contents !== read(MADELINE_PHP)) {
$unlock = Tools::flock(MADELINE_PHP.'.lock', LOCK_EX);
write(MADELINE_PHP.'.temp.php', $contents);
move(MADELINE_PHP.'.temp.php', MADELINE_PHP);
$unlock();
}
try {
unlink(MADELINE_PHAR_VERSION);
} catch (Throwable) {
}
if (Magic::$isIpcWorker) {
throw new SignalException('!!!!!!!!!!!!! An update of MadelineProto is required, shutting down worker! !!!!!!!!!!!!!');
}
if ($id) {
EventLoop::cancel($id);
}
return;
}
/** @var string */
foreach (glob(MADELINE_PHAR_GLOB) as $path) {
$base = basename($path);
if ($base === 'madeline-'.API::RELEASE.'.phar') {
continue;
}
$f = fopen("$path.lock", 'c');
if (flock($f, LOCK_EX|LOCK_NB)) {
fclose($f);
unlink($path);
unlink("$path.lock");
} else {
fclose($f);
}
}
} catch (Throwable $e) {
if ($e instanceof SignalException) {
throw $e;
}
Logger::log("An error occurred in the phar cleanup loop: $e", Logger::FATAL_ERROR);
}
};
$cb();
EventLoop::unreference($id = EventLoop::repeat(3600.0, $cb));
}
/** @var \WeakMap<\Fiber, true> */
public static WeakMap $map;
public static function registerFiber(\Fiber $fiber): \Fiber
{
self::$map ??= new WeakMap;
self::$map[$fiber] = true;
return $fiber;
}
private static function getMemoryConsumption(): int
{
self::$map ??= new WeakMap;
$memory = round(memory_get_usage()/1024/1024, 1);
/*if (!Magic::$suspendPeriodicLogging) {
Logger::log("Memory consumption: $memory Mb", Logger::ULTRA_VERBOSE);
}*/
/*if (!Magic::$suspendPeriodicLogging) {
$k = 0;
foreach (self::$map as $fiber => $_) {
if ($k++ === 0) {
continue;
}
if ($fiber->isTerminated()) {
continue;
}
if (!$fiber->isStarted()) {
continue;
}
$reflection = new ReflectionFiber($fiber);
$tlTrace = '';
foreach ($reflection->getTrace() as $k => $frame) {
$tlTrace .= isset($frame['file']) ? \str_pad(\basename($frame['file']).'('.$frame['line'].'):', 20)."\t" : '';
$tlTrace .= isset($frame['function']) ? $frame['function'].'(' : '';
$tlTrace .= isset($frame['args']) ? \substr(\json_encode($frame['args']) ?: '', 1, -1) : '';
$tlTrace .= ')';
$tlTrace .= "\n";
}
\var_dump($tlTrace);
}
$fibers = self::$map->count();
$maps = '~'.\substr_count(\file_get_contents('/proc/self/maps'), "\n");
Logger::log("Running fibers: $fibers, maps: $maps", Logger::ULTRA_VERBOSE);
}*/
return (int) $memory;
}
}