Use new enum

This commit is contained in:
Lance Pioch 2024-04-18 03:50:20 -04:00
parent 256a961e1b
commit c5008a43e7
15 changed files with 60 additions and 66 deletions

View File

@ -2,6 +2,7 @@
namespace App\Exceptions\Http\Server; namespace App\Exceptions\Http\Server;
use App\Enums\ServerState;
use App\Models\Server; use App\Models\Server;
use Symfony\Component\HttpKernel\Exception\ConflictHttpException; use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
@ -20,7 +21,7 @@ class ServerStateConflictException extends ConflictHttpException
$message = 'The node of this server is currently under maintenance and the functionality requested is unavailable.'; $message = 'The node of this server is currently under maintenance and the functionality requested is unavailable.';
} elseif (!$server->isInstalled()) { } elseif (!$server->isInstalled()) {
$message = 'This server has not yet completed its installation process, please try again later.'; $message = 'This server has not yet completed its installation process, please try again later.';
} elseif ($server->status === Server::STATUS_RESTORING_BACKUP) { } elseif ($server->status === ServerState::RestoringBackup) {
$message = 'This server is currently restoring from a backup, please try again later.'; $message = 'This server is currently restoring from a backup, please try again later.';
} elseif (!is_null($server->transfer)) { } elseif (!is_null($server->transfer)) {
$message = 'This server is currently being transferred to a new machine, please try again later.'; $message = 'This server is currently being transferred to a new machine, please try again later.';

View File

@ -48,21 +48,15 @@ class ServerResource extends Resource
return $details['state'] ?? 'unknown'; return $details['state'] ?? 'unknown';
}) })
->options([ ->options(collect(ContainerStatus::cases())->mapWithKeys(
'running' => 'Running', fn (ContainerStatus $status) => [$status->value => str($status->value)->ucwords()]
'starting' => 'Starting', ))
'stopping' => 'Stopping', ->colors(collect(ContainerStatus::cases())->mapWithKeys(
'offline' => 'Offline', fn (ContainerStatus $status) => [$status->value => $status->color()]
'unknown' => 'Unknown', ))
]) ->icons(collect(ContainerStatus::cases())->mapWithKeys(
fn (ContainerStatus $status) => [$status->value => $status->icon()]
->colors([ ))
'running' => 'success',
'offline' => 'danger',
'starting' => 'primary',
'stopping' => 'warning',
'unknown' => 'primary',
])
->grouped() ->grouped()
->columnSpanFull() ->columnSpanFull()
->inline(), ->inline(),
@ -73,23 +67,15 @@ class ServerResource extends Resource
->hiddenOn('create') ->hiddenOn('create')
->disableOptionWhen(fn ($state, $value) => $state !== $value) ->disableOptionWhen(fn ($state, $value) => $state !== $value)
->formatStateUsing(fn ($state) => $state ?? 'none') ->formatStateUsing(fn ($state) => $state ?? 'none')
->options([ ->options(collect(ServerState::cases())->mapWithKeys(
'none' => 'None', fn (ServerState $state) => [$state->value => str($state->value)->replace('_', ' ')->ucwords()]
Server::STATUS_INSTALLING => str(Server::STATUS_INSTALLING)->title()->replace('_', ' '), ))
Server::STATUS_INSTALL_FAILED => str(Server::STATUS_INSTALL_FAILED)->title()->replace('_', ' '), ->colors(collect(ServerState::cases())->mapWithKeys(
Server::STATUS_REINSTALL_FAILED => str(Server::STATUS_REINSTALL_FAILED)->title()->replace('_', ' '), fn (ServerState $state) => [$state->value => $state->color()]
Server::STATUS_SUSPENDED => str(Server::STATUS_SUSPENDED)->title()->replace('_', ' '), ))
Server::STATUS_RESTORING_BACKUP => str(Server::STATUS_RESTORING_BACKUP)->title()->replace('_', ' '), ->icons(collect(ServerState::cases())->mapWithKeys(
]) fn (ServerState $state) => [$state->value => $state->icon()]
))
->colors([
'none' => 'primary',
Server::STATUS_INSTALLING => 'primary',
Server::STATUS_INSTALL_FAILED => 'danger',
Server::STATUS_REINSTALL_FAILED => 'danger',
Server::STATUS_SUSPENDED => 'danger',
Server::STATUS_RESTORING_BACKUP => 'primary',
])
->grouped() ->grouped()
->columnSpanFull() ->columnSpanFull()
->inline(), ->inline(),

