An open-source, self-hostable PaaS alternative to Vercel, Heroku & Netlify that lets you easily deploy static sites, databases, full-stack applications and 360+ one-click services on your own servers.
PHP coolifydatabasesdeploymentdockerdocker-composeinertiajslaravelmariadbmysqlnextjsnodejsphppostgresredisself-hostedself-hostingserverstatic-sitesveltesvelte5
fix(databases): unblock interrupted imports and prevent double starts
Andras Bacsaia8117f911450
diff --git a/app/Actions/Database/RestartDatabase.php b/app/Actions/Database/RestartDatabase.phpindex f8fef5855c..3bb83e4187 100644--- a/app/Actions/Database/RestartDatabase.php+++ b/app/Actions/Database/RestartDatabase.php@@ -22,6 +22,10 @@ class RestartDatabaseif (! $server->isFunctional()) {return 'Server is not functional';}+ $busyError = StartDatabase::operationInProgressError($database);+ if ($busyError !== null) {+ return $busyError;+ }$prerequisiteError = StartDatabase::prerequisiteError($database);if ($prerequisiteError !== null) {return $prerequisiteError;diff --git a/app/Actions/Database/StartDatabase.php b/app/Actions/Database/StartDatabase.phpindex af2b48e893..6bc06969d2 100644--- a/app/Actions/Database/StartDatabase.php+++ b/app/Actions/Database/StartDatabase.php@@ -35,6 +35,10 @@ class StartDatabaseif (! $server->isFunctional()) {return 'Server is not functional';}+ $busyError = self::operationInProgressError($database);+ if ($busyError !== null) {+ return $busyError;+ }$prerequisiteError = self::prerequisiteError($database);if ($prerequisiteError !== null) {return $prerequisiteError;@@ -83,6 +87,29 @@ class StartDatabasereturn $activity;}+ /**+ * Refuse a second start/restart while a start, restart or import of this database is+ * queued or running. The UI hides Start/Restart in this state; this is the server-side check.+ * Stale start activities do not block and are marked as failed, so the UI stays consistent.+ */+ public static function operationInProgressError(StandaloneRedis|StandalonePostgresql|StandaloneMongodb|StandaloneMysql|StandaloneMariadb|StandaloneKeydb|StandaloneDragonfly|StandaloneClickhouse $database): ?string+ {+ if (blank($database->uuid)) {+ return null;+ }++ $liveOperations = collect([+ ResourceStartActivity::DATABASE_START_OPERATION,+ ResourceStartActivity::DATABASE_IMPORT_OPERATION,+ ])->flatMap(fn (string $operation) => ResourceStartActivity::failStale(+ ResourceStartActivity::active($database->uuid, $operation)+ ));++ return $liveOperations->isNotEmpty() || ResourceStartActivity::latestRunning($database->uuid) !== null+ ? ResourceStartActivity::DATABASE_OPERATION_IN_PROGRESS_MESSAGE+ : null;+ }+/*** Check prerequisites that would make the queued start fail, so the user gets the* error immediately instead of a queued start that can only fail later.diff --git a/app/Actions/Database/StartDatabaseImport.php b/app/Actions/Database/StartDatabaseImport.phpindex 0359bbc2ab..aea98b0045 100644--- a/app/Actions/Database/StartDatabaseImport.php+++ b/app/Actions/Database/StartDatabaseImport.php@@ -2,7 +2,6 @@namespace App\Actions\Database;-use App\Enums\ProcessStatus;use App\Models\S3Storage;use App\Models\Server;use App\Models\ServiceDatabase;@@ -11,6 +10,7 @@ use App\Support\DatabaseBackupFileValidator;use App\Support\DatabaseImport\DatabaseImportCommandBuilder;use App\Support\DatabaseImport\DatabaseImportException;use App\Support\DatabaseImport\DatabaseImportSource;+use App\Support\ResourceStartActivity;use App\Support\ValidationPatterns;use Illuminate\Database\Eloquent\Model;use Illuminate\Support\Facades\Cache;@@ -68,12 +68,8 @@ class StartDatabaseImportprivate function startImport(Model $resource, DatabaseImportSource $source, int $teamId, Server $server, string $container, string $network): Activity{- $active = Activity::query()->where('properties->team_id', $teamId)- ->where('properties->type_uuid', $resource->uuid)- ->where('properties->operation', 'database_import')- ->whereIn('properties->status', [ProcessStatus::QUEUED->value, ProcessStatus::IN_PROGRESS->value])- ->exists();- if ($active) {+ $active = ResourceStartActivity::active($resource->uuid, ResourceStartActivity::DATABASE_IMPORT_OPERATION, $teamId);+ if (ResourceStartActivity::failStale($active)->isNotEmpty()) {throw new DatabaseImportException('A database import is already running.', 409);}@@ -145,11 +141,13 @@ class StartDatabaseImport$commandList[] = 'rm -f '.escapeshellarg($scriptPath);$commandList[] = 'docker exec '.escapeshellarg($container).' sh -c '.escapeshellarg($scriptPath);- $activity = remote_process($commandList, $server, type_uuid: $resource->uuid, model: $resource, callEventOnFinish: 'DatabaseImportFinished', callEventData: $cleanup);- $activity->properties = $activity->properties->merge(['operation' => 'database_import', 'resource_kind' => $resource instanceof ServiceDatabase ? 'service_database' : 'standalone_database', 'operation_uuid' => $operation]);- $activity->save();-- return $activity;+ // The operation properties are set when the activity is created: the CoolifyTask job can+ // load and save the activity before a later update, which would drop them again.+ return remote_process($commandList, $server, type_uuid: $resource->uuid, model: $resource, callEventOnFinish: 'DatabaseImportFinished', callEventData: $cleanup, properties: [+ 'operation' => ResourceStartActivity::DATABASE_IMPORT_OPERATION,+ 'resource_kind' => $resource instanceof ServiceDatabase ? 'service_database' : 'standalone_database',+ 'operation_uuid' => $operation,+ ]);}private function target(Model $resource): arraydiff --git a/app/Console/Commands/Init.php b/app/Console/Commands/Init.phpindex 4f3a808df1..f087002da1 100644--- a/app/Console/Commands/Init.php+++ b/app/Console/Commands/Init.php@@ -110,10 +110,10 @@ class Init extends Command$interruptedStartCount = ResourceStartActivity::failInterrupted();if ($interruptedStartCount > 0) {- echo "Marked {$interruptedStartCount} interrupted database/service starts as failed\n";+ echo "Marked {$interruptedStartCount} interrupted database/service starts and database imports as failed\n";}} catch (\Throwable $e) {- echo "Could not cleanup interrupted database/service starts: {$e->getMessage()}\n";+ echo "Could not cleanup interrupted database/service starts and database imports: {$e->getMessage()}\n";}try {diff --git a/app/Http/Controllers/Api/DatabasesController.php b/app/Http/Controllers/Api/DatabasesController.phpindex 8c3fd410aa..2189a3e08c 100644--- a/app/Http/Controllers/Api/DatabasesController.php+++ b/app/Http/Controllers/Api/DatabasesController.php@@ -3238,6 +3238,10 @@ class DatabasesController extends Controllerresponse: 404,ref: '#/components/responses/404',),+ new OA\Response(+ response: 409,+ description: 'Another start, restart or import of this database is already in progress.',+ ),])]public function action_deploy(Request $request)@@ -3260,6 +3264,9 @@ class DatabasesController extends Controllerif (str($database->status)->contains('running')) {return response()->json(['message' => 'Database is already running.'], 400);}+ if ($busyError = StartDatabase::operationInProgressError($database)) {+ return response()->json(['message' => $busyError], 409);+ }StartDatabase::dispatch($database);auditLog('api.database.started', [@@ -3424,6 +3431,10 @@ class DatabasesController extends Controllerresponse: 404,ref: '#/components/responses/404',),+ new OA\Response(+ response: 409,+ description: 'Another start, restart or import of this database is already in progress.',+ ),])]public function action_restart(Request $request)@@ -3443,6 +3454,9 @@ class DatabasesController extends Controller$this->authorize('manage', $database);+ if ($busyError = StartDatabase::operationInProgressError($database)) {+ return response()->json(['message' => $busyError], 409);+ }RestartDatabase::dispatch($database);auditLog('api.database.restarted', [diff --git a/app/Jobs/DatabaseStartJob.php b/app/Jobs/DatabaseStartJob.phpindex e520c79dfe..3c79d54582 100644--- a/app/Jobs/DatabaseStartJob.php+++ b/app/Jobs/DatabaseStartJob.php@@ -25,9 +25,11 @@ use App\Support\ResourceStartActivity;use Illuminate\Bus\Queueable;use Illuminate\Contracts\Queue\ShouldBeEncrypted;use Illuminate\Contracts\Queue\ShouldQueue;+use Illuminate\Database\Eloquent\Model;use Illuminate\Foundation\Bus\Dispatchable;use Illuminate\Queue\InteractsWithQueue;use Illuminate\Queue\SerializesModels;+use Illuminate\Support\Facades\Cache;use Spatie\Activitylog\Models\Activity;use Throwable;@@ -55,6 +57,60 @@ class DatabaseStartJob implements ShouldBeEncrypted, ShouldQueueabort_unless((int) $database->team()->id === $this->teamId, 403);$activity = Activity::query()->findOrFail($this->activityId);+ if (! $this->isStillRequested($activity, $database->uuid)) {+ event(new DatabaseStatusChanged($this->userId));++ return;+ }++ $lock = Cache::lock(ResourceStartActivity::databaseStartLockKey($database->uuid), ResourceStartActivity::DATABASE_START_LOCK_SECONDS);+ if (! $lock->get()) {+ ResourceStartActivity::markFailed($activity, ResourceStartActivity::ALREADY_STARTING_MESSAGE);+ event(new DatabaseStatusChanged($this->userId));++ return;+ }++ try {+ $this->runStart($database, $activity);+ } finally {+ $lock->release();+ }+ }++ /**+ * A start runs only while its activity is still queued and no newer start of the same+ * database was requested. A start that waited in a busy queue can be treated as stale and+ * replaced by a new one; without this check both would run one after the other.+ */+ private function isStillRequested(Activity $activity, string $databaseUuid): bool+ {+ if (data_get($activity, 'properties.status') !== ProcessStatus::QUEUED->value) {+ return false;+ }++ $newerStartExists = Activity::query()+ ->where('properties->type_uuid', $databaseUuid)+ ->where('properties->operation', ResourceStartActivity::DATABASE_START_OPERATION)+ ->whereIn('properties->status', [+ ProcessStatus::QUEUED->value,+ ProcessStatus::IN_PROGRESS->value,+ ProcessStatus::FINISHED->value,+ ])+ ->where('id', '>', $activity->getKey())+ ->exists();++ if ($newerStartExists) {+ ResourceStartActivity::markFailed($activity, ResourceStartActivity::SUPERSEDED_MESSAGE);++ return false;+ }++ return true;+ }++ private function runStart(Model $database, Activity $activity): void+ {$result = match ($database->getMorphClass()) {StandalonePostgresql::class => StartPostgresql::run($database, $activity),StandaloneRedis::class => StartRedis::run($database, $activity),diff --git a/app/Support/ResourceStartActivity.php b/app/Support/ResourceStartActivity.phpindex e4baaec978..25a75e09e2 100644--- a/app/Support/ResourceStartActivity.php+++ b/app/Support/ResourceStartActivity.php@@ -8,17 +8,20 @@ use Illuminate\Support\Collection;use Spatie\Activitylog\Models\Activity;/**- * State of the activity log rows that track database and service start/restart runs.+ * State of the activity log rows that track database and service start/restart runs+ * and database imports.** A killed worker, a Coolify restart or a lost queue can leave such an activity queued or* in progress forever. Activities that have not progressed for longer than their job can- * possibly run are treated as stale, so they no longer block Start/Restart in the UI.+ * possibly run are treated as stale, so they no longer block Start/Restart/Import.* Command output is saved to the activity as it arrives, so `updated_at` is the heartbeat.*/class ResourceStartActivity{public const DATABASE_START_OPERATION = 'database-start';+ public const DATABASE_IMPORT_OPERATION = 'database_import';+/*** A start that is still waiting in the queue after this long is treated as lost.*/@@ -29,8 +32,34 @@ class ResourceStartActivity*/public const IN_PROGRESS_STALE_AFTER_SECONDS = 900;+ /**+ * A restore can be silent for a long time (for example pg_restore without verbose output),+ * so the output heartbeat is not reliable for imports. The remote restore process is killed+ * after the SSH command timeout, so an import without progress for longer than that plus+ * this margin cannot still be running.+ */+ public const IMPORT_STALE_MARGIN_SECONDS = 1800;++ /**+ * Lower bound for the import limit, also used when the SSH command timeout is disabled (0).+ */+ public const IMPORT_MIN_STALE_AFTER_SECONDS = 7200;++ /**+ * The start lock must not outlive a killed job for long: DatabaseStartJob times out after 600 seconds.+ */+ public const DATABASE_START_LOCK_SECONDS = self::IN_PROGRESS_STALE_AFTER_SECONDS;+public const INTERRUPTED_MESSAGE = 'Interrupted by a Coolify restart.';+ public const STALE_MESSAGE = 'Marked as failed: no progress was recorded for too long.';++ public const SUPERSEDED_MESSAGE = 'Skipped: a newer start of this database was requested.';++ public const ALREADY_STARTING_MESSAGE = 'Skipped: another start of this database is still running.';++ public const DATABASE_OPERATION_IN_PROGRESS_MESSAGE = 'Another start, restart or import of this database is already in progress.';+private const ACTIVE_STATUSES = [ProcessStatus::QUEUED->value,ProcessStatus::IN_PROGRESS->value,@@ -65,13 +94,58 @@ class ResourceStartActivityreturn true;}- $staleAfterSeconds = data_get($activity, 'properties.status') === ProcessStatus::QUEUED->value- ? self::QUEUED_STALE_AFTER_SECONDS- : self::IN_PROGRESS_STALE_AFTER_SECONDS;+ $staleAfterSeconds = match (true) {+ data_get($activity, 'properties.operation') === self::DATABASE_IMPORT_OPERATION => self::importStaleAfterSeconds(),+ data_get($activity, 'properties.status') === ProcessStatus::QUEUED->value => self::QUEUED_STALE_AFTER_SECONDS,+ default => self::IN_PROGRESS_STALE_AFTER_SECONDS,+ };return $lastProgressAt->lte(now()->subSeconds($staleAfterSeconds));}+ public static function importStaleAfterSeconds(): int+ {+ $commandTimeout = (int) config('constants.ssh.command_timeout');++ return max(self::IMPORT_MIN_STALE_AFTER_SECONDS, $commandTimeout + self::IMPORT_STALE_MARGIN_SECONDS);+ }++ public static function databaseStartLockKey(string $databaseUuid): string+ {+ return "database-start:{$databaseUuid}";+ }++ /**+ * Queued or in-progress activities of one operation for a resource, oldest first.+ *+ * @return Collection<int, Activity>+ */+ public static function active(string $typeUuid, string $operation, ?int $teamId = null): Collection+ {+ return Activity::query()+ ->where('properties->type_uuid', $typeUuid)+ ->where('properties->operation', $operation)+ ->whereIn('properties->status', self::ACTIVE_STATUSES)+ ->when($teamId !== null, fn ($query) => $query->where('properties->team_id', $teamId))+ ->orderBy('id')+ ->get();+ }++ /**+ * Fail the stale activities in the list, so the UI and API stop reporting them as running.+ *+ * @param Collection<int, Activity> $activities+ * @return Collection<int, Activity> The activities that are not stale.+ */+ public static function failStale(Collection $activities): Collection+ {+ [$stale, $live] = $activities->partition(fn (Activity $activity): bool => self::isStale($activity));++ $stale->each(fn (Activity $activity) => self::markFailed($activity, self::STALE_MESSAGE));++ return $live->values();+ }+/*** Mark an activity as failed, append the reason to its log and stop log polling.*/@@ -92,8 +166,8 @@ class ResourceStartActivity}/**- * Fail database and service start activities left queued or in progress by a restart.- * Runs during app:init, before any queue worker is started.+ * Fail database starts, database imports and service starts left queued or in progress+ * by a restart. Runs during app:init, before any queue worker is started.*/public static function failInterrupted(): int{@@ -104,7 +178,11 @@ class ResourceStartActivity$serviceUuids = self::existingServiceUuids($activities);$interrupted = $activities->filter(- fn (Activity $activity): bool => data_get($activity, 'properties.operation') === self::DATABASE_START_OPERATION+ fn (Activity $activity): bool => in_array(+ data_get($activity, 'properties.operation'),+ [self::DATABASE_START_OPERATION, self::DATABASE_IMPORT_OPERATION],+ true,+ )|| $serviceUuids->contains(data_get($activity, 'properties.type_uuid')));diff --git a/bootstrap/helpers/remoteProcess.php b/bootstrap/helpers/remoteProcess.phpindex 241368d388..8e767ed484 100644--- a/bootstrap/helpers/remoteProcess.php+++ b/bootstrap/helpers/remoteProcess.php@@ -25,7 +25,8 @@ function remote_process(?Model $model = null,bool $ignore_errors = false,$callEventOnFinish = null,- $callEventData = null+ $callEventData = null,+ array $properties = [],): Activity {$type = $type ?? ActivityTypes::INLINE->value;$command = $command instanceof Collection ? $command->toArray() : $command;@@ -46,6 +47,7 @@ function remote_process(SshMultiplexingHelper::ensureMultiplexedConnection($server);$properties = [+ ...$properties,'server_uuid' => $server->uuid,'command' => $command_string,'type' => $type,diff --git a/tests/Feature/DatabaseStartConcurrencyTest.php b/tests/Feature/DatabaseStartConcurrencyTest.phpnew file mode 100644index 0000000000..3645368e30--- /dev/null+++ b/tests/Feature/DatabaseStartConcurrencyTest.php@@ -0,0 +1,276 @@+<?php++use App\Actions\Database\RestartDatabase;+use App\Actions\Database\StartDatabase;+use App\Actions\Database\StartPostgresql;+use App\Actions\Database\StopDatabase;+use App\Enums\ActivityTypes;+use App\Enums\ProcessStatus;+use App\Events\DatabaseStatusChanged;+use App\Jobs\DatabaseStartJob;+use App\Livewire\Project\Database\Heading;+use App\Models\Environment;+use App\Models\InstanceSettings;+use App\Models\Project;+use App\Models\Server;+use App\Models\StandaloneDocker;+use App\Models\StandalonePostgresql;+use App\Models\Team;+use App\Models\User;+use App\Support\ResourceStartActivity;+use Illuminate\Foundation\Testing\RefreshDatabase;+use Illuminate\Support\Facades\Bus;+use Illuminate\Support\Facades\Cache;+use Illuminate\Support\Facades\Event;+use Illuminate\Support\Facades\Queue;+use Illuminate\Support\Str;+use Livewire\Livewire;+use Spatie\Activitylog\Models\Activity;++uses(RefreshDatabase::class);++beforeEach(function () {+ InstanceSettings::forceCreate(['id' => 0]);+ config()->set('cache.default', 'array');++ $this->team = Team::factory()->create();+ $this->user = User::factory()->create();+ $this->team->members()->attach($this->user, ['role' => 'owner']);+ session(['currentTeam' => $this->team]);+ $this->bearerToken = $this->user->createToken('test-token', ['*'])->plainTextToken;++ $this->server = Server::factory()->create(['team_id' => $this->team->id]);+ $this->server->settings()->update([+ 'is_reachable' => true,+ 'is_usable' => true,+ 'force_disabled' => false,+ ]);+ $this->destination = StandaloneDocker::firstOrCreate(+ ['server_id' => $this->server->id, 'network' => 'coolify'],+ ['uuid' => (string) Str::uuid(), 'name' => 'docker']+ );+ $project = Project::factory()->create(['team_id' => $this->team->id]);+ $environment = Environment::factory()->create(['project_id' => $project->id]);+ $this->database = StandalonePostgresql::create([+ 'uuid' => (string) Str::uuid(),+ 'name' => 'db',+ 'postgres_user' => 'postgres',+ 'postgres_password' => 'password',+ 'postgres_db' => 'db',+ 'image' => 'postgres:17',+ 'status' => 'exited',+ 'environment_id' => $environment->id,+ 'destination_id' => $this->destination->id,+ 'destination_type' => $this->destination->getMorphClass(),+ ]);+});++function concurrentStartActivity(string $databaseUuid, int $teamId, ProcessStatus $status = ProcessStatus::QUEUED, int $minutesSinceLastUpdate = 0): Activity+{+ $activity = activity()+ ->withProperties([+ 'type' => ActivityTypes::INLINE->value,+ 'type_uuid' => $databaseUuid,+ 'status' => $status->value,+ 'team_id' => $teamId,+ 'operation' => ResourceStartActivity::DATABASE_START_OPERATION,+ ])+ ->event(ActivityTypes::INLINE->value)+ ->log('[]');++ Activity::query()->whereKey($activity->id)->update([+ 'created_at' => now()->subMinutes($minutesSinceLastUpdate),+ 'updated_at' => now()->subMinutes($minutesSinceLastUpdate),+ ]);++ return $activity->refresh();+}++function databaseStartActivityCount(string $databaseUuid): int+{+ return Activity::query()+ ->where('properties->type_uuid', $databaseUuid)+ ->where('properties->operation', ResourceStartActivity::DATABASE_START_OPERATION)+ ->count();+}++function databaseStartApiHeaders(string $token): array+{+ return ['Authorization' => 'Bearer '.$token, 'Content-Type' => 'application/json'];+}++describe('start and restart guards', function () {+ it('does not queue a second start from the UI while a start is queued', function () {+ Bus::fake();+ concurrentStartActivity($this->database->uuid, $this->team->id);++ Livewire::actingAs($this->user)->test(Heading::class, ['database' => $this->database])+ ->call('start')+ ->assertDispatched('error', ResourceStartActivity::DATABASE_OPERATION_IN_PROGRESS_MESSAGE);++ Bus::assertNotDispatched(DatabaseStartJob::class);+ expect(databaseStartActivityCount($this->database->uuid))->toBe(1);+ });++ it('does not stop the database on a UI restart while a start is in progress', function () {+ Bus::fake();+ StopDatabase::shouldRun()->never();+ concurrentStartActivity($this->database->uuid, $this->team->id, ProcessStatus::IN_PROGRESS);++ Livewire::actingAs($this->user)->test(Heading::class, ['database' => $this->database])+ ->call('restart')+ ->assertDispatched('error', ResourceStartActivity::DATABASE_OPERATION_IN_PROGRESS_MESSAGE);++ Bus::assertNotDispatched(DatabaseStartJob::class);+ expect(databaseStartActivityCount($this->database->uuid))->toBe(1);+ });++ it('rejects an API start while a start is queued', function () {+ Queue::fake();+ concurrentStartActivity($this->database->uuid, $this->team->id);++ $this->withHeaders(databaseStartApiHeaders($this->bearerToken))+ ->postJson("/api/v1/databases/{$this->database->uuid}/start")+ ->assertStatus(409)+ ->assertJson(['message' => ResourceStartActivity::DATABASE_OPERATION_IN_PROGRESS_MESSAGE]);++ StartDatabase::assertNotPushed();+ });++ it('rejects an API restart while a start is queued', function () {+ Queue::fake();+ concurrentStartActivity($this->database->uuid, $this->team->id);++ $this->withHeaders(databaseStartApiHeaders($this->bearerToken))+ ->postJson("/api/v1/databases/{$this->database->uuid}/restart")+ ->assertStatus(409)+ ->assertJson(['message' => ResourceStartActivity::DATABASE_OPERATION_IN_PROGRESS_MESSAGE]);++ RestartDatabase::assertNotPushed();+ });++ it('still queues an API start when no start is running', function () {+ Queue::fake();+ concurrentStartActivity($this->database->uuid, $this->team->id, ProcessStatus::FINISHED);++ $this->withHeaders(databaseStartApiHeaders($this->bearerToken))+ ->postJson("/api/v1/databases/{$this->database->uuid}/start")+ ->assertOk();++ StartDatabase::assertPushed();+ });++ it('does not reveal a running start of another team database through the API', function () {+ Queue::fake();+ concurrentStartActivity($this->database->uuid, $this->team->id);+ $otherTeam = Team::factory()->create();+ $otherUser = User::factory()->create();+ $otherTeam->members()->attach($otherUser, ['role' => 'owner']);+ session(['currentTeam' => $otherTeam]);+ $otherToken = $otherUser->createToken('other-token', ['*'])->plainTextToken;++ $this->withHeaders(databaseStartApiHeaders($otherToken))+ ->postJson("/api/v1/databases/{$this->database->uuid}/start")+ ->assertNotFound();++ StartDatabase::assertNotPushed();+ });++ it('refuses to queue a second start in the action itself', function () {+ Bus::fake();+ concurrentStartActivity($this->database->uuid, $this->team->id);++ expect(StartDatabase::run($this->database))->toBe(ResourceStartActivity::DATABASE_OPERATION_IN_PROGRESS_MESSAGE);++ Bus::assertNotDispatched(DatabaseStartJob::class);+ expect(databaseStartActivityCount($this->database->uuid))->toBe(1);+ });++ it('does not stop the database when a queued restart action finds a running start', function () {+ Bus::fake();+ StopDatabase::shouldRun()->never();+ concurrentStartActivity($this->database->uuid, $this->team->id, ProcessStatus::IN_PROGRESS);++ expect(RestartDatabase::run($this->database))->toBe(ResourceStartActivity::DATABASE_OPERATION_IN_PROGRESS_MESSAGE);+ });++ it('lets a new start replace a stale queued start and marks the stale one as failed', function () {+ Bus::fake();+ $stale = concurrentStartActivity($this->database->uuid, $this->team->id, minutesSinceLastUpdate: 11);++ expect(StartDatabase::run($this->database))->toBeInstanceOf(Activity::class);++ Bus::assertDispatched(DatabaseStartJob::class);+ $stale->refresh();+ expect(data_get($stale, 'properties.status'))->toBe(ProcessStatus::ERROR->value)+ ->and(data_get($stale, 'properties.error'))->toBe(ResourceStartActivity::STALE_MESSAGE);+ });+});++describe('start job', function () {+ beforeEach(function () {+ Event::fake([DatabaseStatusChanged::class]);+ });++ it('does not run the start commands while another start of the same database holds the lock', function () {+ StartPostgresql::shouldRun()->never();+ $activity = concurrentStartActivity($this->database->uuid, $this->team->id);+ $lock = Cache::lock(ResourceStartActivity::databaseStartLockKey($this->database->uuid), 60);+ expect($lock->get())->toBeTrue();++ try {+ DatabaseStartJob::dispatchSync(StandalonePostgresql::class, $this->database->id, $this->team->id, $activity->id, null);+ } finally {+ $lock->release();+ }++ $activity->refresh();+ expect(data_get($activity, 'properties.status'))->toBe(ProcessStatus::ERROR->value)+ ->and(data_get($activity, 'properties.error'))->toBe(ResourceStartActivity::ALREADY_STARTING_MESSAGE);+ });++ it('holds the start lock while the start commands run and releases it afterwards', function () {+ $activity = concurrentStartActivity($this->database->uuid, $this->team->id);+ $lockKey = ResourceStartActivity::databaseStartLockKey($this->database->uuid);+ $lockWasHeld = null;+ StartPostgresql::shouldRun()->once()->andReturnUsing(function ($database, Activity $activity) use ($lockKey, &$lockWasHeld) {+ $probe = Cache::lock($lockKey, 60);+ $lockWasHeld = ! $probe->get();+ if (! $lockWasHeld) {+ $probe->release();+ }+ $activity->properties = $activity->properties->merge(['status' => ProcessStatus::FINISHED->value]);+ $activity->save();++ return $activity;+ });++ DatabaseStartJob::dispatchSync(StandalonePostgresql::class, $this->database->id, $this->team->id, $activity->id, null);++ expect($lockWasHeld)->toBeTrue();+ $lock = Cache::lock($lockKey, 60);+ expect($lock->get())->toBeTrue();+ $lock->release();+ });++ it('skips a start that a newer start of the same database replaced', function () {+ StartPostgresql::shouldRun()->never();+ $older = concurrentStartActivity($this->database->uuid, $this->team->id, minutesSinceLastUpdate: 20);+ concurrentStartActivity($this->database->uuid, $this->team->id);++ DatabaseStartJob::dispatchSync(StandalonePostgresql::class, $this->database->id, $this->team->id, $older->id, null);++ $older->refresh();+ expect(data_get($older, 'properties.status'))->toBe(ProcessStatus::ERROR->value)+ ->and(data_get($older, 'properties.error'))->toBe(ResourceStartActivity::SUPERSEDED_MESSAGE);+ });++ it('skips a start whose activity is no longer queued', function () {+ StartPostgresql::shouldRun()->never();+ $activity = concurrentStartActivity($this->database->uuid, $this->team->id, ProcessStatus::ERROR);++ DatabaseStartJob::dispatchSync(StandalonePostgresql::class, $this->database->id, $this->team->id, $activity->id, null);++ expect(data_get($activity->refresh(), 'properties.status'))->toBe(ProcessStatus::ERROR->value);+ });+});diff --git a/tests/Feature/StaleStartActivityTest.php b/tests/Feature/StaleStartActivityTest.phpindex 0867fa7187..6560fe0366 100644--- a/tests/Feature/StaleStartActivityTest.php+++ b/tests/Feature/StaleStartActivityTest.php@@ -170,3 +170,32 @@ it('runs the interrupted start cleanup from app:init', function () {expect($source)->toContain('ResourceStartActivity::failInterrupted()');});++it('marks interrupted database imports as failed on startup and leaves other operations alone', function () {+ $queuedImport = startActivity($this->database->uuid, ProcessStatus::QUEUED, 'database_import');+ $runningImport = startActivity((string) Str::uuid(), ProcessStatus::IN_PROGRESS, 'database_import');+ $finishedImport = startActivity($this->database->uuid, ProcessStatus::FINISHED, 'database_import');+ $otherOperation = startActivity($this->database->uuid, ProcessStatus::IN_PROGRESS, 'something-else');++ expect(ResourceStartActivity::failInterrupted())->toBe(2);++ foreach ([$queuedImport, $runningImport] as $activity) {+ $activity->refresh();+ expect(data_get($activity, 'properties.status'))->toBe(ProcessStatus::ERROR->value)+ ->and(data_get($activity, 'properties.error'))->toBe('Interrupted by a Coolify restart.');+ }++ expect(data_get($finishedImport->refresh(), 'properties.status'))->toBe(ProcessStatus::FINISHED->value)+ ->and(data_get($otherOperation->refresh(), 'properties.status'))->toBe(ProcessStatus::IN_PROGRESS->value);+});++it('keeps a long silent import as running with the import limit instead of the start limit', function () {+ $activity = startActivity($this->database->uuid, ProcessStatus::IN_PROGRESS, 'database_import', 30);++ expect(ResourceStartActivity::isStale($activity))->toBeFalse()+ ->and(databaseHeadingFor($this->database)->checkDeployments())->toBeTrue();++ $stale = startActivity($this->database->uuid, ProcessStatus::IN_PROGRESS, 'database_import', intdiv(ResourceStartActivity::importStaleAfterSeconds(), 60) + 1);++ expect(ResourceStartActivity::isStale($stale))->toBeTrue();+});diff --git a/tests/Feature/StartDatabaseImportBackupPreparationTest.php b/tests/Feature/StartDatabaseImportBackupPreparationTest.phpindex 3fa0c42f55..4d301d0a79 100644--- a/tests/Feature/StartDatabaseImportBackupPreparationTest.php+++ b/tests/Feature/StartDatabaseImportBackupPreparationTest.php@@ -12,6 +12,7 @@ use App\Models\StandaloneDocker;use App\Models\StandalonePostgresql;use App\Models\Team;use App\Support\DatabaseImport\DatabaseImportSource;+use App\Support\ResourceStartActivity;use Illuminate\Filesystem\FilesystemAdapter;use Illuminate\Filesystem\FilesystemManager;use Illuminate\Foundation\Testing\RefreshDatabase;@@ -19,6 +20,7 @@ use Illuminate\Support\Facades\Process;use Illuminate\Support\Facades\Queue;use Illuminate\Support\Facades\Storage;use Illuminate\Support\Str;+use Spatie\Activitylog\Models\Activity;uses(RefreshDatabase::class);@@ -157,3 +159,15 @@ test('s3 backups are prepared in the s3 helper and streamed into the database coQueue::assertPushed(CoolifyTask::class, fn (CoolifyTask $job) => ! array_key_exists('serverTmpPath', $job->call_event_data)&& str_starts_with((string) $job->call_event_data['containerName'], 's3-restore-'));});++test('the import activity is created with its operation, before the CoolifyTask job can load it', function () {+ $operationsAtCreation = [];+ Activity::created(function (Activity $activity) use (&$operationsAtCreation) {+ $operationsAtCreation[] = $activity->getExtraProperty('operation');+ });++ importServerBackup($this, '/srv/backups/app.sql', '2d2d20506f73');++ expect($operationsAtCreation)->toBe([ResourceStartActivity::DATABASE_IMPORT_OPERATION]);+ Queue::assertPushed(CoolifyTask::class);+});diff --git a/tests/Feature/StartDatabaseImportConcurrencyTest.php b/tests/Feature/StartDatabaseImportConcurrencyTest.phpindex d7d27a6c8c..bab4f99b83 100644--- a/tests/Feature/StartDatabaseImportConcurrencyTest.php+++ b/tests/Feature/StartDatabaseImportConcurrencyTest.php@@ -11,6 +11,7 @@ use App\Models\StandalonePostgresql;use App\Models\Team;use App\Support\DatabaseImport\DatabaseImportException;use App\Support\DatabaseImport\DatabaseImportSource;+use App\Support\ResourceStartActivity;use Illuminate\Foundation\Testing\RefreshDatabase;use Illuminate\Support\Facades\Cache;use Illuminate\Support\Str;@@ -123,3 +124,70 @@ test('a failed start releases the import lock', function () {$lock->release();}});++function importActivity(string $databaseUuid, int $teamId, ProcessStatus $status, int $minutesSinceLastUpdate = 0): Activity+{+ $activity = Activity::create([+ 'log_name' => 'default',+ 'description' => '[]',+ 'properties' => [+ 'team_id' => $teamId,+ 'type_uuid' => $databaseUuid,+ 'operation' => 'database_import',+ 'status' => $status->value,+ ],+ ]);++ Activity::query()->whereKey($activity->id)->update([+ 'created_at' => now()->subMinutes($minutesSinceLastUpdate),+ 'updated_at' => now()->subMinutes($minutesSinceLastUpdate),+ ]);++ return $activity->refresh();+}++test('an in-progress import that is silent for a long time but within the limit still blocks', function () {+ $minutes = intdiv(ResourceStartActivity::importStaleAfterSeconds(), 60) - 5;+ $activity = importActivity($this->database->uuid, $this->team->id, ProcessStatus::IN_PROGRESS, $minutes);++ expect(fn () => startImport($this->database, $this->team->id))+ ->toThrow(DatabaseImportException::class, 'A database import is already running.');++ expect(data_get($activity->refresh(), 'properties.status'))->toBe(ProcessStatus::IN_PROGRESS->value);+});++test('a stale import does not block a new import and is marked as failed', function (ProcessStatus $status) {+ $minutes = intdiv(ResourceStartActivity::importStaleAfterSeconds(), 60) + 5;+ $stale = importActivity($this->database->uuid, $this->team->id, $status, $minutes);++ // The guard lets the import through, so it fails later on the invalid path instead of with 409.+ expect(fn () => startImport($this->database, $this->team->id))+ ->toThrow(DatabaseImportException::class, 'The server path is invalid.');++ $stale->refresh();+ expect(data_get($stale, 'properties.status'))->toBe(ProcessStatus::ERROR->value)+ ->and(data_get($stale, 'properties.error'))->toBe(ResourceStartActivity::STALE_MESSAGE)+ ->and(data_get($stale, 'properties.exitCode'))->toBe(1);+})->with([+ 'queued' => ProcessStatus::QUEUED,+ 'in progress' => ProcessStatus::IN_PROGRESS,+]);++test('the stale import limit follows a raised SSH command timeout', function () {+ config()->set('constants.ssh.command_timeout', 5 * 3600);++ expect(ResourceStartActivity::importStaleAfterSeconds())->toBeGreaterThan(5 * 3600);+});++test('an import interrupted by a Coolify restart is failed at boot and no longer blocks a new import', function () {+ $interrupted = importActivity($this->database->uuid, $this->team->id, ProcessStatus::IN_PROGRESS);++ expect(ResourceStartActivity::failInterrupted())->toBe(1);++ $interrupted->refresh();+ expect(data_get($interrupted, 'properties.status'))->toBe(ProcessStatus::ERROR->value)+ ->and(data_get($interrupted, 'properties.error'))->toBe(ResourceStartActivity::INTERRUPTED_MESSAGE);++ expect(fn () => startImport($this->database, $this->team->id))+ ->toThrow(DatabaseImportException::class, 'The server path is invalid.');+});