Skip to content

Commit

Permalink
fix(otel): do not wait for exit handlers to send responses
Browse files Browse the repository at this point in the history
  • Loading branch information
lf- committed May 5, 2023
1 parent c3c5dc1 commit 7ab5a4e
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 5 deletions.
19 changes: 18 additions & 1 deletion app/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,21 @@
\app\security\oauth\modules\OAuthHandlerModule::register(new \app\security\oauth\modules\GoogleOAuthHandler());
\app\security\oauth\modules\OAuthHandlerModule::register(new \app\security\oauth\modules\SlackOAuthHandler());

\vhs\web\HttpContext::Server()->handle();
try {
\vhs\web\HttpContext::Server()->handle();
} catch (\vhs\RequestFinished $e) {
} finally {
/*
* This is here to fix a problem where exit-handlers need to finish dealing
* with a request e.g. by sending traces to an OpenTelemetry service, and
* that may take between a few ms and a while, which we should never make
* the client wait for.
*
* https://stackoverflow.com/questions/15273570/continue-processing-php-after-sending-http-response
*/
session_write_close();
fastcgi_finish_request();
// Ensure that the root span of the server is always closed cleanly.
\vhs\web\HttpContext::Server()->endRootSpan();
exit();
}
10 changes: 10 additions & 0 deletions vhs/RequestFinished.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace vhs;

/**
* Finishes processing the request and stops the HTTP server cleanly.
*/
class RequestFinished extends \Exception
{
}
9 changes: 5 additions & 4 deletions vhs/web/HttpServer.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,10 @@ private function beginRootSpan(): void {
* Ends the root span for a request. Expected to be called unconditionally
* at the end of a request's lifecycle (if not, the trace will most likely
* be shown as missing a root span).
*
* Called by the RequestFinished exception handler.
*/
private function endRootSpan(): void {
public function endRootSpan(): void {
if ($this->root_span) {
$this->root_span->end();
}
Expand Down Expand Up @@ -167,8 +169,7 @@ private function endResponse() {
}
}

$this->endRootSpan();
exit();
throw new \vhs\RequestFinished();
}

public function clear() {
Expand Down Expand Up @@ -217,7 +218,7 @@ public function sendOnlyHeaders() {

$self = $this;
array_push($this->headerBuffer, function() use ($self) {
exit();
throw new \vhs\RequestFinished();
});
}

Expand Down

0 comments on commit 7ab5a4e

Please sign in to comment.