-
-
Notifications
You must be signed in to change notification settings - Fork 190
/
Copy pathMiddleware.php
287 lines (240 loc) · 8.86 KB
/
Middleware.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
<?php
namespace Sentry\Laravel\Tracing;
use Closure;
use Illuminate\Http\Request;
use Laravel\Lumen\Application as LumenApplication;
use Sentry\SentrySdk;
use Sentry\State\HubInterface;
use Sentry\Tracing\Span;
use Sentry\Tracing\SpanContext;
use Sentry\Tracing\TransactionSource;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
use function Sentry\continueTrace;
/**
* @internal
*/
class Middleware
{
/**
* The current active transaction.
*
* @var \Sentry\Tracing\Transaction|null
*/
protected $transaction;
/**
* The span for the `app.handle` part of the application.
*
* @var \Sentry\Tracing\Span|null
*/
protected $appSpan;
/**
* The timestamp of application bootstrap completion.
*
* @var float|null
*/
private $bootedTimestamp;
/**
* Whether we should continue tracing after the response has been sent to the client.
*
* @var bool
*/
private $continueAfterResponse;
/**
* Whether a defined route was matched in the application.
*
* @var bool
*/
private $didRouteMatch = false;
/**
* Construct the Sentry tracing middleware.
*/
public function __construct(bool $continueAfterResponse = true)
{
$this->continueAfterResponse = $continueAfterResponse;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
if (app()->bound(HubInterface::class)) {
$this->startTransaction($request, app(HubInterface::class));
}
return $next($request);
}
/**
* Handle the application termination.
*
* @param \Illuminate\Http\Request $request
* @param mixed $response
*
* @return void
*/
public function terminate(Request $request, $response): void
{
// If there is no transaction or the HubInterface is not bound in the container there is nothing for us to do
if ($this->transaction === null || !app()->bound(HubInterface::class)) {
return;
}
if ($this->shouldRouteBeIgnored($request)) {
return;
}
if ($this->appSpan !== null) {
$this->appSpan->finish();
$this->appSpan = null;
}
if ($response instanceof SymfonyResponse) {
$this->hydrateResponseData($response);
}
if ($this->continueAfterResponse) {
// Resolving the transaction finisher class will register the terminating callback
// which is responsible for calling `finishTransaction`. We have registered the
// class as a singleton to keep the state in the container and away from here
// this way we ensure the callback is only registered once even for Octane.
app(TransactionFinisher::class);
} else {
$this->finishTransaction();
}
}
/**
* Set the timestamp of application bootstrap completion.
*
* @param float|null $timestamp The unix timestamp of the booted event, default to `microtime(true)` if not `null`.
*
* @return void
*
* @internal This method should only be invoked right after the application has finished "booting".
*/
public function setBootedTimestamp(?float $timestamp = null): void
{
$this->bootedTimestamp = $timestamp ?? microtime(true);
}
private function startTransaction(Request $request, HubInterface $sentry): void
{
// Prevent starting a new transaction if we are already in a transaction
if ($sentry->getTransaction() !== null) {
return;
}
// Reset our internal state in case we are handling multiple requests (e.g. in Octane)
$this->didRouteMatch = false;
// Try $_SERVER['REQUEST_TIME_FLOAT'] then LARAVEL_START and fallback to microtime(true) if neither are defined
$requestStartTime = $request->server(
'REQUEST_TIME_FLOAT',
defined('LARAVEL_START')
? LARAVEL_START
: microtime(true)
);
$context = continueTrace(
$request->header('sentry-trace') ?? $request->header('traceparent', ''),
$request->header('baggage', '')
);
$requestPath = '/' . ltrim($request->path(), '/');
$context->setOp('http.server');
$context->setName($requestPath);
$context->setOrigin('auto.http.server');
$context->setSource(TransactionSource::url());
$context->setStartTimestamp($requestStartTime);
$context->setData([
'url' => $requestPath,
'http.request.method' => strtoupper($request->method()),
]);
$transaction = $sentry->startTransaction($context);
SentrySdk::getCurrentHub()->setSpan($transaction);
// If this transaction is not sampled, we can stop here to prevent doing work for nothing
if (!$transaction->getSampled()) {
return;
}
$this->transaction = $transaction;
$bootstrapSpan = $this->addAppBootstrapSpan();
$this->appSpan = $this->transaction->startChild(
SpanContext::make()
->setOp('middleware.handle')
->setOrigin('auto.http.server')
->setStartTimestamp($bootstrapSpan ? $bootstrapSpan->getEndTimestamp() : microtime(true))
);
SentrySdk::getCurrentHub()->setSpan($this->appSpan);
}
private function addAppBootstrapSpan(): ?Span
{
if ($this->bootedTimestamp === null) {
return null;
}
$span = $this->transaction->startChild(
SpanContext::make()
->setOp('app.bootstrap')
->setOrigin('auto.http.server')
->setStartTimestamp($this->transaction->getStartTimestamp())
->setEndTimestamp($this->bootedTimestamp)
);
// Add more information about the bootstrap section if possible
$this->addBootDetailTimeSpans($span);
// Consume the booted timestamp, because we don't want to report the boot(strap) spans more than once
$this->bootedTimestamp = null;
return $span;
}
private function addBootDetailTimeSpans(Span $bootstrap): void
{
// This constant should be defined right after the composer `autoload.php` require statement in `public/index.php`
// define('SENTRY_AUTOLOAD', microtime(true));
if (!defined('SENTRY_AUTOLOAD') || !SENTRY_AUTOLOAD) {
return;
}
$bootstrap->startChild(
SpanContext::make()
->setOp('app.php.autoload')
->setOrigin('auto.http.server')
->setStartTimestamp($this->transaction->getStartTimestamp())
->setEndTimestamp(SENTRY_AUTOLOAD)
);
}
private function hydrateResponseData(SymfonyResponse $response): void
{
$this->transaction->setHttpStatus($response->getStatusCode());
$this->transaction->setData([
'http.response.status_code' => $response->getStatusCode(),
]);
}
public function finishTransaction(): void
{
// We could end up multiple times here since we register a terminating callback so
// double check if we have a transaction before trying to finish it since it could
// have already been finished in between being registered and being executed again
if ($this->transaction === null) {
return;
}
// Make sure we set the transaction and not have a child span in the Sentry SDK
// If the transaction is not on the scope during finish, the trace.context is wrong
SentrySdk::getCurrentHub()->setSpan($this->transaction);
$this->transaction->finish();
$this->transaction = null;
}
private function internalSignalRouteWasMatched(): void
{
$this->didRouteMatch = true;
}
/**
* Indicates if the route should be ignored and the transaction discarded.
*/
private function shouldRouteBeIgnored(Request $request): bool
{
// Laravel Lumen doesn't use `illuminate/routing`.
// Instead we use the route available on the request to detect if a route was matched.
if (app() instanceof LumenApplication) {
return $request->route() === null && config('sentry.tracing.missing_routes', false) === false;
}
// If a route has not been matched we ignore unless we are configured to trace missing routes
return !$this->didRouteMatch && config('sentry.tracing.missing_routes', false) === false;
}
public static function signalRouteWasMatched(): void
{
if (!app()->bound(self::class)) {
return;
}
app(self::class)->internalSignalRouteWasMatched();
}
}