VOOZH about

URL: https://deepwiki.com/hypervel/bus/9.1-batch-repository-interface

⇱ Batch Repository Interface | hypervel/bus | DeepWiki


Loading...
Menu

Batch Repository Interface

This document defines the persistence layer contracts for batch processing. The BatchRepository and PrunableBatchRepository interfaces specify how batch metadata, job counts, and lifecycle state are stored and retrieved. These contracts abstract the underlying storage mechanism, enabling different implementations (database, cache, etc.) while maintaining a consistent API.

For information about the database implementation of these interfaces, see Database Implementation. For details on batch pruning strategies, see Pruning Old Batch Data. For an overview of the batch processing system, see Batch Processing.


Interface Overview

The batch repository system consists of two interface contracts located in the Hypervel\Bus\Contracts namespace:

InterfacePurposeLocation
BatchRepositoryCore persistence operations for batch lifecycle managementsrc/Contracts/BatchRepository.php12
PrunableBatchRepositoryExtends BatchRepository with cleanup operationssrc/Contracts/PrunableBatchRepository.php9

Diagram: Batch Repository Interface Hierarchy

The PrunableBatchRepository extends BatchRepository to add data retention management capabilities. Implementations must provide all methods from both interfaces.

Sources: src/Contracts/BatchRepository.php src/Contracts/PrunableBatchRepository.php


BatchRepository Interface

The BatchRepository interface src/Contracts/BatchRepository.php12 defines the complete contract for batch persistence operations. All methods operate on batch identifiers (integers or strings) and manage batch state throughout the lifecycle.

Retrieval Methods

These methods retrieve existing batch information from storage.

get(int $limit, mixed $before): array

Retrieves a paginated list of batches src/Contracts/BatchRepository.php19

ParameterTypeDescription
$limitintMaximum number of batches to return
$beforemixedCursor for pagination (implementation-specific)
ReturnsBatch[]Array of Batch objects

This method supports pagination by accepting a cursor value in the $before parameter, whose format is implementation-dependent.

find(int|string $batchId): ?Batch

Retrieves information about a specific batch by its identifier src/Contracts/BatchRepository.php24

ParameterTypeDescription
$batchIdint|stringUnique batch identifier
Returns?BatchBatch object if found, null otherwise

Returns null when the batch does not exist in storage.

Sources: src/Contracts/BatchRepository.php14-24

Batch Creation

store(PendingBatch $batch): ?Batch

Persists a new pending batch to storage src/Contracts/BatchRepository.php29

ParameterTypeDescription
$batchPendingBatchConfigured batch ready for persistence
Returns?BatchCreated Batch object, or null on failure

This method is called when PendingBatch::dispatch() or PendingBatch::dispatchAfterResponse() is invoked. The implementation must:

  • Generate a unique batch ID
  • Serialize batch options and callbacks
  • Store initial job counts
  • Return a Batch object representing the persisted batch

Sources: src/Contracts/BatchRepository.php27-29

Job Count Management

These methods atomically update job counts as batch jobs are processed. Atomic operations are critical for correctness in concurrent environments.

incrementTotalJobs(int|string $batchId, int $amount): void

Increases the total number of jobs in a batch src/Contracts/BatchRepository.php34

ParameterTypeDescription
$batchIdint|stringBatch identifier
$amountintNumber of jobs to add

This method is called when jobs are dynamically added to an existing batch via Batch::add().

decrementPendingJobs(int|string $batchId, string $jobId): UpdatedBatchJobCounts

Decrements the pending job count when a job completes successfully src/Contracts/BatchRepository.php39

ParameterTypeDescription
$batchIdint|stringBatch identifier
$jobIdstringUnique job identifier
ReturnsUpdatedBatchJobCountsValue object containing updated counts

The UpdatedBatchJobCounts return value contains the updated pending and failed job counts, allowing the caller to determine batch completion status.

incrementFailedJobs(int|string $batchId, string $jobId): UpdatedBatchJobCounts

Increments the failed job count when a job throws an exception src/Contracts/BatchRepository.php44

ParameterTypeDescription
$batchIdint|stringBatch identifier
$jobIdstringUnique job identifier
ReturnsUpdatedBatchJobCountsValue object containing updated counts

Like decrementPendingJobs, this returns updated counts to enable completion detection.

Sources: src/Contracts/BatchRepository.php31-44


Diagram: Job Count Update Flow During Batch Execution

Sources: src/Contracts/BatchRepository.php31-44

Lifecycle State Management

These methods manage the overall state of a batch as it progresses through its lifecycle.

markAsFinished(int|string $batchId): void

Marks a batch as finished, indicating all jobs have completed src/Contracts/BatchRepository.php49

