*/ private array $ignoredFiles = []; private bool $isLocked = false; public function __construct( private readonly DeletesBackups $deleteBackup, private readonly BackupManager $backupManager, ) {} /** @return NormalizedValidationRules */ public static function rules(): array { return [ 'name' => ['nullable', 'string', 'max:191'], 'is_locked' => ['nullable', 'boolean'], 'ignored_files' => ['nullable', 'array', 'list'], 'ignored_files.*' => ['string'], ]; } public function setIsLocked(bool $isLocked): InitiatesBackups { $this->isLocked = $isLocked; return $this; } public function setIgnoredFiles(?array $ignored): InitiatesBackups { $this->ignoredFiles = $ignored ?? []; return $this; } public function initiate(Server $server, ?string $name = null, bool $override = false): Backup { Validator::validate(['name' => $name, 'is_locked' => $this->isLocked, 'ignored_files' => $this->ignoredFiles], self::rules()); [$backup, $rotated] = DB::transaction(/** @return array{Backup, Collection} */ function () use ($server, $name, $override): array { $limit = config('backups.throttles.limit'); $period = config('backups.throttles.period'); if ($period > 0) { $previousCount = $server->backups() ->withTrashed() ->nonFailed() ->where('created_at', '>=', CarbonImmutable::now()->subSeconds($period)) ->lockForUpdate() ->count(); if ($previousCount >= $limit) { $message = sprintf('Only %d backups may be generated within a %d second span of time.', $limit, $period); $latest = $server->backups() ->withTrashed() ->nonFailed() ->where('created_at', '>=', CarbonImmutable::now()->subSeconds($period)) ->orderByDesc('created_at') ->first() ?? throw new UnexpectedValueException('The backup throttle query returned an empty result set.'); throw new TooManyRequestsHttpException((int) CarbonImmutable::now()->diffInSeconds($latest->created_at?->addSeconds($period)), $message); } } $rotated = new Collection; $count = $server->backups()->nonFailed()->lockForUpdate()->count(); if (! $server->backup_limit || $count >= $server->backup_limit) { // Do not allow the user to continue if this server is already at its limit and can't override. if (! $override || $server->backup_limit <= 0) { throw new TooManyBackupsException($server->backup_limit); } // Pick the oldest backups that are not "locked" (indicating a backup that should never // be automatically purged) to make room for this one. A backup rotated out by another // request that has not finished deleting it still counts here, so take enough to bring // the server back to its limit. They are deleted once Wings accepts the new backup. $needed = $count - $server->backup_limit + 1; $rotated = $server->backups() ->nonFailed() ->where('is_locked', false) ->orderBy('created_at') ->limit($needed) ->get(); if ($rotated->count() < $needed) { throw new TooManyBackupsException($server->backup_limit); } } $backup = $server->backups()->create([ 'uuid' => Uuid::uuid4()->toString(), 'name' => mb_trim($name ?? '') ?: sprintf('Backup at %s', CarbonImmutable::now()->toDateTimeString()), // Don't use the PHP empty function here in case anything that is "empty" by default // (0, false, etc.) was passed as a file or folder name. 'ignored_files' => array_values(array_filter($this->ignoredFiles, fn (string $file): bool => $file !== '')), 'disk' => $this->backupManager->getDefaultAdapter(), 'is_locked' => $this->isLocked, ]); return [$backup, $rotated]; }); // Wings is only asked once the rows are committed, and backups rotated out to make room // are deleted only after it accepts the new one. try { Daemon::server($server)->backups()->create($backup); } catch (Throwable $throwable) { // Record the attempt as failed, the same state Wings reports for a failed backup. $backup->forceFill([ 'is_successful' => false, 'is_locked' => false, 'completed_at' => CarbonImmutable::now(), ])->save(); throw $throwable; } Activity::event('server:backup.start') ->subject($server, $backup) ->property(['name' => $backup->name, 'locked' => $backup->is_locked]) ->log(); foreach ($rotated as $old) { // Re-read the row: it may have been deleted or locked since it was picked. $current = Backup::query()->whereKey($old->getKey())->first(); if ($current === null) { continue; } try { $this->deleteBackup->delete($current); } catch (Throwable $throwable) { // The new backup is already running, so leave the server one over its limit // rather than failing a request Wings accepted. report($throwable); } } return $backup->refresh(); } }