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
10 changes: 7 additions & 3 deletions lib/Http/Client/LoggingClientService.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,13 @@ public function newClient(?callable $handler = null): IClient {
/** @var \GuzzleHttp\Client $guzzle */
$guzzle = $ref->getValue($client);

$handler = $guzzle->getConfig('handler');
if ($handler instanceof \GuzzleHttp\HandlerStack) {
$handler->unshift(
$stack = $guzzle->getConfig('handler');
if ($stack instanceof \GuzzleHttp\HandlerStack) {
// Idempotent: replace an already injected entry instead of
// stacking a second one (double decoration would silently
// duplicate every log entry).
$stack->remove('admin_audit_http_client');
$stack->unshift(
new HttpClientLoggerMiddleware(
$this->logger,
$this->resolveLogDir(),
Expand Down
9 changes: 7 additions & 2 deletions lib/Http/Client/Middleware/HttpClientLoggerMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -129,8 +129,13 @@ function (ResponseInterface $response) use ($request, $reqHeaders, $reqId) {

// Content-Length: 0 — no body
if (!$immediate) {
$compact = $this->compactHeaders($respHeaders);
$cl = $compact['content-length'] ?? $compact['Content-Length'] ?? null;
$cl = null;
foreach ($meta['responseHeaders'] as $k => $v) {
if (strtolower((string)$k) === 'content-length') {
$cl = is_array($v) ? ($v[0] ?? null) : $v;
break;
}
}
if ($cl !== null && is_numeric($cl) && (int)$cl === 0) {
$immediate = true;
}
Expand Down
21 changes: 13 additions & 8 deletions lib/Http/Client/Middleware/LogPathHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,20 @@ public static function getPathsFromMeta(array $meta, string $baseDir, ?string $r
}
}

if ($host === null && !empty($meta['requestHeaders']['Host'])) {
$hostHeader = $meta['requestHeaders']['Host'];
$hostHeader = is_array($hostHeader) ? ($hostHeader[0] ?? '') : (string)$hostHeader;
if ($hostHeader !== '') {
if (strpos($hostHeader, ':') !== false) {
[$host, $port] = explode(':', $hostHeader, 2) + [1 => null];
} else {
$host = $hostHeader;
if ($host === null && !empty($meta['requestHeaders']) && is_array($meta['requestHeaders'])) {
foreach ($meta['requestHeaders'] as $name => $value) {
if (strtolower((string)$name) !== 'host') {
continue;
}
$hostHeader = is_array($value) ? ($value[0] ?? '') : (string)$value;
if ($hostHeader !== '') {
if (strpos($hostHeader, ':') !== false) {
[$host, $port] = explode(':', $hostHeader, 2) + [1 => null];
} else {
$host = $hostHeader;
}
}
break;
}
}

Expand Down
4 changes: 3 additions & 1 deletion tests/integration/MiddlewareInjectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,9 @@ public function testMiddlewareIsInjectedIntoHandlerStack(): void {

$stackRef = new \ReflectionProperty(HandlerStack::class, 'stack');
$names = array_column($stackRef->getValue($handler), 1);
$this->assertContains('admin_audit_http_client', $names);
// This service decorates the already decorated container service, so
// without the idempotency guard the entry would appear twice here.
$this->assertCount(1, array_keys($names, 'admin_audit_http_client', true));
}

public function testEnabledAppDecoratesClientService(): void {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,32 @@ public function testGeneratedRequestIdCarriesServerRequestIdPrefix(): void {
$this->assertStringStartsWith('server-req-', (string)$seen);
}

public function testMixedCaseContentLengthZeroLogsImmediately(): void {
$dir = sys_get_temp_dir() . '/aahc-cl-' . bin2hex(random_bytes(4));
$mw = new HttpClientLoggerMiddleware(new NullLogger(), $dir);

$handler = $mw(function (Request $request, array $options) {
return new FulfilledPromise(new Response(200, ['Content-length' => '0'], ''));
});

try {
$response = $handler(new Request('GET', 'https://example.com/ping'), [])->wait();

$this->assertNotInstanceOf(CountingStream::class, $response->getBody());

$lines = file($dir . '/example.com.json', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$this->assertNotFalse($lines);
$entry = json_decode($lines[0], true, 512, JSON_THROW_ON_ERROR);
$this->assertSame(200, $entry['status']);
$this->assertNull($entry['compressionStats']['decompressed_bytes']);
} finally {
foreach (glob($dir . '/*') ?: [] as $file) {
@unlink($file);
}
@rmdir($dir);
}
}

public function testWriteImmediateOmitsDecompressedBytesAndRatio(): void {
$dir = sys_get_temp_dir() . '/aahc-wi-' . bin2hex(random_bytes(4));
$mw = new HttpClientLoggerMiddleware(new NullLogger(), $dir);
Expand Down
8 changes: 8 additions & 0 deletions tests/unit/Http/Client/Middleware/LogPathHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,14 @@ public function testHostHeaderFallbackWithPort(): void {
$this->assertSame($this->baseDir . '/foo.bar_8080.json', $json);
}

public function testHostHeaderFallbackIsCaseInsensitive(): void {
[$json] = LogPathHelper::getPathsFromMeta(
['requestHeaders' => ['host' => 'foo.bar:8080']],
$this->baseDir,
);
$this->assertSame($this->baseDir . '/foo.bar_8080.json', $json);
}

public function testHostHeaderFallbackAcceptsArrayValues(): void {
[$json] = LogPathHelper::getPathsFromMeta(
['requestHeaders' => ['Host' => ['foo.bar']]],
Expand Down
Loading