deadline = microtime( true ) + $seconds; $this->memory_limit = $memory_limit_bytes; } public static function forRequest(): self { return new self( Environment::tickSeconds(), Environment::memoryLimitBytes() ); } /** * Lets the runner offer stages a way to persist job state before the request ends. */ public function onCommit( callable $committer ): void { $this->committer = $committer; } /** * Lets the runner publish progress from inside a tick. It is called from unit(), at most once a second, and * must be cheap: it is how the screen sees a long tick moving instead of a frozen bar. */ public function onHeartbeat( callable $heartbeat ): void { $this->heartbeat = $heartbeat; } /** * Makes the job's current cursor durable right now. Stages whose work is not * idempotent (SQL replay) call this before and after each batch so a crash can * only ever re-run the batch that was in flight. */ public function commit(): void { if ( null !== $this->committer ) { ( $this->committer )(); } } /** * Stages call this after each completed unit of work (a batch, a block, a file). */ public function unit(): void { ++$this->units; if ( null !== $this->heartbeat ) { $now = microtime( true ); if ( $now - $this->last_beat >= 1.0 ) { $this->last_beat = $now; ( $this->heartbeat )(); } } } /** * Always false until one unit has been reported. A request that starts already * short of time or memory must still make progress, otherwise the job would be * ticked forever without advancing. */ public function exhausted(): bool { if ( 0 === $this->units ) { return false; } return microtime( true ) >= $this->deadline || $this->memoryPressure(); } /** * Ends this request's turn: the runner stops looping and the browser comes back after the * stage's delay. Used when a stage must back off rather than do work (another writer is active). */ public function endTick(): void { ++$this->units; $this->deadline = 0.0; } public function remainingSeconds(): float { return max( 0.0, $this->deadline - microtime( true ) ); } public function memoryPressure(): bool { return $this->memory_limit > 0 && memory_get_usage( true ) > $this->memory_limit * 0.75; } }