Skip to content

Track a multi-step job

Track a multi-step job

use Cbox\Operations\Contracts\Operations;
use Cbox\Operations\DataObjects\{StartOperation, AdvanceStep, CompleteOperation, FailOperation};

class ImportContacts
{
    public function __construct(private Operations $operations) {}

    public function handle(string $fileId): void
    {
        $op = $this->operations->start(new StartOperation(
            kind: 'contact-import',
            targetType: 'file',
            targetId: $fileId,
            steps: ['parse', 'validate', 'persist'],
        ));

        try {
            $this->parse($fileId);    $this->operations->advanceStep(new AdvanceStep($op->id, 'parse'));
            $this->validate($fileId); $this->operations->advanceStep(new AdvanceStep($op->id, 'validate'));
            $this->persist($fileId);  $this->operations->advanceStep(new AdvanceStep($op->id, 'persist'));

            $this->operations->complete(new CompleteOperation($op->id));
        } catch (\Throwable $e) {
            $this->operations->fail(new FailOperation($op->id, $e->getMessage()));
            throw $e;
        }
    }
}

Because every mutation is idempotent, a retried job that already advanced parse simply continues from where it was.