MadelineProto/src/danog/MadelineProto/Db/MysqlArray.php

373 lines
9.9 KiB
PHP
Raw Normal View History

2020-04-25 21:57:55 +02:00
<?php
namespace danog\MadelineProto\Db;
use Amp\Mysql\Pool;
2020-04-28 02:41:06 +02:00
use Amp\Producer;
use Amp\Promise;
2020-04-25 21:57:55 +02:00
use Amp\Sql\ResultSet;
2020-04-28 02:41:06 +02:00
use danog\MadelineProto\Logger;
2020-04-25 21:57:55 +02:00
use function Amp\call;
2020-04-27 02:21:18 +02:00
class MysqlArray implements DbArray
2020-04-25 21:57:55 +02:00
{
2020-05-02 19:36:59 +02:00
use ArrayCacheTrait;
2020-04-25 21:57:55 +02:00
private string $table;
private array $settings;
private Pool $db;
public function __serialize(): array
{
return [
'table' => $this->table,
'settings' => $this->settings
];
}
public function __unserialize($data): void
{
foreach ($data as $property => $value) {
$this->{$property} = $value;
}
2020-04-28 02:41:06 +02:00
try {
$this->db = static::getDbConnection($this->settings);
} catch (\Throwable $e) {
Logger::log($e->getMessage(), Logger::ERROR);
}
2020-04-25 21:57:55 +02:00
}
2020-05-20 22:15:52 +02:00
/**
* @param string $name
* @param DbArray|array|null $value
* @param string $tablePrefix
* @param array $settings
*
* @return Promise
*/
2020-05-17 21:04:32 +02:00
public static function getInstance(string $name, $value = null, string $tablePrefix = '', array $settings = []): Promise
2020-04-25 21:57:55 +02:00
{
$tableName = "{$tablePrefix}_{$name}";
if ($value instanceof self && $value->table === $tableName) {
$instance = &$value;
} else {
$instance = new static();
$instance->table = $tableName;
}
2020-04-25 21:57:55 +02:00
2020-04-28 02:41:06 +02:00
$instance->settings = $settings;
$instance->db = static::getDbConnection($settings);
2020-05-02 19:36:59 +02:00
$instance->ttl = $settings['cache_ttl'] ?? $instance->ttl;
2020-04-28 02:41:06 +02:00
2020-06-09 00:47:54 +02:00
$instance->startCacheCleanupLoop();
2020-05-17 21:04:32 +02:00
return call(static function() use($instance, $value) {
2020-05-12 19:35:15 +02:00
yield from $instance->prepareTable();
//Skip migrations if its same object
if ($instance !== $value) {
yield from static::renameTmpTable($instance, $value);
yield from static::migrateDataToDb($instance, $value);
}
2020-05-12 19:35:15 +02:00
2020-05-17 21:04:32 +02:00
return $instance;
});
}
2020-04-28 02:41:06 +02:00
2020-05-20 22:15:52 +02:00
/**
* @param MysqlArray $instance
* @param DbArray|array|null $value
*
* @return \Generator
*/
private static function renameTmpTable(MysqlArray $instance, $value): \Generator
2020-05-17 21:04:32 +02:00
{
if ($value instanceof static && $value->table) {
if (
$value->table !== $instance->table &&
2020-05-17 21:04:32 +02:00
mb_strpos($instance->table, 'tmp') !== 0
) {
yield from $instance->renameTable($value->table, $instance->table);
} else {
2020-05-17 21:04:32 +02:00
$instance->table = $value->table;
2020-04-28 02:41:06 +02:00
}
2020-05-17 21:04:32 +02:00
}
}
2020-05-20 22:15:52 +02:00
/**
* @param MysqlArray $instance
* @param DbArray|array|null $value
*
* @return \Generator
* @throws \Throwable
*/
private static function migrateDataToDb(MysqlArray $instance, $value): \Generator
2020-05-17 21:04:32 +02:00
{
if (!empty($value) && !$value instanceof MysqlArray) {
2020-05-17 21:04:32 +02:00
Logger::log('Converting database.', Logger::ERROR);
2020-05-20 22:15:52 +02:00
if ($value instanceof DbArray) {
$value = yield $value->getArrayCopy();
} else {
$value = (array) $value;
}
2020-05-17 21:04:32 +02:00
$counter = 0;
$total = count($value);
foreach ($value as $key => $item) {
2020-05-17 21:04:32 +02:00
$counter++;
if ($counter % 500 === 0) {
2020-05-17 21:04:32 +02:00
yield $instance->offsetSet($key, $item);
Logger::log("Loading data to table {$instance->table}: $counter/$total", Logger::WARNING);
2020-05-17 21:04:32 +02:00
} else {
$instance->offsetSet($key, $item);
}
2020-04-25 21:57:55 +02:00
2020-05-17 21:04:32 +02:00
}
Logger::log('Converting database done.', Logger::ERROR);
}
2020-04-25 21:57:55 +02:00
}
public function offsetExists($index): bool
{
throw new \RuntimeException('Native isset not support promises. Use isset method');
}
2020-04-25 21:57:55 +02:00
/**
* Check if key isset
2020-04-25 21:57:55 +02:00
*
* @param $key
2020-04-25 21:57:55 +02:00
*
2020-05-03 03:33:54 +02:00
* @return Promise<bool> true if the offset exists, otherwise false
2020-04-25 21:57:55 +02:00
*/
public function isset($key): Promise
2020-04-25 21:57:55 +02:00
{
return call(fn() => yield $this->offsetGet($key) !== null);
2020-04-25 21:57:55 +02:00
}
2020-05-03 03:33:54 +02:00
public function offsetGet($offset): Promise
2020-04-28 02:41:06 +02:00
{
return call(function() use($offset) {
2020-05-02 19:36:59 +02:00
if ($cached = $this->getCache($offset)) {
return $cached;
}
2020-04-28 02:41:06 +02:00
$row = yield $this->request(
2020-05-16 23:38:30 +02:00
"SELECT `value` FROM `{$this->table}` WHERE `key` = :index LIMIT 1",
2020-04-28 02:41:06 +02:00
['index' => $offset]
);
2020-05-02 19:36:59 +02:00
if ($value = $this->getValue($row)) {
$this->setCache($offset, $value);
}
return $value;
2020-04-28 02:41:06 +02:00
});
2020-04-25 21:57:55 +02:00
}
/**
* Set value for an offset
*
* @link https://php.net/manual/en/arrayiterator.offsetset.php
*
* @param string $index <p>
* The index to set for.
* </p>
* @param $value
*
* @throws \Throwable
*/
2020-05-12 19:35:15 +02:00
public function offsetSet($index, $value): Promise
2020-04-28 02:41:06 +02:00
{
if ($this->getCache($index) === $value) {
2020-05-12 19:35:15 +02:00
return call(fn()=>null);
}
2020-05-02 19:36:59 +02:00
$this->setCache($index, $value);
$request = $this->request("
INSERT INTO `{$this->table}`
SET `key` = :index, `value` = :value
ON DUPLICATE KEY UPDATE `value` = :value
",
2020-04-28 02:41:06 +02:00
[
'index' => $index,
'value' => serialize($value),
]
);
//Ensure that cache is synced with latest insert in case of concurrent requests.
$request->onResolve(fn() => $this->setCache($index, $value));
return $request;
2020-04-28 02:41:06 +02:00
}
2020-04-25 21:57:55 +02:00
/**
* Unset value for an offset
*
* @link https://php.net/manual/en/arrayiterator.offsetunset.php
*
* @param string $index <p>
* The offset to unset.
* </p>
*
2020-05-03 03:33:54 +02:00
* @return Promise
2020-04-25 21:57:55 +02:00
* @throws \Throwable
*/
2020-05-03 03:33:54 +02:00
public function offsetUnset($index): Promise
2020-04-25 21:57:55 +02:00
{
2020-05-02 19:36:59 +02:00
$this->unsetCache($index);
2020-05-03 03:33:54 +02:00
return $this->request("
2020-04-25 21:57:55 +02:00
DELETE FROM `{$this->table}`
WHERE `key` = :index
",
['index' => $index]
);
}
/**
* Get array copy
*
* @return Promise<array>
2020-04-25 21:57:55 +02:00
* @throws \Throwable
*/
public function getArrayCopy(): Promise
2020-04-25 21:57:55 +02:00
{
return call(function(){
$iterator = $this->getIterator();
$result = [];
while (yield $iterator->advance()) {
[$key, $value] = $iterator->getCurrent();
$result[$key] = $value;
}
return $result;
});
2020-04-25 21:57:55 +02:00
}
2020-04-28 02:41:06 +02:00
public function getIterator(): Producer
{
return new Producer(function (callable $emit) {
2020-05-16 23:38:30 +02:00
$request = yield $this->db->execute("SELECT `key`, `value` FROM `{$this->table}`");
2020-04-28 02:41:06 +02:00
while (yield $request->advance()) {
$row = $request->getCurrent();
2020-05-03 03:33:54 +02:00
yield $emit([$row['key'], $this->getValue($row)]);
2020-04-28 02:41:06 +02:00
}
});
}
2020-04-25 21:57:55 +02:00
/**
* Count elements
*
* @link https://php.net/manual/en/arrayiterator.count.php
2020-05-03 03:33:54 +02:00
* @return Promise<int> The number of elements or public properties in the associated
2020-04-25 21:57:55 +02:00
* array or object, respectively.
* @throws \Throwable
*/
2020-05-03 03:33:54 +02:00
public function count(): Promise
2020-04-25 21:57:55 +02:00
{
2020-05-03 03:33:54 +02:00
return call(function(){
2020-05-16 23:38:30 +02:00
$row = yield $this->request("SELECT count(`key`) as `count` FROM `{$this->table}`");
2020-05-03 03:33:54 +02:00
return $row[0]['count'] ?? 0;
});
2020-04-27 02:21:18 +02:00
}
private function getValue(array $row)
{
if ($row) {
2020-04-28 02:41:06 +02:00
if (!empty($row[0]['value'])) {
$row = reset($row);
}
2020-04-27 02:21:18 +02:00
return unserialize($row['value']);
}
return null;
2020-04-25 21:57:55 +02:00
}
2020-04-28 02:41:06 +02:00
public static function getDbConnection(array $settings): Pool
2020-04-25 21:57:55 +02:00
{
2020-04-28 02:41:06 +02:00
return Mysql::getConnection(
$settings['host'],
$settings['port'],
$settings['user'],
$settings['password'],
$settings['database'],
2020-05-04 22:09:39 +02:00
$settings['max_connections'],
$settings['idle_timeout']
2020-04-25 21:57:55 +02:00
);
}
/**
* Create table for property
*
* @return array|null
* @throws \Throwable
*/
private function prepareTable()
{
2020-05-17 21:04:32 +02:00
Logger::log("Creating/checking table {$this->table}", Logger::WARNING);
2020-05-12 19:35:15 +02:00
return yield $this->request("
2020-04-25 21:57:55 +02:00
CREATE TABLE IF NOT EXISTS `{$this->table}`
(
`key` VARCHAR(255) NOT NULL,
2020-04-27 02:21:18 +02:00
`value` MEDIUMBLOB NULL,
2020-04-25 21:57:55 +02:00
`ts` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`key`)
)
2020-05-05 19:05:32 +02:00
ENGINE = InnoDB
CHARACTER SET 'utf8mb4'
COLLATE 'utf8mb4_general_ci'
2020-04-25 21:57:55 +02:00
");
}
2020-04-28 02:41:06 +02:00
private function renameTable(string $from, string $to)
{
2020-05-17 21:04:32 +02:00
Logger::log("Renaming table {$from} to {$to}", Logger::WARNING);
2020-05-12 19:35:15 +02:00
yield $this->request("
2020-05-16 23:38:30 +02:00
ALTER TABLE `{$from}` RENAME TO `{$to}`;
2020-05-03 16:04:30 +02:00
");
2020-05-12 19:35:15 +02:00
yield $this->request("
2020-05-16 23:38:30 +02:00
DROP TABLE IF EXISTS `{$from}`;
2020-05-03 16:04:30 +02:00
");
2020-04-28 02:41:06 +02:00
}
2020-04-25 21:57:55 +02:00
/**
* Perform async request to db
2020-04-28 02:41:06 +02:00
*
* @param string $query
* @param array $params
*
* @return Promise
* @throws \Throwable
*/
private function request(string $query, array $params = []): Promise
{
return call(function() use($query, $params) {
2020-05-12 19:35:15 +02:00
Logger::log([$query, $params], Logger::VERBOSE);
if (empty($this->db) || !$this->db->isAlive()) {
Logger::log('No database connection', Logger::WARNING);
2020-04-28 02:41:06 +02:00
return [];
}
2020-05-03 16:04:30 +02:00
try {
$request = yield $this->db->execute($query, $params);
} catch (\Throwable $e) {
2020-05-12 00:41:27 +02:00
Logger::log($e->getMessage(), Logger::ERROR);
2020-05-03 16:04:30 +02:00
return [];
}
2020-04-28 02:41:06 +02:00
$result = [];
if ($request instanceof ResultSet) {
while (yield $request->advance()) {
$result[] = $request->getCurrent();
2020-04-25 21:57:55 +02:00
}
2020-04-28 02:41:06 +02:00
}
return $result;
});
2020-04-25 21:57:55 +02:00
}
}