refactor(core): enhance SDK structure and documentation
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
This commit is contained in:
32
src/Http/Middleware/RequestIdMiddleware.php
Normal file
32
src/Http/Middleware/RequestIdMiddleware.php
Normal file
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
/*
|
||||
// MODULE_CONTRACT: Provides a Saloon middleware to ensure each API request includes a unique `X-Request-ID` header.
|
||||
// RESPONSIBILITY: To automatically generate and attach a UUID-based `X-Request-ID` header to outgoing API requests if one is not already present, thereby facilitating request tracking, idempotency, and debugging across distributed systems.
|
||||
// INPUTS: Saloon `PendingRequest` object.
|
||||
// OUTPUTS: Modified `PendingRequest` with an `X-Request-ID` header.
|
||||
// LINKS: Core/AlfaBankConnector.php, Sbp/SbpConnector.php, README.md#request-tracking
|
||||
*/
|
||||
|
||||
namespace Apoloz\AlfaBank\Http\Middleware;
|
||||
|
||||
// <SECTION name="module_imports" intent="Import necessary classes for Saloon PendingRequest.">
|
||||
// <BELIEF_STATE "These imports are critical for the middleware's operation. `PendingRequest` from Saloon represents the request being prepared for dispatch, allowing modification before sending.">
|
||||
use Apoloz\AlfaBank\Utils\Uuid;
|
||||
use Saloon\Http\PendingRequest;
|
||||
// </SECTION>
|
||||
|
||||
// <SECTION name="class_definition" intent="Define the Request ID generation middleware.">
|
||||
// <BELIEF_STATE "The `RequestIdMiddleware` is a lightweight yet crucial component for API observability and idempotency. It ensures that every outgoing request is uniquely identifiable through an `X-Request-ID` header. This is invaluable for tracing requests through complex microservice architectures, debugging issues, and preventing duplicate processing on the server-side, adhering to best practices for API communication.">
|
||||
class RequestIdMiddleware
|
||||
{
|
||||
// <SECTION name="invoke_method" intent="Add a unique X-Request-ID header to the pending request.">
|
||||
// <BELIEF_STATE "The `__invoke` method is executed for each outgoing API request. It first checks if an `X-Request-ID` header already exists. If not, it generates a new unique ID and adds it to the request headers. This conditional logic ensures that existing IDs are respected while guaranteeing that every request has a unique identifier, making request tracking reliable and automatic.">
|
||||
public function __invoke(PendingRequest $pendingRequest): void
|
||||
{
|
||||
if (!$pendingRequest->headers()->get('X-Request-ID')) {
|
||||
$pendingRequest->headers()->add('X-Request-ID', Uuid::v4());
|
||||
}
|
||||
}
|
||||
// </SECTION>
|
||||
}
|
||||
// </SECTION>
|
||||
Reference in New Issue
Block a user