View File

@ -2,6 +2,7 @@
namespace App\Http\Controllers\Admin\Servers; namespace App\Http\Controllers\Admin\Servers;
use App\Enums\ServerState;
use App\Models\DatabaseHost; use App\Models\DatabaseHost;
use App\Models\Egg; use App\Models\Egg;
use App\Models\Mount; use App\Models\Mount;
@ -110,7 +111,7 @@ class ServerViewController extends Controller
*/ */
public function manage(Request $request, Server $server): View public function manage(Request $request, Server $server): View
{ {
if ($server->status === Server::STATUS_INSTALL_FAILED) { if ($server->status === ServerState::InstallFailed) {
throw new DisplayException('This server is in a failed install state and cannot be recovered. Please delete and re-create the server.'); throw new DisplayException('This server is in a failed install state and cannot be recovered. Please delete and re-create the server.');
} }

View File

@ -2,6 +2,7 @@
namespace App\Http\Controllers\Admin; namespace App\Http\Controllers\Admin;
use App\Enums\ServerState;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use App\Models\User; use App\Models\User;
use Illuminate\Http\Response; use Illuminate\Http\Response;
@ -71,11 +72,11 @@ class ServersController extends Controller
*/ */
public function toggleInstall(Server $server): RedirectResponse public function toggleInstall(Server $server): RedirectResponse
{ {
if ($server->status === Server::STATUS_INSTALL_FAILED) { if ($server->status === ServerState::InstallFailed) {
throw new DisplayException(trans('admin/server.exceptions.marked_as_failed')); throw new DisplayException(trans('admin/server.exceptions.marked_as_failed'));
} }
$server->status = $server->isInstalled() ? Server::STATUS_INSTALLING : null; $server->status = $server->isInstalled() ? ServerState::Installing : null;
$server->save(); $server->save();
$this->alert->success(trans('admin/server.alerts.install_toggled'))->flash(); $this->alert->success(trans('admin/server.alerts.install_toggled'))->flash();

View File

@ -2,6 +2,7 @@
namespace App\Http\Controllers\Api\Client\Servers; namespace App\Http\Controllers\Api\Client\Servers;
use App\Enums\ServerState;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use App\Models\Backup; use App\Models\Backup;
use App\Models\Server; use App\Models\Server;
@ -212,7 +213,7 @@ class BackupController extends ClientApiController
// Update the status right away for the server so that we know not to allow certain // Update the status right away for the server so that we know not to allow certain
// actions against it via the Panel API. // actions against it via the Panel API.
$server->update(['status' => Server::STATUS_RESTORING_BACKUP]); $server->update(['status' => ServerState::RestoringBackup]);
$this->daemonRepository->setServer($server)->restore($backup, $url ?? null, $request->input('truncate')); $this->daemonRepository->setServer($server)->restore($backup, $url ?? null, $request->input('truncate'));
}); });

View File

