feat(previews): implement soft delete and cleanup for ApplicationPreview, enhancing resource management in DeleteResourceJob

This commit is contained in:
Andras Bacsai
2025-07-14 21:17:40 +02:00
parent 5bdf2e8481
commit 13f10028db
4 changed files with 129 additions and 39 deletions

View File

@@ -3,6 +3,7 @@
namespace App\Livewire\Project\Application;
use App\Actions\Docker\GetContainersStatus;
use App\Jobs\DeleteResourceJob;
use App\Models\Application;
use App\Models\ApplicationPreview;
use Illuminate\Support\Collection;
@@ -205,48 +206,28 @@ class Previews extends Component
public function delete(int $pull_request_id)
{
try {
$server = $this->application->destination->server;
$preview = ApplicationPreview::where('application_id', $this->application->id)
->where('pull_request_id', $pull_request_id)
->first();
if ($this->application->destination->server->isSwarm()) {
instant_remote_process(["docker stack rm {$this->application->uuid}-{$pull_request_id}"], $server);
} else {
$containers = getCurrentApplicationContainerStatus($server, $this->application->id, $pull_request_id)->toArray();
$this->stopContainers($containers, $server);
if (! $preview) {
$this->dispatch('error', 'Preview not found.');
return;
}
ApplicationPreview::where('application_id', $this->application->id)
->where('pull_request_id', $pull_request_id)
->first()
->delete();
// Soft delete immediately for instant UI feedback
$preview->delete();
$this->application->refresh();
// Dispatch the job for async cleanup (container stopping + force delete)
DeleteResourceJob::dispatch($preview);
// Refresh the application and its previews relationship to reflect the soft delete
$this->application->load('previews');
$this->dispatch('update_links');
$this->dispatch('success', 'Preview deleted.');
$this->dispatch('success', 'Preview deletion started. It may take a few moments to complete.');
} catch (\Throwable $e) {
return handleError($e, $this);
}
}
private function stopContainers(array $containers, $server, int $timeout = 30)
{
if (empty($containers)) {
return;
}
$containerNames = [];
foreach ($containers as $container) {
$containerNames[] = str_replace('/', '', $container['Names']);
}
$containerList = implode(' ', array_map('escapeshellarg', $containerNames));
$commands = [
"docker stop --time=$timeout $containerList",
"docker rm -f $containerList",
];
instant_remote_process(
command: $commands,
server: $server,
throwError: false
);
}
}