Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 13 additions & 11 deletions app/Callbacks/WatchCallbacks.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@
use App\Callbacks\Input\CallbackRequest;
use App\Callbacks\Resolution\PrivateKeyResolver;
use App\Callbacks\Watching\CallbackWatcherFactory;
use App\Callbacks\Watching\CallbackWatchObserver;
use App\Callbacks\Watching\CallbackWatchRequest;
use App\Quickpay\QuickpayClient;
use Closure;
use Illuminate\Http\Client\Factory;

final readonly class WatchCallbacks
Expand All @@ -17,24 +18,25 @@ public function __construct(
private PrivateKeyResolver $privateKeys,
) {}

/** @param Closure(string, array<string, int|string|null>): void $observer */
public function execute(
QuickpayClient $quickpay,
string $apiKey,
CallbackRequest $request,
int $interval,
int $deliveryAttempts,
Closure $observer,
CallbackWatchObserver $observer,
): void {
$this->watchers->make($quickpay, $this->http)->run(
paymentId: $request->paymentId,
orderId: $request->orderId,
target: $request->target,
apiKey: $apiKey,
privateKey: $this->privateKeys->resolve($quickpay),
interval: $interval,
deliveryAttempts: $deliveryAttempts,
observer: $observer,
new CallbackWatchRequest(
paymentId: $request->paymentId,
orderId: $request->orderId,
target: $request->target,
apiKey: $apiKey,
privateKey: $this->privateKeys->resolve($quickpay),
interval: $interval,
deliveryAttempts: $deliveryAttempts,
),
$observer,
);
}
}
85 changes: 85 additions & 0 deletions app/Callbacks/Watching/AccountWideWatch.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
<?php

namespace App\Callbacks\Watching;

use App\Callbacks\Resolution\PaymentLocator;
use Closure;
use DateTimeImmutable;
use DateTimeZone;
use UnexpectedValueException;

/**
* Watches every payment on the account from an explicit readiness time.
*
* The session becomes ready at the next whole UTC second and forwards only
* operations created at or after it. Each poll scans closed whole-second
* windows that overlap the previous one by a second, so a payment changed at a
* window edge is not missed; already forwarded operations are remembered per
* payment.
*/
final readonly class AccountWideWatch
{
/**
* @param Closure(int): mixed $sleep
* @param Closure(): bool $continue
* @param Closure(): DateTimeImmutable $clock
* @param Closure(DateTimeImmutable): mixed $waitUntil
*/
public function __construct(
private PaymentLocator $locator,
private WatchPoller $poller,
private OperationForwarder $forwarder,
private Closure $sleep,
private Closure $continue,
private Closure $clock,
private Closure $waitUntil,
) {}

public function run(CallbackWatchRequest $request, CallbackWatchObserver $observer): void
{
$readiness = $this->wholeUtcSecond(($this->clock)())->modify('+1 second');
($this->waitUntil)($readiness);
$observer->watchingAllPayments($readiness);
$watermark = $readiness;
$known = [];

while (($this->continue)()) {
($this->sleep)($request->interval);
$windowEnd = $this->wholeUtcSecond(($this->clock)());

if ($windowEnd < $watermark) {
throw new UnexpectedValueException('The callback watcher clock moved before its payment watermark.');
}

$payments = $this->poller->poll(
fn (): array => $this->locator->changedBetween($watermark->modify('-1 second'), $windowEnd),
$request->interval,
$observer,
);
$watermark = $windowEnd;

foreach ($payments as $payment) {
$paymentId = WatchedPayment::id($payment->json);
$new = array_column(array_filter(
WatchedPayment::operations($payment->json),
fn (array $operation): bool => $operation['created_at'] >= $readiness
&& ! isset($known[$paymentId][$operation['id']]),
), 'id');

$this->forwarder->forward($payment, $paymentId, $new, $request, $observer);
$known[$paymentId] = ($known[$paymentId] ?? []) + array_fill_keys($new, true);
}
}
}

private function wholeUtcSecond(DateTimeImmutable $time): DateTimeImmutable
{
$utc = $time->setTimezone(new DateTimeZone('UTC'));

return $utc->setTime(
(int) $utc->format('H'),
(int) $utc->format('i'),
(int) $utc->format('s'),
);
}
}
43 changes: 43 additions & 0 deletions app/Callbacks/Watching/CallbackWatchObserver.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

namespace App\Callbacks\Watching;

use DateTimeImmutable;

/**
* Receives the progress of one watch session.
*
* One method per event keeps every event and its data typed, so a presenter
* cannot miss or misspell one.
*/
interface CallbackWatchObserver
{
/** Account-wide watching forwards operations created at or after $readyAt. */
public function watchingAllPayments(DateTimeImmutable $readyAt): void;

/** The watched order has no payment yet. */
public function waitingForPayment(string $orderId): void;

/** The watched payment exists and its current operations are baselined. */
public function watchingPayment(string $paymentId, int $baselineOperations): void;

/** The watched order created its payment after the session started. */
public function paymentFound(string $paymentId, string $orderId): void;

/** One poll found several new operations on the same payment snapshot. */
public function multipleOperations(int $count): void;

public function deliveryRetrying(
string $paymentId,
string $operationId,
int $attempt,
int $maximumAttempts,
int $delay,
?int $status,
): void;

/** A retryable Quickpay polling failure; $status is null without an HTTP response. */
public function pollingRetrying(?int $status, int $delay): void;

public function delivered(string $paymentId, string $operationId, ?int $status): void;
}
30 changes: 30 additions & 0 deletions app/Callbacks/Watching/CallbackWatchRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

namespace App\Callbacks\Watching;

use App\Callbacks\Delivery\CallbackTarget;

/**
* Describes one foreground watch session: what to watch, where to forward and
* how to sign, poll and retry.
*
* Without a payment ID or order ID the session watches every payment on the
* account.
*/
final readonly class CallbackWatchRequest
{
public function __construct(
public ?string $paymentId,
public ?string $orderId,
public CallbackTarget $target,
public string $apiKey,
public string $privateKey,
public int $interval,
public int $deliveryAttempts,
) {}

public function isAccountWide(): bool
{
return $this->paymentId === null && $this->orderId === null;
}
}
Loading
Loading