ParameterTypeDescription
$batchIdint|stringBatch identifier

This method is called when the pending job count reaches zero. The implementation should update the batch's finished_at timestamp and state.

cancel(int|string $batchId): void

Cancels a batch, preventing further job execution src/Contracts/BatchRepository.php54

ParameterTypeDescription
$batchIdint|stringBatch identifier

This method is invoked when Batch::cancel() is called. The implementation should mark the batch as cancelled and update the cancelled_at timestamp.

delete(int|string $batchId): void

Permanently removes a batch from storage src/Contracts/BatchRepository.php59

ParameterTypeDescription
$batchIdint|stringBatch identifier

Unlike cancel(), this completely removes the batch record. This is typically used for cleanup after batch callbacks have executed.

Sources: src/Contracts/BatchRepository.php46-59

Transaction Management

These methods provide transactional consistency for batch operations.

transaction(Closure $callback): mixed

Executes a closure within a storage-specific transaction src/Contracts/BatchRepository.php64

ParameterTypeDescription
$callbackClosureOperation to execute transactionally
ReturnsmixedReturn value of the callback

The implementation must ensure that all operations within the callback either succeed or fail atomically. This is used when batch operations require multiple coordinated updates.

rollBack(): void

Rolls back the last transaction for the connection src/Contracts/BatchRepository.php69

This method provides explicit rollback control, typically used in error handling scenarios.

Sources: src/Contracts/BatchRepository.php61-69


PrunableBatchRepository Interface

The PrunableBatchRepository interface src/Contracts/PrunableBatchRepository.php9 extends BatchRepository with data retention capabilities. Implementations of this interface can clean up old batch records to prevent unbounded storage growth.

prune(DateTimeInterface $before): int

Removes all batch entries older than the specified date src/Contracts/PrunableBatchRepository.php14

ParameterTypeDescription
$beforeDateTimeInterfaceCutoff date for pruning
ReturnsintNumber of batches deleted

This method provides the foundation for maintenance operations. The specific criteria for "older than" (creation time, completion time, etc.) is implementation-defined. See Pruning Old Batch Data for detailed pruning strategies.

Sources: src/Contracts/PrunableBatchRepository.php9-15


Method Categories and Lifecycle Mapping

The following table categorizes BatchRepository methods by their role in the batch lifecycle:

Lifecycle StageMethodsPurpose
Creationstore()Persist new batch to storage
Retrievalget(), find()Query existing batches
Job ProcessingdecrementPendingJobs(), incrementFailedJobs()Update counts as jobs execute
Dynamic ScalingincrementTotalJobs()Add jobs to running batch
CompletionmarkAsFinished()Mark batch as completed
Cancellationcancel()Abort batch execution
Cleanupdelete(), prune()Remove batch data
Consistencytransaction(), rollBack()Ensure atomic operations

Diagram: Batch State Transitions and Associated Repository Methods

Sources: src/Contracts/BatchRepository.php src/Contracts/PrunableBatchRepository.php


Implementation Requirements

Any class implementing BatchRepository must satisfy these contracts:

  1. Atomicity: Count update methods (decrementPendingJobs, incrementFailedJobs, incrementTotalJobs) must execute atomically to prevent race conditions in concurrent environments.

  2. Idempotency: Methods that accept a $jobId parameter should be idempotent for the same job ID, preventing duplicate count updates if called multiple times.

  3. Transaction Support: The transaction() method must provide ACID guarantees appropriate to the storage backend.

  4. Batch ID Flexibility: Methods must accept both integer and string batch IDs to accommodate different identifier schemes.

  5. Null Safety: The find() and store() methods return nullable Batch objects, requiring callers to handle missing or failed batches.


Diagram: Repository Contract Requirements and Implementation Concerns

Sources: src/Contracts/BatchRepository.php src/Contracts/PrunableBatchRepository.php


Integration with Batch Processing System

The repository interfaces integrate with the broader batch processing system at several key points:

  1. Batch Creation: PendingBatch::dispatch() calls store() to persist the batch before dispatching jobs [see Creating and Managing Batches]

  2. Job Execution: The Batchable trait calls count update methods as jobs complete [see Batchable Trait]

  3. Lifecycle Callbacks: The Batch object queries the repository to determine when to fire callbacks (then, catch, finally) [see Batch Callbacks and Lifecycle]

  4. Dependency Injection: The BatchRepository contract is bound in the DI container by ConfigProvider [see Architecture and System Design]

  5. Queue Integration: The Dispatcher uses the repository to associate jobs with their parent batches [see Queue Integration]

Sources: src/Contracts/BatchRepository.php src/Contracts/PrunableBatchRepository.php

Refresh this wiki

On this page