PHP code example of rasuvaeff / context

1. Go to this page and download the library: Download rasuvaeff/context library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

rasuvaeff / context example snippets


use Rasuvaeff\Context\Context;

$root = Context::background();                       // never terminates by itself

[$request, $requestController] = $root->withTimeout(3.0);   // seconds
[$step, $stepController] = $request->withCancel();          // cancellable branch
[$capped] = $request->withDeadline($absoluteNs);            // monotonic hrtime() ns

$traced = $request->withValue(RequestId::class, new RequestId('r-42'));
$traced->value(RequestId::class)?->value;                    // 'r-42' (nearest ancestor wins)

$request->assertActive();        // throws ContextCancelledException / ContextExpiredException
$request->isTerminated();        // cancelled or expired
$request->isCancelled();         // explicit cancellation
$request->isExpired();           // deadline passed
$request->remainingMs();         // null without a deadline; >= 1.0 while active, 0.0 once expired

$unsubscribe = $request->onTerminate(static function (TerminationCause $cause): void {
    // release a resource owned by this operation
});

$unsubscribe();                  // the resource was released early: drop the listener
$requestController->cancel($reason);   // $reason becomes the exception's previous

[$jobContext, $jobController] = Context::background()->withTimeout($ttrSeconds);
try {
    foreach ($steps as $step) {
        $jobContext->assertActive();
        $step($jobContext);
    }
    $queue->ack($message);
} catch (ContextExpiredException) {
    $queue->nack($message); // let the queue decide retry/dead-letter
} finally {
    $jobController->cancel();
}

// sender: an HTTP header or a queue message attribute
$headers['X-Request-Timeout-Ms'] = (string) (int) $context->remainingMs();

// receiver: never longer than its own limit
[$context] = Context::background()->withTimeout(min($limitSeconds, $headerMs / 1000));

$clock = new FakeTimeSource();               // your TimeSource returning nowNs()
[$context] = Context::background($clock)->withTimeout(1.0);
$clock->advanceNs(2_000_000_000);
$context->isExpired();                        // true