@ -2,6 +2,7 @@
namespace App\Http\Controllers\Api\Remote\Servers; namespace App\Http\Controllers\Api\Remote\Servers;
use App\Enums\ServerState;
use App\Models\Backup; use App\Models\Backup;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use App\Models\Server; use App\Models\Server;
@ -81,7 +82,7 @@ class ServerDetailsController extends Controller
->latest('timestamp'), ->latest('timestamp'),
]) ])
->where('node_id', $node->id) ->where('node_id', $node->id)
->where('status', Server::STATUS_RESTORING_BACKUP) ->where('status', ServerState::RestoringBackup)
->get(); ->get();
$this->connection->transaction(function () use ($node, $servers) { $this->connection->transaction(function () use ($node, $servers) {
@ -108,7 +109,7 @@ class ServerDetailsController extends Controller
// Update any server marked as installing or restoring as being in a normal state // Update any server marked as installing or restoring as being in a normal state
// at this point in the process. // at this point in the process.
Server::query()->where('node_id', $node->id) Server::query()->where('node_id', $node->id)
->whereIn('status', [Server::STATUS_INSTALLING, Server::STATUS_RESTORING_BACKUP]) ->whereIn('status', [ServerState::Installing, ServerState::RestoringBackup])
->update(['status' => null]); ->update(['status' => null]);
}); });

View File

@ -2,6 +2,7 @@
namespace App\Http\Controllers\Api\Remote\Servers; namespace App\Http\Controllers\Api\Remote\Servers;
use App\Enums\ServerState;
use Illuminate\Http\Response; use Illuminate\Http\Response;
use App\Models\Server; use App\Models\Server;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
@ -36,16 +37,16 @@ class ServerInstallController extends Controller
// Make sure the type of failure is accurate // Make sure the type of failure is accurate
if (!$request->boolean('successful')) { if (!$request->boolean('successful')) {
$status = Server::STATUS_INSTALL_FAILED; $status = ServerState::InstallFailed;
if ($request->boolean('reinstall')) { if ($request->boolean('reinstall')) {
$status = Server::STATUS_REINSTALL_FAILED; $status = ServerState::ReinstallFailed;
} }
} }
// Keep the server suspended if it's already suspended // Keep the server suspended if it's already suspended
if ($server->status === Server::STATUS_SUSPENDED) { if ($server->status === ServerState::Suspended) {
$status = Server::STATUS_SUSPENDED; $status = ServerState::Suspended;
} }
$previouslyInstalledAt = $server->installed_at; $previouslyInstalledAt = $server->installed_at;

View File

