Log/Controller/ControlProfiling.pm untested

filter: Statementstmt 0.0% 0 / 113 Branchbran 0.0% 0 / 18 Conditioncond 0.0% 0 / 8 MC/DCmcdc 0.0% 0 / 5 Subroutinesub 0.0% 0 / 14 Podpod 0.0% 0 / 8 totaltotal 0.0% 0 / 166 CC 10 SCAR 20.2
CC
10
Cov
0%
_dbilog_output_dir
12.0
index
12.0
format_path
12.0
CRAP 7.6
1 # ABSTRACT: Control profiling within your application
2 package Catalyst::Plugin::Profile::DBI::Log::Controller::ControlProfiling;
3  
4 our $VERSION = '0.03'; # VERSION (maintained by DZP::OurPkgVersion)
5 #
6 use Moose;
7 use Path::Tiny qw(path);
8 use namespace::autoclean;
9  
10 use File::stat;
11 use HTML::Entities;
12 use JSON;
13  
14 BEGIN { extends 'Catalyst::Controller' }
15
16  
17 # Read the configured output dir, falling back to the default.
18 # The plugin sets this in setup_finalize; we read it from the app config.
19 sub _dbilog_output_dir {
20 my $self = shift;
21 my $c = ref($_[-1]) && $_[-1]->isa('Catalyst::Context') ? pop : undef;
22 my $conf = $c ? $c->config->{'Plugin::Profile::DBI::Log'} : {};
23 return $conf->{dbilog_out_dir} || 'dbilog_output';
24 }
25  
26 sub _css {
27 return <<'CSS';
28 * { box-sizing: border-box; margin: 0; padding: 0; }
29 body {
30 font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
31 background: #f0f2f5;
32 color: #1a1a2e;
33 line-height: 1.6;
34 padding: 2rem;
35 }
36 .container { max-width: 1200px; margin: 0 auto; }
37 h1 {
38 font-size: 1.6rem;
39 font-weight: 700;
40 margin-bottom: 1.5rem;
41 color: #16213e;
42 }
43 a { color: #0066cc; text-decoration: none; }
44 a:hover { text-decoration: underline; }
45 .table-wrap {
46 background: #fff;
47 border-radius: 8px;
48 box-shadow: 0 1px 3px rgba(0,0,0,0.08);
49 overflow-x: auto;
50 }
51 table { width: 100%; border-collapse: collapse; font-size: 0.85rem; }
52 th {
53 background: #e8edf2;
54 font-weight: 600;
55 text-align: left;
56 padding: 0.75rem 1rem;
57 color: #444;
58 border-bottom: 2px solid #d0d7de;
59 white-space: nowrap;
60 }
61 td {
62 padding: 0.6rem 1rem;
63 border-bottom: 1px solid #eef0f3;
64 vertical-align: top;
65 }
66 tr:hover td { background: #f6f8fa; }
67 .method {
68 display: inline-block;
69 padding: 2px 8px;
70 border-radius: 4px;
71 font-weight: 700;
72 font-size: 0.75rem;
73 letter-spacing: 0.5px;
74 }
75 .method-GET { background: #dafbe1; color: #116329; }
76 .method-POST { background: #ddf4ff; color: #0550ae; }
77 .method-PUT { background: #fff8c5; color: #7d5a00; }
78 .method-PATCH { background: #fff1e5; color: #953800; }
79 .method-DELETE { background: #ffebe9; color: #82071e; }
80 .query-path { font-weight: 600; }
81 .query-string {
82 color: #6e7781;
83 cursor: pointer;
84 display: inline-block;
85 max-width: 400px;
86 overflow: hidden;
87 text-overflow: ellipsis;
88 white-space: nowrap;
89 vertical-align: bottom;
90 }
91 .query-string:hover { color: #0066cc; }
92 .stat { font-variant-numeric: tabular-nums; }
93 .view-btn {
94 display: inline-block;
95 padding: 3px 10px;
96 background: #0066cc;
97 color: #fff !important;
98 border-radius: 4px;
99 font-size: 0.8rem;
100 font-weight: 500;
101 }
102 .view-btn:hover { background: #0052a3; text-decoration: none; }
103 .summary-cards {
104 display: flex;
105 flex-direction: column;
106 gap: 0.75rem;
107 margin-bottom: 1.5rem;
108 }
109 .summary-row {
110 display: flex;
111 gap: 0.75rem;
112 }
113 .summary-row > .card:first-child { flex: 3; }
114 .summary-row > .card:last-child { flex: 1; }
115 .card {
116 background: #fff;
117 border-radius: 8px;
118 box-shadow: 0 1px 3px rgba(0,0,0,0.08);
119 padding: 1rem 1.5rem;
120 flex: 1;
121 }
122 .card-label { font-size: 0.75rem; color: #6e7781; text-transform: uppercase; letter-spacing: 0.5px; }
123 .card-value { font-size: 1.4rem; font-weight: 700; color: #16213e; }
124 .query-table td:first-child { max-width: 500px; }
125 .query-table pre {
126 margin: 0;
127 white-space: pre-wrap;
128 word-break: break-word;
129 font-size: 0.8rem;
130 line-height: 1.5;
131 background: #f6f8fa;
132 padding: 0.5rem;
133 border-radius: 4px;
134 }
135 .stack-trace { color: #6e7781; font-size: 0.8rem; }
136 .back-link { display: inline-block; margin-bottom: 1rem; color: #0066cc; }
137 .empty-state {
138 text-align: center;
139 padding: 3rem;
140 color: #6e7781;
141 background: #fff;
142 border-radius: 8px;
143 box-shadow: 0 1px 3px rgba(0,0,0,0.08);
144 }
145 CSS
146 }
147  
148  
149 sub index : Local {
150 my ($self, $c) = @_;
151 my $dbilog_output_dir = $self->_dbilog_output_dir($c);
152 my $css = $self->_css;
153  
154 opendir my $outdir, $dbilog_output_dir
155 or do {
156 $c->response->status(500);
157 $c->response->body("Failed to open $dbilog_output_dir: $!");
158 return;
159 };
160 my @files = grep { $_ !~ /^(\.|html)/ } readdir $outdir;
161  
162 my @rows;
163 file:
164 for my $file (
165 grep {
166 -s path($dbilog_output_dir, $_)
167 } sort {
168 (stat path($dbilog_output_dir, $b))->ctime
169 <=>
170 (stat path($dbilog_output_dir, $a))->ctime
171 } @files
172 ) {
173 my $stats = get_stats(path($dbilog_output_dir, $file));
174 next file unless $stats->{query_count};
175  
176 my $datetime = scalar localtime( (stat path($dbilog_output_dir, $file))->ctime);
177 my $path = format_path($stats->{path_query});
178 my $method = HTML::Entities::encode_entities($stats->{method});
179 my $file_enc = HTML::Entities::encode_entities($file);
180  
181 push @rows, <<ROW;
182 <tr>
183 <td><span class="method method-$method">$method</span></td>
184 <td>$path</td>
185 <td class="stat">@{[ HTML::Entities::encode_entities($stats->{total_query_time}) ]}s</td>
186 <td class="stat">@{[ HTML::Entities::encode_entities($stats->{slowest_query}) ]}s</td>
187 <td class="stat">@{[ HTML::Entities::encode_entities($stats->{query_count}) ]}</td>
188 <td>@{[ HTML::Entities::encode_entities($datetime) ]}</td>
189 <td>@{[ HTML::Entities::encode_entities($stats->{ip}) ]}</td>
190 <td><a href="/dbi/log/show/$file_enc" class="view-btn">View</a></td>
191 </tr>
192 ROW
193 }
194  
195 my $table_body = @rows
196 ? join("\n", @rows)
197 : '<tr><td colspan="8" class="empty-state">No profiled requests found.</td></tr>';
198  
199 my $html = <<"HTML";
200 <!DOCTYPE html>
201 <html lang="en">
202 <head>
203 <meta charset="utf-8">
204 <meta name="viewport" content="width=device-width, initial-scale=1">
205 <title>DBI::Log Profiled Requests</title>
206 <style>$css</style>
207 </head>
208 <body>
209 <div class="container">
210 <h1>DBI::Log &mdash; Profiled Requests</h1>
211 <div class="table-wrap">
212 <table>
213 <thead>
214 <tr>
215 <th>Method</th>
216 <th>Path</th>
217 <th>Total Query Time</th>
218 <th>Slowest Query</th>
219 <th>Queries</th>
220 <th>Datetime</th>
221 <th>IP</th>
222 <th></th>
223 </tr>
224 </thead>
225 <tbody>
226 $table_body
227 </tbody>
228 </table>
229 </div>
230 </div>
231 </body>
232 </html>
233 HTML
234  
235 $c->response->body($html);
236 $c->response->status(200);
237 }
238  
239  
240 # Turn URL path into HTML to display the path part before the query more
241 # prominently, and potentially truncate long query strings.
242 sub format_path {
243 my $in = shift;
244 my ($path, $query) = split /\?/, $in, 2;
245 my $out = qq{<span class="query-path">$path</span>};
246 if ($query) {
247 my $reveal_js;
248 my $title_attr = qq{title="@{[ HTML::Entities::encode_entities($query) ]}"};
249 my $display_query = $query;
250 if (length $query > 100) {
251 $display_query = substr($query, 0, 100) . "...";
252 my $js_safe = $query;
253 $js_safe =~ s{\\}{\\\\}g;
254 $js_safe =~ s{"}{&quot;}g;
255 $js_safe =~ s{\n}{\\n}g;
256 $js_safe =~ s{\r}{\\r}g;
257 $reveal_js = qq{onclick="this.textContent = \\"$js_safe\\"" };
258 }
259 $display_query = HTML::Entities::encode_entities($display_query);
260  
261 $out .= qq{?<span class="query-string" ${reveal_js}${title_attr}>$display_query</span>};
262 }
263 return $out;
264 }
265  
266  
267 sub get_stats {
268 my $file = shift;
269 my @json_lines = path($file)->lines;
270  
271 my %stats;
272 # The file is line-delimited JSON, where each line is a separate
273 # JSON object, so we need to read each line as JSON separately.
274 # The first line is our metadata describing the HTTP request which was
275 # being processed.
276 my $metadata_json = shift @json_lines;
277 %stats = %{ JSON::from_json($metadata_json) };
278  
279 for my $line (@json_lines) {
280 my $line_data = JSON::from_json($line);
281 $stats{query_count}++;
282 $stats{total_query_time} += $line_data->{time_taken};
283 $stats{slowest_query} = $line_data->{time_taken}
284 if $line_data->{time_taken} > $stats{slowest_query};
285 }
286 return \%stats;
287
288 }
289  
290 sub show :Local Args(1) {
291 my ($self, $c, $profile) = @_;
292 my $dbilog_output_dir = $self->_dbilog_output_dir($c);
293  
294 # Guard against path traversal attempts
295 if ($profile =~ m{(\.\.|/|\\)}) {
296 $c->response->status(400);
297 $c->response->body("Invalid profile name");
298 return;
299 }
300  
301 my (undef, $path) = split '_', $profile, 4;
302  
303 my $profile_path = Path::Tiny::path(
304 $dbilog_output_dir,
305 $profile
306 );
307 my $datetime = scalar localtime($profile_path->stat->ctime);
308  
309 my $stats = get_stats($profile_path);
310  
311 # It makes sense for GET request URLs to be clickable - not so much for
312 # PUT/POST, so work it out:
313 my $encoded_path_query = HTML::Entities::encode_entities($stats->{path_query});
314 my $path_maybe_link = $stats->{method} eq 'GET'
315 ? qq{<a href="$encoded_path_query">$encoded_path_query</a>}
316 : $encoded_path_query;
317  
318 my $method = HTML::Entities::encode_entities($stats->{method});
319 my $css = $self->_css;
320  
321 my @query_rows;
322 for my $json_line ($profile_path->lines) {
323 my $data = JSON::from_json($json_line);
324  
325 my $first_frame = (
326 grep {
327 $_->{file} !~ m{(DBIx/Class|Try/Tiny|Context/Preserve)}
328 } @{ $data->{stack} }
329 )[-1];
330  
331 my $stack_summarised = sprintf "%s @ %s L%d",
332 @$first_frame{qw(sub file line)};
333  
334 push @query_rows, <<ROW;
335 <tr>
336 <td><pre class="query">@{[ HTML::Entities::encode_entities($data->{query}) ]}</pre></td>
337 <td class="stat">@{[ HTML::Entities::encode_entities($data->{time_taken}) ]}</td>
338 <td class="stack-trace">@{[ HTML::Entities::encode_entities($stack_summarised) ]}</td>
339 </tr>
340 ROW
341 }
342  
343 my $query_count = scalar @query_rows;
344  
345 my $html = <<"HTML";
346 <!DOCTYPE html>
347 <html lang="en">
348 <head>
349 <meta charset="utf-8">
350 <meta name="viewport" content="width=device-width, initial-scale=1">
351 <title>DBI::Log &mdash; $method $path</title>
352 <style>$css</style>
353 <script src="https://unpkg.com/jquery\@3.7.1/dist/jquery.min.js"></script>
354 <script src="https://unpkg.com/sql-formatter\@2.6.3/dist/sql-formatter.min.js"></script>
355 </head>
356 <body>
357 <div class="container">
358 <a href="/dbi/log/index" class="back-link">&larr; Back to all requests</a>
359 <h1>DBI::Log &mdash; Request Detail</h1>
360  
361 <div class="summary-cards">
362 <div class="summary-row">
363 <div class="card">
364 <div class="card-label">Request</div>
365 <div class="card-value"><span class="method method-$method">$method</span> $path_maybe_link</div>
366 </div>
367 <div class="card">
368 <div class="card-label">Recorded</div>
369 <div class="card-value" style="font-size:1rem">@{[ HTML::Entities::encode_entities($datetime) ]}</div>
370 </div>
371 </div>
372 <div class="summary-row">
373 <div class="card">
374 <div class="card-label">Total DB Time</div>
375 <div class="card-value">@{[ HTML::Entities::encode_entities($stats->{total_query_time}) ]}s</div>
376 </div>
377 <div class="card">
378 <div class="card-label">Queries</div>
379 <div class="card-value">$query_count</div>
380 </div>
381 </div>
382 </div>
383  
384 <div class="table-wrap">
385 <table class="query-table">
386 <thead>
387 <tr>
388 <th>Query</th>
389 <th>Took</th>
390 <th>Stack</th>
391 </tr>
392 </thead>
393 <tbody>
394 @{[ join("\n", @query_rows) ]}
395 </tbody>
396 </table>
397 </div>
398 </div>
399  
400 <script>
401 \$('.query').each(function (i) {
402 let formatted = sqlFormatter.format(\$(this).text(), { language: 'postgresql' });
403 \$(this).text( formatted );
404 });
405 </script>
406 </body>
407 </html>
408 HTML
409  
410 $c->response->body($html);
411  
412  
413 }
414  
415 sub generate_stack_trace_html {
416 my $stack_data = shift;
417  
418 my $html = <<STACKTRACETABLESTART;
419  
420 <h2>Stack trace</h2>
421  
422 <table class="query-table">
423 <thead>
424 <tr>
425 <th>File</th>
426 <th>Line</th>
427 <th>Sub</th>
428 </tr>
429 </thead>
430 <tbody>
431 STACKTRACETABLESTART
432  
433 for my $frame (@{ $stack_data }) {
434 $html .= <<STACKROW;
435 <tr>
436 <td>@{[ HTML::Entities::encode_entities($frame->{file}) ]}</td>
437 <td class="stat">@{[ HTML::Entities::encode_entities($frame->{line}) ]}</td>
438 <td class="stack-trace">@{[ HTML::Entities::encode_entities($frame->{sub}) ]}</td>
439 </tr>
440 STACKROW
441 }
442  
443 $html .= "</tbody></table>";
444  
445 return $html;
446 }
447  
448  
449 1;
450  
451 =head1 NAME
452  
453 Catalyst::Plugin::Profile::DBI::Log::Controller::ControlProfiling
454  
455 =head1 DESCRIPTION
456  
457 Provides the route handlers to list profiled HTTP requests, and
458 inspect the DB queries they executed.
459  
460 See the base L<Catalyst::Plugin::Profile::DBI::Log> documentation for
461 more details.
462  
463 =head1 AUTHOR
464  
465 David Precious (BIGPRESH) C<< <davidp@preshweb.co.uk> >>
466  
467 =head1 COPYRIGHT AND LICENCE
468  
469 Copyright (C) 2024 by David Precious
470  
471 This library is free software; you can redistribute it and/or modify it
472 under the same terms as Perl itself.
473  
474 =cut
475  
476  
477 __END__