Skip to content

Commit

Permalink
refactor Task to native enum
Browse files Browse the repository at this point in the history
  • Loading branch information
Nielsvanpach committed Jun 12, 2024
1 parent ef47b64 commit cfa484a
Show file tree
Hide file tree
Showing 21 changed files with 55 additions and 49 deletions.
4 changes: 2 additions & 2 deletions src/Commands/MonitorBackupsCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ protected function checkSourcesHealth(): self
$this->error("Source `{$source->name}` is unhealthy");

foreach ($failureMessages as $failureMessage) {
$source->logError(Task::MONITOR, $failureMessage);
$source->logError(Task::Monitor, $failureMessage);
}

$source->update(['healthy' => false]);
Expand Down Expand Up @@ -79,7 +79,7 @@ protected function checkDestinationsHealth(): self
$this->error("Destination `{$destination->name}` is unhealthy");

foreach ($failureMessages as $failureMessage) {
$destination->logError(Task::MONITOR, $failureMessage);
$destination->logError(Task::Monitor, $failureMessage);
}

event(new UnhealthyDestinationFoundEvent($destination, $failureMessages));
Expand Down
8 changes: 4 additions & 4 deletions src/Models/Backup.php
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ public function markAsInProgress(): self

public function markAsCompleted(): self
{
$this->logInfo(Task::BACKUP, 'Backup completed.');
$this->logInfo(Task::Backup, 'Backup completed.');

$this->update([
'status' => BackupStatus::Completed,
Expand All @@ -124,7 +124,7 @@ public function markAsCompleted(): self

public function markAsFailed(string $errorMessage): self
{
$this->logError(Task::BACKUP, "Backup failed: {$errorMessage}");
$this->logError(Task::Backup, "Backup failed: {$errorMessage}");

$this->update([
'status' => BackupStatus::Failed,
Expand All @@ -146,7 +146,7 @@ public function scopeFailed(Builder $query): void
public function handleProgress(string $type, string $progressOutput): self
{
if ($type === Process::ERR) {
$this->logError(Task::BACKUP, $progressOutput);
$this->logError(Task::Backup, $progressOutput);

return $this;
}
Expand All @@ -162,7 +162,7 @@ public function handleProgress(string $type, string $progressOutput): self
return $this;
}

protected function addMessageToLog(string $task, string $level, string $message): Backup
protected function addMessageToLog(Task $task, string $level, string $message): Backup
{
$this->logItems()->create([
'source_id' => $this->source_id,
Expand Down
5 changes: 5 additions & 0 deletions src/Models/BackupLogItem.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Spatie\BackupServer\Support\Helpers\Enums\Task;

class BackupLogItem extends Model
{
Expand All @@ -14,6 +15,10 @@ class BackupLogItem extends Model

protected $guarded = [];

protected $casts = [
'task' => Task::class,
];

public function source(): BelongsTo
{
return $this->belongsTo(Source::class);
Expand Down
7 changes: 4 additions & 3 deletions src/Models/Concerns/LogsActivity.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Illuminate\Database\Eloquent\Relations\HasMany;
use Spatie\BackupServer\Models\BackupLogItem;
use Spatie\BackupServer\Support\Helpers\Enums\LogLevel;
use Spatie\BackupServer\Support\Helpers\Enums\Task;

trait LogsActivity
{
Expand All @@ -13,15 +14,15 @@ public function logItems(): HasMany
return $this->hasMany(BackupLogItem::class);
}

public function logInfo(string $task, string $text): void
public function logInfo(Task $task, string $text): void
{
$this->addMessageToLog($task, LogLevel::INFO, $text);
}

public function logError(string $task, string $text): void
public function logError(Task $task, string $text): void
{
$this->addMessageToLog($task, LogLevel::ERROR, $text);
}

abstract protected function addMessageToLog(string $task, string $level, string $message);
abstract protected function addMessageToLog(Task $task, string $level, string $message);
}
3 changes: 2 additions & 1 deletion src/Models/Destination.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use Spatie\BackupServer\Models\Concerns\HasAsyncDelete;
use Spatie\BackupServer\Models\Concerns\HasBackupRelation;
use Spatie\BackupServer\Models\Concerns\LogsActivity;
use Spatie\BackupServer\Support\Helpers\Enums\Task;
use Spatie\BackupServer\Tasks\Cleanup\Jobs\DeleteDestinationJob;
use Spatie\BackupServer\Tasks\Monitor\HealthCheckCollection;
use Spatie\BackupServer\Tests\Database\Factories\DestinationFactory;
Expand Down Expand Up @@ -64,7 +65,7 @@ public function reachable(): bool
}
}

protected function addMessageToLog(string $task, string $level, string $message): void
protected function addMessageToLog(Task $task, string $level, string $message): void
{
$this->logItems()->create([
'task' => $task,
Expand Down
3 changes: 2 additions & 1 deletion src/Models/Source.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Spatie\BackupServer\Models\Concerns\HasAsyncDelete;
use Spatie\BackupServer\Models\Concerns\HasBackupRelation;
use Spatie\BackupServer\Models\Concerns\LogsActivity;
use Spatie\BackupServer\Support\Helpers\Enums\Task;
use Spatie\BackupServer\Tasks\Cleanup\Jobs\DeleteSourceJob;
use Spatie\BackupServer\Tasks\Monitor\HealthCheckCollection;
use Spatie\BackupServer\Tests\Database\Factories\SourceFactory;
Expand Down Expand Up @@ -102,7 +103,7 @@ public function scopeUnhealthy(Builder $query): void
$query->where('healthy', false);
}

protected function addMessageToLog(string $task, string $level, string $message): Source
protected function addMessageToLog(Task $task, string $level, string $message): Source
{
$this->logItems()->create([
'destination_id' => $this->destination_id,
Expand Down
10 changes: 4 additions & 6 deletions src/Support/Helpers/Enums/Task.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,9 @@

namespace Spatie\BackupServer\Support\Helpers\Enums;

class Task
enum Task: string
{
public const BACKUP = 'backup';

public const CLEANUP = 'cleanup';

public const MONITOR = 'monitor';
case Backup = 'backup';
case Cleanup = 'cleanup';
case Monitor = 'monitor';
}
2 changes: 1 addition & 1 deletion src/Tasks/Backup/Actions/CreateBackupAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public function execute(Source $source): Backup
($this->afterBackupModelCreated)($backup);
}

$backup->logInfo(Task::BACKUP, 'Dispatching backup job...');
$backup->logInfo(Task::Backup, 'Dispatching backup job...');

$job = (new PerformBackupJob($backup));

Expand Down
2 changes: 1 addition & 1 deletion src/Tasks/Backup/Jobs/BackupTasks/CalculateBackupSize.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ class CalculateBackupSize implements BackupTask
{
public function execute(Backup $backup): void
{
$backup->logInfo(Task::BACKUP, 'Calculating backup size...');
$backup->logInfo(Task::Backup, 'Calculating backup size...');

$backup->recalculateBackupSize();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,17 @@ public function executeBackupCommands(Backup $backup, string $commandAttributeNa

$label = str_replace('_', ' ', $commandAttributeName);

$backup->logInfo(Task::BACKUP, "Performing {$label}...");
$backup->logInfo(Task::Backup, "Performing {$label}...");

/** @var \Symfony\Component\Process\Process $process */
$process = $backup->source->executeSshCommands($commands);

if (! $process->isSuccessful()) {
$backup->logError(Task::BACKUP, $label.' error output:'.PHP_EOL.$process->getErrorOutput());
$backup->logError(Task::Backup, $label.' error output:'.PHP_EOL.$process->getErrorOutput());

throw BackupFailed::BackupCommandsFailed($backup, $commandAttributeName, $process->getErrorOutput());
}

$backup->logInfo(Task::BACKUP, $label.' output:'.PHP_EOL.$process->getOutput());
$backup->logInfo(Task::Backup, $label.' output:'.PHP_EOL.$process->getOutput());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ class DetermineDestinationPath implements BackupTask
{
public function execute(Backup $backup): void
{
$backup->logInfo(Task::BACKUP, 'Determining destination directory...');
$backup->logInfo(Task::Backup, 'Determining destination directory...');

$directory = $backup->destination->directory.$backup->source->id.'/backup-'.$backup->created_at->format('Y-m-d-His').'/';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ class EnsureDestinationIsReachable implements BackupTask
{
public function execute(Backup $backup): void
{
$backup->logInfo(Task::BACKUP, 'Ensuring destination is reachable...');
$backup->logInfo(Task::Backup, 'Ensuring destination is reachable...');

if (! $backup->destination->reachable()) {
throw BackupFailed::destinationNotReachable($backup);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ class EnsureSourceIsReachable implements BackupTask
{
public function execute(Backup $backup): void
{
$backup->logInfo(Task::BACKUP, 'Ensuring source is reachable...');
$backup->logInfo(Task::Backup, 'Ensuring source is reachable...');

$process = $backup->source->executeSshCommands(['whoami']);

Expand Down
4 changes: 2 additions & 2 deletions src/Tasks/Backup/Jobs/BackupTasks/RunBackup.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class RunBackup implements BackupTask
{
public function execute(Backup $backup): void
{
$backup->logInfo(Task::BACKUP, 'Running backup...');
$backup->logInfo(Task::Backup, 'Running backup...');

$pendingBackup = (new PendingBackup())
->from($backup->sourceLocation())
Expand Down Expand Up @@ -87,7 +87,7 @@ protected function saveRsyncSummary(Backup $backup, string $output)

$summary = substr($output, $startingPosition);

$backup->logInfo(Task::BACKUP, trim($summary));
$backup->logInfo(Task::Backup, trim($summary));

$backup->update([
'rsync_summary' => trim($summary),
Expand Down
6 changes: 3 additions & 3 deletions src/Tasks/Cleanup/Jobs/PerformCleanupDestinationJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,18 +37,18 @@ public function __construct(public Destination $destination)

public function handle(): void
{
$this->destination->logInfo(Task::CLEANUP, 'Starting cleanup of destination');
$this->destination->logInfo(Task::Cleanup, 'Starting cleanup of destination');

//TODO: implement

$this->destination->logInfo(Task::CLEANUP, 'Destination cleaned up');
$this->destination->logInfo(Task::Cleanup, 'Destination cleaned up');

event(new CleanupForDestinationCompletedEvent($this->destination));
}

public function failed(Throwable $exception): void
{
$this->destination->logError(Task::CLEANUP, "Error while cleaning up destination `{$this->destination->name}`: `{$exception->getMessage()}`");
$this->destination->logError(Task::Cleanup, "Error while cleaning up destination `{$this->destination->name}`: `{$exception->getMessage()}`");

event(new CleanupForDestinationFailedEvent($this->destination, $exception->getMessage()));
}
Expand Down
6 changes: 3 additions & 3 deletions src/Tasks/Cleanup/Jobs/PerformCleanupSourceJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public function __construct(public Source $source)

public function handle(): void
{
$this->source->logInfo(Task::CLEANUP, 'Starting cleanup...');
$this->source->logInfo(Task::Cleanup, 'Starting cleanup...');

$tasks = [
DeleteBackupsWithoutDirectoriesFromDb::class,
Expand All @@ -54,12 +54,12 @@ public function handle(): void

event(new CleanupForSourceCompletedEvent($this->source));

$this->source->logInfo(Task::CLEANUP, 'Cleanup done!');
$this->source->logInfo(Task::Cleanup, 'Cleanup done!');
}

public function failed(Throwable $exception): void
{
$this->source->logError(Task::CLEANUP, "Error while cleaning up source `{$this->source->name}`: `{$exception->getMessage()}`");
$this->source->logError(Task::Cleanup, "Error while cleaning up source `{$this->source->name}`: `{$exception->getMessage()}`");

report($exception);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public function execute(Source $source): void
->completedBackups()
->each(function (Backup $backup) {
if (! $backup->existsOnDisk()) {
$backup->source->logInfo(Task::CLEANUP, "Removing backup id `{$backup->id}` because its directory `{$backup->destinationLocation()->getPath()}` on disk `{$backup->disk_name}` does not exist anymore ");
$backup->source->logInfo(Task::Cleanup, "Removing backup id `{$backup->id}` because its directory `{$backup->destinationLocation()->getPath()}` on disk `{$backup->disk_name}` does not exist anymore ");
$backup->delete();
}
});
Expand Down
2 changes: 1 addition & 1 deletion src/Tasks/Cleanup/Jobs/Tasks/DeleteFailedBackups.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public function execute(Source $source): void
->get()
->filter(fn (Backup $backup) => $backup->created_at->diffInDays() > 1)
->each(function (Backup $backup) use ($source) {
$source->logInfo(Task::CLEANUP, "Removing backup id {$backup->id} because it has failed");
$source->logInfo(Task::Cleanup, "Removing backup id {$backup->id} because it has failed");

$backup->delete();
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ class RecalculateRealBackupSizes implements CleanupTask
{
public function execute(Source $source): void
{
$source->logInfo(Task::CLEANUP, 'Recalculating real backup sizes...');
$source->logInfo(Task::Cleanup, 'Recalculating real backup sizes...');

/** @var \Spatie\BackupServer\Tasks\Backup\Support\BackupCollection $backupCollection */
$backupCollection = $source->completedBackups()->get();
Expand Down
2 changes: 1 addition & 1 deletion src/Tasks/Cleanup/Strategies/DefaultCleanupStrategy.php
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ protected function removeOldBackupsUntilUsingLessThanMaximumStorage(BackupCollec
/** @var \Spatie\BackupServer\Models\Backup $oldestBackup */
$oldestBackup = $backups->oldest();

$oldestBackup->logInfo(Task::CLEANUP, 'Deleting backup because destination uses more space than the limit allows');
$oldestBackup->logInfo(Task::Cleanup, 'Deleting backup because destination uses more space than the limit allows');

$oldestBackup->delete();

Expand Down
24 changes: 12 additions & 12 deletions tests/Unit/Models/Concerns/LogsActivityTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,71 +10,71 @@
test('a source can log activity', function () {
$source = Source::factory()->create();

$source->logInfo(Task::BACKUP, 'info for backup task');
$source->logInfo(Task::Backup, 'info for backup task');
$this->assertDatabaseHas('backup_server_backup_log', [
'source_id' => $source->id,
'backup_id' => null,
'destination_id' => $source->destination->id,
'level' => LogLevel::INFO,
'task' => Task::BACKUP,
'task' => Task::Backup,
'message' => 'info for backup task',
]);

$source->logError(Task::CLEANUP, 'error for cleanup task');
$source->logError(Task::Cleanup, 'error for cleanup task');
$this->assertDatabaseHas('backup_server_backup_log', [
'source_id' => $source->id,
'backup_id' => null,
'destination_id' => $source->destination->id,
'level' => LogLevel::ERROR,
'task' => Task::CLEANUP,
'task' => Task::Cleanup,
'message' => 'error for cleanup task',
]);
});

test('a backup can log activity', function () {
$backup = Backup::factory()->make();

$backup->logInfo(Task::BACKUP, 'info for backup task');
$backup->logInfo(Task::Backup, 'info for backup task');
$this->assertDatabaseHas('backup_server_backup_log', [
'source_id' => $backup->source->id,
'backup_id' => $backup->id,
'destination_id' => $backup->destination->id,
'level' => LogLevel::INFO,
'task' => Task::BACKUP,
'task' => Task::Backup,
'message' => 'info for backup task',
]);

$backup->logError(Task::CLEANUP, 'error for cleanup task');
$backup->logError(Task::Cleanup, 'error for cleanup task');
$this->assertDatabaseHas('backup_server_backup_log', [
'source_id' => $backup->source->id,
'backup_id' => $backup->id,
'destination_id' => $backup->destination->id,
'level' => LogLevel::ERROR,
'task' => Task::CLEANUP,
'task' => Task::Cleanup,
'message' => 'error for cleanup task',
]);
});

test('a destination can log activity', function () {
$destination = Destination::factory()->create();

$destination->logInfo(Task::BACKUP, 'info for backup task');
$destination->logInfo(Task::Backup, 'info for backup task');
$this->assertDatabaseHas('backup_server_backup_log', [
'source_id' => null,
'backup_id' => null,
'destination_id' => $destination->id,
'level' => LogLevel::INFO,
'task' => Task::BACKUP,
'task' => Task::Backup,
'message' => 'info for backup task',
]);

$destination->logError(Task::CLEANUP, 'error for cleanup task');
$destination->logError(Task::Cleanup, 'error for cleanup task');
$this->assertDatabaseHas('backup_server_backup_log', [
'source_id' => null,
'backup_id' => null,
'destination_id' => $destination->id,
'level' => LogLevel::ERROR,
'task' => Task::CLEANUP,
'task' => Task::Cleanup,
'message' => 'error for cleanup task',
]);
});

0 comments on commit cfa484a

Please sign in to comment.