@ -2,6 +2,7 @@
namespace App\Models; namespace App\Models;
use App\Enums\ServerState;
use App\Exceptions\Http\Connection\DaemonConnectionException; use App\Exceptions\Http\Connection\DaemonConnectionException;
use GuzzleHttp\Exception\GuzzleException; use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Notifications\Notifiable; use Illuminate\Notifications\Notifiable;
@ -112,12 +113,6 @@ class Server extends Model
*/ */
public const RESOURCE_NAME = 'server'; public const RESOURCE_NAME = 'server';
public const STATUS_INSTALLING = 'installing';
public const STATUS_INSTALL_FAILED = 'install_failed';
public const STATUS_REINSTALL_FAILED = 'reinstall_failed';
public const STATUS_SUSPENDED = 'suspended';
public const STATUS_RESTORING_BACKUP = 'restoring_backup';
/** /**
* The table associated with the model. * The table associated with the model.
*/ */
@ -128,7 +123,7 @@ class Server extends Model
* on server instances unless the user specifies otherwise in the request. * on server instances unless the user specifies otherwise in the request.
*/ */
protected $attributes = [ protected $attributes = [
'status' => self::STATUS_INSTALLING, 'status' => ServerState::Installing,
'oom_disabled' => true, 'oom_disabled' => true,
'installed_at' => null, 'installed_at' => null,
]; ];
@ -171,6 +166,7 @@ class Server extends Model
{ {
return [ return [
'node_id' => 'integer', 'node_id' => 'integer',
'status' => ServerState::class,
'skip_scripts' => 'boolean', 'skip_scripts' => 'boolean',
'owner_id' => 'integer', 'owner_id' => 'integer',
'memory' => 'integer', 'memory' => 'integer',
@ -203,12 +199,12 @@ class Server extends Model
public function isInstalled(): bool public function isInstalled(): bool
{ {
return $this->status !== self::STATUS_INSTALLING && $this->status !== self::STATUS_INSTALL_FAILED; return $this->status !== ServerState::Installing && $this->status !== ServerState::InstallFailed;
} }
public function isSuspended(): bool public function isSuspended(): bool
{ {
return $this->status === self::STATUS_SUSPENDED; return $this->status === ServerState::Suspended;
} }
/** /**
@ -359,7 +355,7 @@ class Server extends Model
$this->isSuspended() || $this->isSuspended() ||
$this->node->isUnderMaintenance() || $this->node->isUnderMaintenance() ||
!$this->isInstalled() || !$this->isInstalled() ||
$this->status === self::STATUS_RESTORING_BACKUP || $this->status === ServerState::RestoringBackup ||
!is_null($this->transfer) !is_null($this->transfer)
) { ) {
throw new ServerStateConflictException($this); throw new ServerStateConflictException($this);
@ -376,7 +372,7 @@ class Server extends Model
{ {
if ( if (
!$this->isInstalled() || !$this->isInstalled() ||
$this->status === self::STATUS_RESTORING_BACKUP || $this->status === ServerState::RestoringBackup ||
!is_null($this->transfer) !is_null($this->transfer)
) { ) {
throw new ServerStateConflictException($this); throw new ServerStateConflictException($this);

View File

@ -2,6 +2,7 @@
namespace App\Services\Servers; namespace App\Services\Servers;
use App\Enums\ServerState;
use App\Models\Server; use App\Models\Server;
use Illuminate\Database\ConnectionInterface; use Illuminate\Database\ConnectionInterface;
use App\Repositories\Daemon\DaemonServerRepository; use App\Repositories\Daemon\DaemonServerRepository;
@ -25,7 +26,7 @@ class ReinstallServerService
public function handle(Server $server): Server public function handle(Server $server): Server
{ {
return $this->connection->transaction(function () use ($server) { return $this->connection->transaction(function () use ($server) {
$server->fill(['status' => Server::STATUS_INSTALLING])->save(); $server->fill(['status' => ServerState::Installing])->save();
$this->daemonServerRepository->setServer($server)->reinstall(); $this->daemonServerRepository->setServer($server)->reinstall();

View File

@ -2,6 +2,7 @@
namespace App\Services\Servers; namespace App\Services\Servers;
use App\Enums\ServerState;
use App\Models\ServerVariable; use App\Models\ServerVariable;
use Ramsey\Uuid\Uuid; use Ramsey\Uuid\Uuid;
use Illuminate\Support\Arr; use Illuminate\Support\Arr;
@ -132,7 +133,7 @@ class ServerCreationService
'node_id' => Arr::get($data, 'node_id'), 'node_id' => Arr::get($data, 'node_id'),
'name' => Arr::get($data, 'name'), 'name' => Arr::get($data, 'name'),
'description' => Arr::get($data, 'description') ?? '', 'description' => Arr::get($data, 'description') ?? '',
'status' => Server::STATUS_INSTALLING, 'status' => ServerState::Installing,
'skip_scripts' => Arr::get($data, 'skip_scripts') ?? isset($data['skip_scripts']), 'skip_scripts' => Arr::get($data, 'skip_scripts') ?? isset($data['skip_scripts']),
'owner_id' => Arr::get($data, 'owner_id'), 'owner_id' => Arr::get($data, 'owner_id'),
'memory' => Arr::get($data, 'memory'), 'memory' => Arr::get($data, 'memory'),

View File

@ -2,6 +2,7 @@
namespace App\Services\Servers; namespace App\Services\Servers;
use App\Enums\ServerState;
use Webmozart\Assert\Assert; use Webmozart\Assert\Assert;
use App\Models\Server; use App\Models\Server;
use App\Repositories\Daemon\DaemonServerRepository; use App\Repositories\Daemon\DaemonServerRepository;
@ -44,7 +45,7 @@ class SuspensionService
// Update the server's suspension status. // Update the server's suspension status.
$server->update([ $server->update([
'status' => $isSuspending ? Server::STATUS_SUSPENDED : null, 'status' => $isSuspending ? ServerState::Suspended : null,
]); ]);
try { try {
@ -53,7 +54,7 @@ class SuspensionService
} catch (\Exception $exception) { } catch (\Exception $exception) {
// Rollback the server's suspension status if daemon fails to sync the server. // Rollback the server's suspension status if daemon fails to sync the server.
$server->update([ $server->update([
'status' => $isSuspending ? null : Server::STATUS_SUSPENDED, 'status' => $isSuspending ? null : ServerState::Suspended,
]); ]);
throw $exception; throw $exception;
} }

View File

@ -2,6 +2,7 @@
namespace App\Tests\Integration\Api\Client\Server; namespace App\Tests\Integration\Api\Client\Server;
use App\Enums\ServerState;
use Illuminate\Http\Response; use Illuminate\Http\Response;
use App\Models\Server; use App\Models\Server;
use App\Models\Permission; use App\Models\Permission;
@ -93,7 +94,7 @@ class SettingsControllerTest extends ClientApiIntegrationTestCase
->assertStatus(Response::HTTP_ACCEPTED); ->assertStatus(Response::HTTP_ACCEPTED);
$server = $server->refresh(); $server = $server->refresh();
$this->assertSame(Server::STATUS_INSTALLING, $server->status); $this->assertSame(ServerState::Installing, $server->status);
} }
/** /**

View File

@ -2,6 +2,7 @@
namespace App\Tests\Integration\Api\Remote; namespace App\Tests\Integration\Api\Remote;
use App\Enums\ServerState;
use App\Models\Node; use App\Models\Node;
use App\Models\User; use App\Models\User;
use App\Models\Server; use App\Models\Server;
@ -207,9 +208,9 @@ class SftpAuthenticationControllerTest extends IntegrationTestCase
public static function serverStateDataProvider(): array public static function serverStateDataProvider(): array
{ {
return [ return [
'installing' => [Server::STATUS_INSTALLING], 'installing' => [ServerState::Installing->value],
'suspended' => [Server::STATUS_SUSPENDED], 'suspended' => [ServerState::Suspended->value],
'restoring a backup' => [Server::STATUS_RESTORING_BACKUP], 'restoring a backup' => [ServerState::RestoringBackup->value],
]; ];
} }

View File

@ -2,6 +2,7 @@
namespace App\Tests\Integration\Jobs\Schedule; namespace App\Tests\Integration\Jobs\Schedule;
use App\Enums\ServerState;
use Carbon\Carbon; use Carbon\Carbon;
use Carbon\CarbonImmutable; use Carbon\CarbonImmutable;
use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Request;
@ -151,7 +152,7 @@ class RunTaskJobTest extends IntegrationTestCase
public function testTaskIsNotRunIfServerIsSuspended(): void public function testTaskIsNotRunIfServerIsSuspended(): void
{ {
$server = $this->createServerModel([ $server = $this->createServerModel([
'status' => Server::STATUS_SUSPENDED, 'status' => ServerState::Suspended,
]); ]);
$schedule = Schedule::factory()->for($server)->create([ $schedule = Schedule::factory()->for($server)->create([

View File

@ -2,8 +2,8 @@
namespace App\Tests\Integration\Services\Servers; namespace App\Tests\Integration\Services\Servers;
use App\Enums\ServerState;
use Mockery\MockInterface; use Mockery\MockInterface;
use App\Models\Server;
use App\Services\Servers\SuspensionService; use App\Services\Servers\SuspensionService;
use App\Tests\Integration\IntegrationTestCase; use App\Tests\Integration\IntegrationTestCase;
use App\Repositories\Daemon\DaemonServerRepository; use App\Repositories\Daemon\DaemonServerRepository;
@ -47,7 +47,7 @@ class SuspensionServiceTest extends IntegrationTestCase
$server->refresh(); $server->refresh();
$this->assertFalse($server->isSuspended()); $this->assertFalse($server->isSuspended());
$server->update(['status' => Server::STATUS_SUSPENDED]); $server->update(['status' => ServerState::Suspended]);
$this->getService()->toggle($server); $this->getService()->toggle($server);
$server->refresh(); $server->refresh();