Отправка копий базы на FTP (свой клиент на потоках) и второй пример расписания

This commit is contained in:
rsgrinko committed 2026-09-16 16:15:46 +03:00
1 parent 0732897a8c
commit 7355566289
20 files changed
+1040 -12

No files matched your search

+84 -1
View File
@@ -10,9 +10,14 @@ declare(strict_types=1);
*/
use Rsgrinko\Proton\Backup\Backup;
use Rsgrinko\Proton\Backup\BackupJob;
use Rsgrinko\Proton\Backup\ShipBackupJob;
use Rsgrinko\Proton\Database\Connection;
use Rsgrinko\Proton\Database\Migrator;
use Rsgrinko\Proton\Models\Role;
use Rsgrinko\Proton\Models\Setting;
use Rsgrinko\Proton\Models\User;
use Rsgrinko\Proton\Models\UserNotification;
use Rsgrinko\Proton\Support\Config;
use Rsgrinko\Proton\Support\ProtonException;
@@ -201,10 +206,88 @@ test('копии: расписание включается настройкой
}
});
// Соседям расписание нужно в исходном виде
Rsgrinko\Proton\Queue\Scheduler::reset();
});
test('заметки: пересчёт slug по расписанию выключен, пока не задан NOTES_SLUG_RESYNC', function (): void {
putenv('NOTES_SLUG_RESYNC');
Rsgrinko\Proton\Queue\Scheduler::reset();
$names = array_column(Rsgrinko\Proton\Queue\Scheduler::tasks(), 'name');
assertFalse(in_array('notes:rebuild-slugs', $names, true), 'без переменной задача не планируется');
putenv('NOTES_SLUG_RESYNC=true');
Rsgrinko\Proton\Queue\Scheduler::reset();
$names = array_column(Rsgrinko\Proton\Queue\Scheduler::tasks(), 'name');
assertTrue(in_array('notes:rebuild-slugs', $names, true), 'с переменной — задача появилась');
putenv('NOTES_SLUG_RESYNC');
Rsgrinko\Proton\Queue\Scheduler::reset();
});
test('копии: FTP не настроен — отправка не ставится в очередь', function (): void {
withBackupSandbox(static function (): void {
withConfig(['backup.ftp.host' => ''], static function (): void {
(new BackupJob())->handle([]);
$queued = Connection::instance()->select(
"SELECT COUNT(*) AS n FROM jobs WHERE job_class = :c",
['c' => ShipBackupJob::class]
);
assertSame(0, (int) $queued[0]['n']);
});
});
});
test('копии: FTP настроен — после копии отправка ставится в очередь', function (): void {
withBackupSandbox(static function (): void {
withConfig(['backup.ftp.host' => 'ftp.example.com'], static function (): void {
(new BackupJob())->handle([]);
$queued = Connection::instance()->select(
"SELECT payload FROM jobs WHERE job_class = :c",
['c' => ShipBackupJob::class]
);
assertCount(1, $queued);
$payload = (array) json_decode((string) $queued[0]['payload'], true);
assertMatches('/^proton-.*\.sqlite\.gz$/', (string) $payload['name']);
});
});
});
test('ShipBackupJob: без имени в задаче — понятная ошибка, а не падение', function (): void {
$error = assertThrows(static fn () => (new ShipBackupJob())->handle([]));
assertTrue($error instanceof ProtonException);
assertContains('нет имени копии', $error->getMessage());
});
test('ShipBackupJob: не отправилась — уведомление тем, у кого system.manage', function (): void {
withOwnDatabase(static function (): void {
$admin = User::register('ship_admin', 'секрет123', [
'email' => 'ship_admin@example.com',
'role_id' => Role::admin()?->id() ?? 0,
]);
(new ShipBackupJob())->failed(['name' => 'proton-test.sqlite.gz'], 'сервер не ответил');
assertSame(1, UserNotification::unreadFor($admin->id()));
$notification = assertNotNull(
UserNotification::query()->where('user_id', $admin->id())->orderBy('id', 'desc')->first()
);
assertSame('backup.ship_failed', $notification->raw('type'));
});
});
test('копии: размер показывается по-человечески', function (): void {
assertSame('1,0 КБ', Backup::size(1024));
assertSame('13,2 КБ', Backup::size(13517));
+185
View File
@@ -0,0 +1,185 @@
<?php
declare(strict_types=1);
/**
* Отправка копии базы на FTP: свой клиент на потоках, без расширения ftp.
*
* Настоящего FTP-сервера в проекте нет, поэтому клиент проверяется против
* tests/support/fake_ftp_server.php — игрушечного однопроходного сервера,
* который понимает USER/PASS/TYPE/CWD/MKD/PASV/STOR/QUIT. Так протокол
* (разбор PASV, порядок команд, коды ошибок) проверен по-настоящему,
* а не угадан.
*/
use Rsgrinko\Proton\Backup\Ftp;
use Rsgrinko\Proton\Support\ProtonException;
/**
* Поднимает игрушечный сервер и ждёт, пока он объявит порт.
*
* @return array{process: resource, pipes: array<int, resource>, port: int, portFile: string, destFile: string}
*/
function startFakeFtp(string $mode = 'ok'): array
{
$token = bin2hex(random_bytes(4));
$portFile = APP_ROOT . '/var/tmp/ftp-test-port-' . $token . '.txt';
$destFile = APP_ROOT . '/var/tmp/ftp-test-received-' . $token . '.bin';
@unlink($portFile);
@unlink($destFile);
$process = proc_open(
['php', APP_ROOT . '/tests/support/fake_ftp_server.php', $portFile, $destFile, $mode],
[1 => ['pipe', 'w'], 2 => ['pipe', 'w']],
$pipes
);
if (!is_resource($process)) {
throw new RuntimeException('Не удалось запустить тестовый FTP-сервер');
}
$deadline = microtime(true) + 10;
while (!is_file($portFile) && microtime(true) < $deadline) {
usleep(10000);
}
if (!is_file($portFile)) {
proc_terminate($process);
throw new RuntimeException('Тестовый FTP-сервер не поднялся за 10 секунд');
}
return [
'process' => $process,
'pipes' => $pipes,
'port' => (int) trim((string) file_get_contents($portFile)),
'portFile' => $portFile,
'destFile' => $destFile,
];
}
/**
* @param array{process: resource, pipes: array<int, resource>, port: int, portFile: string, destFile: string} $server
*/
function stopFakeFtp(array $server): void
{
foreach ($server['pipes'] as $pipe) {
if (is_resource($pipe)) {
@fclose($pipe);
}
}
if (is_resource($server['process'])) {
@proc_terminate($server['process']);
@proc_close($server['process']);
}
@unlink($server['portFile']);
@unlink($server['destFile']);
}
/**
* Отправляет тестовый файл через настоящий Ftp::upload() на фейковый сервер.
*/
function shipToFakeFtp(int $port, string $localPath, string $path = ''): void
{
withConfig([
'backup.ftp.host' => '127.0.0.1',
'backup.ftp.port' => $port,
'backup.ftp.username' => 'test',
'backup.ftp.password' => 'secret',
'backup.ftp.path' => $path,
'backup.ftp.timeout' => 5,
], static function () use ($localPath): void {
Ftp::upload($localPath);
});
}
test('ftp: включён только когда задан хост', function (): void {
withConfig(['backup.ftp.host' => ''], static function (): void {
assertFalse(Ftp::enabled());
});
withConfig(['backup.ftp.host' => 'ftp.example.com'], static function (): void {
assertTrue(Ftp::enabled());
});
});
test('ftp: недоступный сервер — понятная ошибка, а не падение', function (): void {
$file = APP_ROOT . '/var/tmp/ftp-test-unreachable.bin';
file_put_contents($file, 'данные');
// Порт, на котором точно никто не слушает
$error = assertThrows(static fn () => shipToFakeFtp(1, $file));
assertTrue($error instanceof ProtonException);
assertContains('Не удалось подключиться', $error->getMessage());
@unlink($file);
});
test('ftp: файл доезжает целиком через PASV', function (): void {
$server = startFakeFtp();
try {
$file = APP_ROOT . '/var/tmp/ftp-test-source.bin';
$body = str_repeat('proton-backup-', 5000); // больше одного чтения буфером
file_put_contents($file, $body);
shipToFakeFtp($server['port'], $file);
assertSame($body, file_get_contents($server['destFile']));
@unlink($file);
} finally {
stopFakeFtp($server);
}
});
test('ftp: каталог заводится сам, если сервер ответил на CWD «нет такого»', function (): void {
$server = startFakeFtp('cwd-fail-then-mkd');
try {
$file = APP_ROOT . '/var/tmp/ftp-test-mkd.bin';
file_put_contents($file, 'x');
shipToFakeFtp($server['port'], $file, 'proton/backups');
assertSame('x', file_get_contents($server['destFile']));
@unlink($file);
} finally {
stopFakeFtp($server);
}
});
test('ftp: сервер отверг вход — сообщение доходит целиком', function (): void {
$server = startFakeFtp('auth-fail');
try {
$file = APP_ROOT . '/var/tmp/ftp-test-auth.bin';
file_put_contents($file, 'x');
$error = assertThrows(static fn () => shipToFakeFtp($server['port'], $file));
assertTrue($error instanceof ProtonException);
assertContains('530', $error->getMessage());
@unlink($file);
} finally {
stopFakeFtp($server);
}
});
test('ftp: отправка несуществующего файла не достаёт до сети', function (): void {
$error = assertThrows(static fn () => Ftp::upload(APP_ROOT . '/var/tmp/нет-такого-файла.bin'));
assertTrue($error instanceof ProtonException);
assertContains('Файла для отправки нет', $error->getMessage());
});
+9
View File
@@ -297,6 +297,15 @@ test('http: лимит заметок на пользователя провер
});
});
test('http: отправка копии на FTP из панели требует настроенного хоста', function (): void {
assertStatus(403, httpRequest('POST', '/admin/backups/ship', httpUser(), ['name' => 'proton-x.sqlite.gz']));
$response = httpRequest('POST', '/admin/backups/ship', httpAdmin(), ['name' => 'proton-x.sqlite.gz']);
assertStatus(302, $response);
assertContains('/admin/backups', $response->header('Location'));
});
test('http: накат миграций из панели доступен только с system.manage', function (): void {
assertStatus(403, httpRequest('POST', '/admin/system/migrate', httpUser()));
+134
View File
@@ -0,0 +1,134 @@
<?php
declare(strict_types=1);
/**
* Игрушечный FTP-сервер на одну сессию — только для tests/FtpTest.php.
* Настоящего FTP в проекте нет, поэтому Rsgrinko\Proton\Backup\Ftp проверяется
* против него: разбор PASV, отправка данных, коды ошибок.
*
* Аргументы: <файл для порта> <файл назначения> [режим]
* Режимы: ok (по умолчанию), auth-fail (PASS отвечает 530),
* cwd-fail-then-mkd (первый CWD отвечает 550, дальше как обычно).
*/
$portFile = (string) ($argv[1] ?? '');
$destFile = (string) ($argv[2] ?? '');
$mode = (string) ($argv[3] ?? 'ok');
$server = stream_socket_server('tcp://127.0.0.1:0', $errno, $errstr);
if ($server === false) {
fwrite(STDERR, $errstr);
exit(1);
}
$name = (string) stream_socket_get_name($server, false);
$port = (int) substr($name, (int) strrpos($name, ':') + 1);
file_put_contents($portFile, (string) $port);
$control = @stream_socket_accept($server, 20);
if ($control === false) {
exit(1);
}
fwrite($control, "220 fake ftp ready\r\n");
$cwdAttempts = 0;
$dataServer = null;
while (!feof($control)) {
$line = fgets($control, 1024);
if ($line === false) {
break;
}
$line = trim($line);
if ($line === '') {
continue;
}
$parts = explode(' ', $line, 2);
$cmd = strtoupper($parts[0]);
switch ($cmd) {
case 'USER':
fwrite($control, "331 need password\r\n");
break;
case 'PASS':
fwrite($control, $mode === 'auth-fail' ? "530 login incorrect\r\n" : "230 logged in\r\n");
break;
case 'TYPE':
fwrite($control, "200 ok\r\n");
break;
case 'CWD':
$cwdAttempts++;
fwrite($control, $mode === 'cwd-fail-then-mkd' && $cwdAttempts === 1
? "550 no such directory\r\n"
: "250 ok\r\n");
break;
case 'MKD':
fwrite($control, "257 created\r\n");
break;
case 'PASV':
$dataServer = stream_socket_server('tcp://127.0.0.1:0', $de, $ds);
$dname = (string) stream_socket_get_name($dataServer, false);
$dport = (int) substr($dname, (int) strrpos($dname, ':') + 1);
$p1 = intdiv($dport, 256);
$p2 = $dport % 256;
fwrite($control, '227 Entering Passive Mode (127,0,0,1,' . $p1 . ',' . $p2 . ")\r\n");
break;
case 'STOR':
fwrite($control, "150 opening data connection\r\n");
$received = '';
$data = $dataServer !== null && $dataServer !== false ? @stream_socket_accept($dataServer, 20) : false;
if ($data !== false) {
while (!feof($data)) {
$chunk = fread($data, 65536);
if ($chunk === false) {
break;
}
$received .= $chunk;
}
fclose($data);
}
file_put_contents($destFile, $received);
fwrite($control, "226 transfer complete\r\n");
break;
case 'QUIT':
fwrite($control, "221 bye\r\n");
break 2;
default:
fwrite($control, "500 unknown command\r\n");
}
}
fclose($control);