Mark stale imports and exports as failed before creating new ones and fix review findings

- Mark stale imports/exports of the organization as failed when a new one is created, so they do not block until the prune command runs
- Move the stale check into a stale() scope on the Import and Export models
- Remove orderBy(created_at) from chunkById queries in the prune commands, it skipped rows with random UUIDs
- Delete the export file if the export was deleted while it was running
- Extract the error details formatting into ErrorDetailsFormatter
- Add the exports() relation to Organization
This commit is contained in:
Constantin Graf
2026-11-18 18:48:12 +01:00
committed by Constantin Graf
parent b5aa2f7e1a
commit eb1e89a91d
10 changed files with 197 additions and 100 deletions

View File

@@ -4,29 +4,15 @@ declare(strict_types=1);
namespace App\Console\Commands\Export;
use App\Enums\ExportStatus;
use App\Models\Export;
use App\Service\Export\ExportService;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage;
class ExportPruneCommand extends Command
{
/**
* Time in seconds a running export can exceed the job timeout before it is considered stale.
* The queue worker kills the job after the timeout, so this only needs to cover small delays.
*/
private const int RUNNING_STALE_BUFFER_SECONDS = 300;
/**
* Time in seconds a pending export can exceed the job timeout before it is considered stale,
* this covers the time the job waits in the queue.
*/
private const int PENDING_STALE_BUFFER_SECONDS = 3600;
/**
* The name and signature of the console command.
*
@@ -52,21 +38,9 @@ class ExportPruneCommand extends Command
$this->comment('Running in dry-run mode. Nothing will be saved or deleted.');
}
$jobTimeout = (int) config('export.job_timeout');
$runningStaleBefore = Carbon::now()->subSeconds($jobTimeout + self::RUNNING_STALE_BUFFER_SECONDS);
$pendingStaleBefore = Carbon::now()->subSeconds($jobTimeout + self::PENDING_STALE_BUFFER_SECONDS);
$staleExports = 0;
Export::query()
->where(function (Builder $query) use ($runningStaleBefore, $pendingStaleBefore): void {
$query->where(function (Builder $query) use ($runningStaleBefore): void {
$query->where('status', ExportStatus::Running)
->where('started_at', '<', $runningStaleBefore);
})->orWhere(function (Builder $query) use ($pendingStaleBefore): void {
$query->where('status', ExportStatus::Pending)
->where('created_at', '<', $pendingStaleBefore);
});
})
->orderBy('created_at', 'asc')
->stale()
->chunkById(500, function (Collection $exports) use ($dryRun, $exportService, &$staleExports): void {
/** @var Collection<int, Export> $exports */
foreach ($exports as $export) {
@@ -84,7 +58,6 @@ class ExportPruneCommand extends Command
->whereNotNull('file_path')
->whereNotNull('finished_at')
->where('finished_at', '<', $retentionBefore)
->orderBy('created_at', 'asc')
->chunkById(500, function (Collection $exports) use ($dryRun, &$prunedFiles): void {
/** @var Collection<int, Export> $exports */
foreach ($exports as $export) {

View File

@@ -4,31 +4,15 @@ declare(strict_types=1);
namespace App\Console\Commands\Import;
use App\Enums\ImportStatus;
use App\Models\Import;
use App\Service\Import\ImportService;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage;
class ImportPruneCommand extends Command
{
/**
* Time in seconds a running import can exceed the job timeout before it is considered stale.
* The queue worker kills the job after the timeout, so this only needs to cover small delays.
* Note: The job itself can not mark a timed out import as failed, since the timeout handler runs while the
* import transaction is still open and the change is rolled back when the worker is killed.
*/
private const int RUNNING_STALE_BUFFER_SECONDS = 300;
/**
* Time in seconds a pending import can exceed the job timeout before it is considered stale,
* this covers the time the job waits in the queue.
*/
private const int PENDING_STALE_BUFFER_SECONDS = 3600;
/**
* The name and signature of the console command.
*
@@ -54,21 +38,9 @@ class ImportPruneCommand extends Command
$this->comment('Running in dry-run mode. Nothing will be saved or deleted.');
}
$jobTimeout = (int) config('import.job_timeout');
$runningStaleBefore = Carbon::now()->subSeconds($jobTimeout + self::RUNNING_STALE_BUFFER_SECONDS);
$pendingStaleBefore = Carbon::now()->subSeconds($jobTimeout + self::PENDING_STALE_BUFFER_SECONDS);
$staleImports = 0;
Import::query()
->where(function (Builder $query) use ($runningStaleBefore, $pendingStaleBefore): void {
$query->where(function (Builder $query) use ($runningStaleBefore): void {
$query->where('status', ImportStatus::Running)
->where('started_at', '<', $runningStaleBefore);
})->orWhere(function (Builder $query) use ($pendingStaleBefore): void {
$query->where('status', ImportStatus::Pending)
->where('created_at', '<', $pendingStaleBefore);
});
})
->orderBy('created_at', 'asc')
->stale()
->chunkById(500, function (Collection $imports) use ($dryRun, $importService, &$staleImports): void {
/** @var Collection<int, Import> $imports */
foreach ($imports as $import) {
@@ -86,7 +58,6 @@ class ImportPruneCommand extends Command
->whereNotNull('file_path')
->whereNotNull('finished_at')
->where('finished_at', '<', $retentionBefore)
->orderBy('created_at', 'asc')
->chunkById(500, function (Collection $imports) use ($dryRun, &$prunedFiles): void {
/** @var Collection<int, Import> $imports */
foreach ($imports as $import) {

View File

@@ -40,6 +40,16 @@ class Export extends Model
use HasUuids;
/**
* Time in seconds a running export can exceed the job timeout before it is considered stale.
*/
private const int RUNNING_STALE_BUFFER_SECONDS = 300;
/**
* Time in seconds a pending export can exceed the job timeout before it is considered stale.
*/
private const int PENDING_STALE_BUFFER_SECONDS = 3600;
private const int DOWNLOAD_FILENAME_SLUG_MAX_LENGTH = 40;
/**
@@ -108,4 +118,28 @@ class Export extends Model
{
return $builder->whereIn('status', ExportStatus::active());
}
/**
* Active exports that are not finished in time, for example because the worker crashed or the job timed out.
* The buffers cover small delays after the job timeout (running) and the time the job waits in the queue (pending).
*
* @param Builder<Export> $builder
* @return Builder<Export>
*/
public function scopeStale(Builder $builder): Builder
{
$jobTimeout = (int) config('export.job_timeout');
$runningStaleBefore = Carbon::now()->subSeconds($jobTimeout + self::RUNNING_STALE_BUFFER_SECONDS);
$pendingStaleBefore = Carbon::now()->subSeconds($jobTimeout + self::PENDING_STALE_BUFFER_SECONDS);
return $builder->where(function (Builder $query) use ($runningStaleBefore, $pendingStaleBefore): void {
$query->where(function (Builder $query) use ($runningStaleBefore): void {
$query->where('status', ExportStatus::Running)
->where('started_at', '<', $runningStaleBefore);
})->orWhere(function (Builder $query) use ($pendingStaleBefore): void {
$query->where('status', ExportStatus::Pending)
->where('created_at', '<', $pendingStaleBefore);
});
});
}
}

View File

@@ -45,6 +45,18 @@ class Import extends Model
use HasUuids;
/**
* Time in seconds a running import can exceed the job timeout before it is considered stale.
* Note: The job itself can not mark a timed out import as failed, since the timeout handler runs while the
* import transaction is still open and the change is rolled back when the worker is killed.
*/
private const int RUNNING_STALE_BUFFER_SECONDS = 300;
/**
* Time in seconds a pending import can exceed the job timeout before it is considered stale.
*/
private const int PENDING_STALE_BUFFER_SECONDS = 3600;
/**
* The attributes that should be cast.
*
@@ -97,4 +109,28 @@ class Import extends Model
{
return $builder->whereIn('status', ImportStatus::active());
}
/**
* Active imports that are not finished in time, for example because the worker crashed or the job timed out.
* The buffers cover small delays after the job timeout (running) and the time the job waits in the queue (pending).
*
* @param Builder<Import> $builder
* @return Builder<Import>
*/
public function scopeStale(Builder $builder): Builder
{
$jobTimeout = (int) config('import.job_timeout');
$runningStaleBefore = Carbon::now()->subSeconds($jobTimeout + self::RUNNING_STALE_BUFFER_SECONDS);
$pendingStaleBefore = Carbon::now()->subSeconds($jobTimeout + self::PENDING_STALE_BUFFER_SECONDS);
return $builder->where(function (Builder $query) use ($runningStaleBefore, $pendingStaleBefore): void {
$query->where(function (Builder $query) use ($runningStaleBefore): void {
$query->where('status', ImportStatus::Running)
->where('started_at', '<', $runningStaleBefore);
})->orWhere(function (Builder $query) use ($pendingStaleBefore): void {
$query->where('status', ImportStatus::Pending)
->where('created_at', '<', $pendingStaleBefore);
});
});
}
}

View File

@@ -41,6 +41,7 @@ use OwenIt\Auditing\Contracts\Auditable as AuditableContract;
* @property Collection<int, User> $realUsers
* @property-read Collection<int, OrganizationInvitation> $organizationInvitations
* @property-read Collection<int, Import> $imports
* @property-read Collection<int, Export> $exports
* @property Member $membership
* @property NumberFormat $number_format
* @property CurrencyFormat $currency_format
@@ -167,6 +168,14 @@ class Organization extends Model implements AuditableContract
return $this->hasMany(Import::class, 'organization_id');
}
/**
* @return HasMany<Export, $this>
*/
public function exports(): HasMany
{
return $this->hasMany(Export::class, 'organization_id');
}
/**
* Find a model by its primary key or throw an exception.
*

View File

@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace App\Service;
use Illuminate\Support\Str;
use Throwable;
class ErrorDetailsFormatter
{
private const int MAX_LENGTH = 50000;
/**
* Technical details of the exception and all previous exceptions for debugging in the admin panel.
*/
public static function format(Throwable $exception): string
{
$parts = [];
$current = $exception;
while ($current !== null) {
$parts[] = $current::class.': '.$current->getMessage()."\n".
'at '.$current->getFile().':'.$current->getLine()."\n".
$current->getTraceAsString();
$current = $current->getPrevious();
}
return Str::limit(implode("\n\nCaused by: ", $parts), self::MAX_LENGTH);
}
}

View File

@@ -19,6 +19,7 @@ use App\Models\Tag;
use App\Models\Task;
use App\Models\TimeEntry;
use App\Models\User;
use App\Service\ErrorDetailsFormatter;
use Exception;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\UniqueConstraintViolationException;
@@ -39,8 +40,6 @@ class ExportService
{
public const string VERSION = '1.0';
private const int ERROR_DETAILS_MAX_LENGTH = 50000;
/**
* Creates an export of all data of the organization and queues it.
*
@@ -48,6 +47,10 @@ class ExportService
*/
public function createOrganizationExport(Organization $organization, ?User $user): Export
{
// Stale exports would block new exports until the export:prune command runs
Export::query()->whereBelongsTo($organization, 'organization')->stale()->get()
->each(fn (Export $staleExport) => $this->markAsFailed($staleExport, 'Export could not be finished'));
if (Export::query()->whereBelongsTo($organization, 'organization')->active()->exists()) {
throw new ExportAlreadyInProgressApiException;
}
@@ -98,11 +101,19 @@ class ExportService
}
$export->status = ExportStatus::Failed;
$export->error_message = 'Export failed, please try again later or contact support';
$export->error_details = $this->getErrorDetails($exception->getPrevious() ?? $exception);
$export->error_details = ErrorDetailsFormatter::format($exception->getPrevious() ?? $exception);
} finally {
$export->finished_at = Carbon::now();
$export->save();
}
// The export (and its organization) can be deleted while the export is running, the file would be orphaned
if ($export->file_path !== null && ! Export::query()->whereKey($export->getKey())->exists()) {
Log::warning('Deleting file of export that was deleted while it was running', [
'export_id' => $export->getKey(),
]);
Storage::disk(config('filesystems.private'))->delete($export->file_path);
}
}
/**
@@ -116,23 +127,6 @@ class ExportService
$export->save();
}
/**
* Technical details of the exception and all previous exceptions for debugging in the admin panel.
*/
private function getErrorDetails(Throwable $exception): string
{
$parts = [];
$current = $exception;
while ($current !== null) {
$parts[] = $current::class.': '.$current->getMessage()."\n".
'at '.$current->getFile().':'.$current->getLine()."\n".
$current->getTraceAsString();
$current = $current->getPrevious();
}
return Str::limit(implode("\n\nCaused by: ", $parts), self::ERROR_DETAILS_MAX_LENGTH);
}
/**
* Creates the export ZIP file and stores it on the private disk.
*

View File

@@ -10,6 +10,7 @@ use App\Jobs\ProcessImport;
use App\Models\Import;
use App\Models\Organization;
use App\Models\User;
use App\Service\ErrorDetailsFormatter;
use App\Service\Import\Importers\ImporterContract;
use App\Service\Import\Importers\ImporterProvider;
use App\Service\Import\Importers\ImportException;
@@ -19,14 +20,11 @@ use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use LogicException;
use Throwable;
class ImportService
{
private const int ERROR_DETAILS_MAX_LENGTH = 50000;
/**
* Stores the import file and queues the import.
*
@@ -39,6 +37,10 @@ class ImportService
// Throws an InvalidArgumentException if the importer type is unknown
app(ImporterProvider::class)->getImporter($importerType);
// Stale imports would block new imports until the import:prune command runs
Import::query()->whereBelongsTo($organization, 'organization')->stale()->get()
->each(fn (Import $staleImport) => $this->markAsFailed($staleImport, 'Import could not be finished'));
if (Import::query()->whereBelongsTo($organization, 'organization')->active()->exists()) {
throw new ImportException('Import is already in progress');
}
@@ -105,12 +107,12 @@ class ImportService
report($exception);
$import->status = ImportStatus::Failed;
$import->error_message = $exception->getMessage();
$import->error_details = $this->getErrorDetails($exception);
$import->error_details = ErrorDetailsFormatter::format($exception);
} catch (Throwable $exception) {
report($exception);
$import->status = ImportStatus::Failed;
$import->error_message = 'Unexpected error during import';
$import->error_details = $this->getErrorDetails($exception);
$import->error_details = ErrorDetailsFormatter::format($exception);
} finally {
$import->credentials = null;
$import->finished_at = Carbon::now();
@@ -130,23 +132,6 @@ class ImportService
$import->save();
}
/**
* Technical details of the exception and all previous exceptions for debugging in the admin panel.
*/
private function getErrorDetails(Throwable $exception): string
{
$parts = [];
$current = $exception;
while ($current !== null) {
$parts[] = $current::class.': '.$current->getMessage()."\n".
'at '.$current->getFile().':'.$current->getLine()."\n".
$current->getTraceAsString();
$current = $current->getPrevious();
}
return Str::limit(implode("\n\nCaused by: ", $parts), self::ERROR_DETAILS_MAX_LENGTH);
}
/**
* @throws ImportException
*/

View File

@@ -157,6 +157,29 @@ class ExportServiceTest extends TestCaseWithDatabase
Queue::assertPushed(ProcessExport::class, fn (ProcessExport $job): bool => $job->export->is($export));
}
public function test_create_organization_export_marks_stale_export_of_the_organization_as_failed_and_creates_new_export(): void
{
// Arrange
Queue::fake();
$organization = Organization::factory()->create();
$staleExport = Export::factory()->forOrganization($organization)->running()->create([
'started_at' => now()->subHours(3),
]);
$otherStaleExport = Export::factory()->running()->create([
'started_at' => now()->subHours(3),
]);
// Act
$export = app(ExportService::class)->createOrganizationExport($organization, null);
// Assert
$this->assertSame(ExportStatus::Pending, $export->status);
$staleExport->refresh();
$this->assertSame(ExportStatus::Failed, $staleExport->status);
$this->assertSame('Export could not be finished', $staleExport->error_message);
$this->assertSame(ExportStatus::Running, $otherStaleExport->refresh()->status);
}
public function test_database_allows_only_one_active_export_per_organization(): void
{
// Arrange
@@ -190,6 +213,24 @@ class ExportServiceTest extends TestCaseWithDatabase
Storage::disk(config('filesystems.private'))->assertExists($export->file_path);
}
public function test_process_deletes_export_file_if_export_was_deleted_while_running(): void
{
// Arrange
$this->mockPrivateStorage();
$organization = Organization::factory()->create();
$export = Export::factory()->forOrganization($organization)->create();
// Simulates a deletion of the export (for example by the deletion of the organization) while it is running
Export::query()->whereKey($export->getKey())->delete();
// Act
app(ExportService::class)->process($export);
// Assert
$this->assertNotNull($export->file_path);
Storage::disk(config('filesystems.private'))->assertMissing($export->file_path);
$this->assertFalse(Export::query()->whereKey($export->getKey())->exists());
}
public function test_process_marks_export_as_failed_with_error_details_if_export_fails(): void
{
// Arrange

View File

@@ -94,6 +94,30 @@ class ImportServiceTest extends TestCase
$this->assertSame(3, Import::query()->count());
}
public function test_create_file_import_marks_stale_import_of_the_organization_as_failed_and_creates_new_import(): void
{
// Arrange
Queue::fake();
Storage::fake(config('filesystems.private'));
$organization = Organization::factory()->create();
$staleImport = Import::factory()->forOrganization($organization)->running()->create([
'started_at' => now()->subHours(3),
]);
$otherStaleImport = Import::factory()->running()->create([
'started_at' => now()->subHours(3),
]);
// Act
$import = app(ImportService::class)->createFileImport($organization, null, 'toggl_time_entries', 'data', 'Europe/Vienna');
// Assert
$this->assertSame(ImportStatus::Pending, $import->status);
$staleImport->refresh();
$this->assertSame(ImportStatus::Failed, $staleImport->status);
$this->assertSame('Import could not be finished', $staleImport->error_message);
$this->assertSame(ImportStatus::Running, $otherStaleImport->refresh()->status);
}
public function test_create_file_import_throws_exception_if_importer_type_is_unknown(): void
{
// Arrange