blib/lib/Database/BI.pm

filter: Statementstmt 88.6% 482 / 544 Branchbran 63.3% 195 / 308 Conditioncond 56.7% 220 / 388 MC/DCmcdc 35.8% 71 / 198 Subroutinesub 98.2% 57 / 58 Podpod 100% 1 / 1 totaltotal 68.5% 1026 / 1497 CC 308 SCAR 33.0
CC
308
Cov
72%
_frame_origin
72.0
_check_url_private_hosts
63.3
_check_allowed_hosts
63.3
CRAP 27.2
« blib/lib/Database/BI/Model/DataSource.pm ↑ Summary blib/lib/Database/BI/CacheDir.pm »
1 package Database::BI;
2  
3 12 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 12 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 12 ▶use Mojo::Base 'Mojolicious', -strict, -signatures;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 12 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 12 ▶use Mojo::File ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 12 ▶use Mojo::URL;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 12 ▶use Database::BI::I18N ();
Subroutine BEGIN: called CC=1 SCAR=0.0
12 12 ▶use Database::BI::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 12 ▶use Database::BI::Sessions;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 12 ▶use CHI ();
Subroutine BEGIN: called CC=1 SCAR=0.0
15 12 ▶use File::Spec ();
Subroutine BEGIN: called CC=1 SCAR=0.0
16 12 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18 12 ▶use Database::BI::Model::DataSource;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 12 ▶use Database::BI::Tutorial;
Subroutine BEGIN: called CC=1 SCAR=0.0
20  
21 # version->declare here alone: this is VERSION_FROM, and with it MakeMaker
22 # writes 0.024.0 into META; a plain dotted string becomes v0.024.0 there.
23 12 ▶use version; our $VERSION = version->declare('0.024.0');
Subroutine BEGIN: called CC=1 SCAR=0.0
24  
25 # The roadmap after 0.021.0, from its gap analysis (2026-11-06).
26 #
27 # Features:
28 # TODO: More JSON: JSON Lines (.jsonl, .ndjson); optional dot-path flattening
29 # of nested objects (address.city) instead of JSON text; reading a large
30 # file as a stream rather than all at once.
31 # TODO: Ranges for historical data: windows anchored to the data rather than
32 # to today ("the first decade in the data"), and decade and century span=
33 # buckets for year columns.
34 # TODO: Multi-sheet XLSX: ?sheet= and a sheet picker, through the /tables
35 # cards that JSON and SQLite use.
36 # TODO: A better Print: a heading naming the view's filters and range, a
37 # "print the rows shown" mode, and a server-side PDF for views too large
38 # for the browser to lay out (Print asks first past 10,000 rows).
39 # TODO: Encoding on upload: detect Windows-1252 (a BOM is read past since
40 # 0.021.0) and say which encoding was used.
41 # TODO: Alerts in the app: a canvas panel to set bi-alert's thresholds and
42 # see recent alerts, so they do not need cron.
43 # TODO: More databases: PostgreSQL through Database::Join::Catalog, as MariaDB
44 # is, and a columnar backend (DuckDB or Parquet) for files too large for
45 # SQLite extracts.
46 #
47 # Technical debt:
48 # TODO: Dashboard.pm is over 15,000 lines. Split it by area (charts, canvas,
49 # model stores, export and access, geo) into controllers of their own;
50 # the routes stay here.
51 # TODO: One validated filter representation. f= is split in _filter_request,
52 # _apply_filter_spec, _filter_specs_to_criteria, _fetch_page and the
53 # canvas, each with its own rules; parse it once into a typed form at the
54 # boundary.
55 # TODO: One date reader. _is_iso_date, _to_iso_date, _date_key,
56 # _time_columns, Calc::date_normalise and the browser's biDetectColType
57 # each recognise dates differently (the browser takes DD-Mon-YYYY, the
58 # server's filter does not). Share one definition.
59 # TODO: Move dashboard.html.tt's inline script into static files (allowed by
60 # script-src 'self') so it can be unit-tested, not only run in Playwright.
61 # TODO: Loading Dashboard.pm during the compile phase runs Sub::Protected's
62 # CHECK, which alone turned the SQL path's sums into JSON strings
63 # (t/time-bucket.t). The server never loads it that way; find which
64 # protected sub is responsible.
65 # TODO: Async work: long joins and geocoding block a worker. Use
66 # Mojo::IOLoop->subprocess, or the server-sent-events streaming, for
67 # progress and free workers.
68 # TODO: Generated CI: the Windows cpanm retry, and the cache that never fills
69 # on Windows (installs go into Perl's own site folder), belong in App::GHGen's
70 # template, not in perl-ci.yml, which it overwrites.
71  
72 # Default config values used by the Config plugin and referenced explicitly
73 # in startup() so callers always get a resolved value.
74 12 Readonly my $DEFAULT_DATA_DIR => 'data';
75 12 Readonly my $DEFAULT_PLATFORM => 'web';
76 12 Readonly my $DEFAULT_LANGUAGE => 'en';
77 12 Readonly my $DEFAULT_CACHE_TTL_URL => '15 min';
78  
79 # The browser-side chart library is fetched from a CDN unless the deployment
80 # self-hosts it. This is the pinned version the pages were tested with; the
81 # URL is a config seam (d3_url), and the Leaflet assets have their own keys
82 # (leaflet_*_url), so an offline installation can point them at its own copies.
83 12 Readonly my $DEFAULT_D3_URL => 'https://cdnjs.cloudflare.com/ajax/libs/d3/7.9.0/d3.min.js';
84  
85 # Where HTML::OSM fetches Leaflet and its tiles when the config names no
86 # other. Only their origins matter: they go into the Content-Security-Policy.
87 12 Readonly my $DEFAULT_LEAFLET_URL => 'https://unpkg.com/';
88 12 Readonly my $DEFAULT_TILE_URL => 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
89  
90 # How long a login lasts after the last request: a working day.
91 12 Readonly my $DEFAULT_LOGIN_EXPIRATION => 8 * 60 * 60;
92  
93 # Where a server started without -l or MOJO_LISTEN listens: this machine only.
94 # Config listen (morbo, daemon, prefork) and hypnotoad => { listen } (hypnotoad)
95 # change the port, or open it to other machines with 'http://*:3000'.
96 12 Readonly my $DEFAULT_LISTEN => 'http://127.0.0.1:3000';
97 12 Readonly my $DEFAULT_HYPNOTOAD_LISTEN => 'http://127.0.0.1:8080';
98  
99 # What a Content-Security-Policy nonce may be made of (base64 or base64url);
100 # anything else reaching the policy is dropped.
101 12 Readonly my $NONCE_RE => qr{\A[A-Za-z0-9+/_=-]+\z};
102  
103 # The Referer a page sends: the whole URL to this site, only the origin to
104 # another, and nothing from https to http. Specs, filter values and share
105 # tokens travel in the query string, and an older browser's default sends all
106 # of it to the CDNs, the tile servers and any site a reader follows a link to.
107 # OpenStreetMap's tile policy asks pages for a Referer, so it is not none.
108 12 Readonly my $REFERRER_POLICY => 'strict-origin-when-cross-origin';
109  
110 # Permissions-Policy: every powerful browser feature off, for this site and
111 # any frame it holds, but writing to the clipboard, which the Copy link
112 # buttons do. Only names Chromium knows: it logs an error for any other.
113 12 Readonly my @PERMISSIONS_DENIED => qw(
114 accelerometer autoplay browsing-topics camera clipboard-read display-capture
115 encrypted-media fullscreen gamepad geolocation gyroscope hid
116 identity-credentials-get idle-detection local-fonts magnetometer microphone
117 midi otp-credentials payment picture-in-picture publickey-credentials-create
118 publickey-credentials-get screen-wake-lock serial storage-access usb
119 window-management xr-spatial-tracking
120 );
121 Readonly my $DEFAULT_PERMISSIONS_POLICY =>
122 12 join(', ', (map { "$_=()" } @PERMISSIONS_DENIED), 'clipboard-write=(self)');
123  
124 # Cross-Origin-Opener-Policy for a page: a window another site opened, or a
125 # window a page opens on another site, gets no handle on the page. No page
126 # opens a window or reads window.opener; links out are rel="noopener" anyway.
127 12 Readonly my $DEFAULT_COOP => 'same-origin';
128 12 Readonly my %COOP_VALUES => map { $_ => 1 } qw(same-origin same-origin-allow-popups noopener-allow-popups unsafe-none);
129  
130 # Strict-Transport-Security, sent on replies to https requests: a year, and
131 # this host only. includeSubDomains and preload reach other sites of the same
132 # domain, and are hard to take back, so they are for the configuration to add.
133 12 Readonly my $DEFAULT_HSTS => 'max-age=31536000';
134 12 Readonly my $HSTS_RE => qr{\Amax-age=\d{1,10}(?:\s*;\s*includeSubDomains)?(?:\s*;\s*preload)?\z}i;
135  
136 # Transport-layer upload size cap (bytes). Mojolicious enforces this before
137 # the request body is read into memory, so an oversized upload never reaches
138 # the controller. Must match $MAX_UPLOAD_BYTES in Dashboard.pm.
139 12 Readonly my $MAX_REQUEST_SIZE => 50 * 1_048_576; # 50 MiB
140 12 Readonly my $UPLOAD_MAX_AGE_S => 24 * 3600; # evict uploads older than 24 h
141  
142 # CHI drivers that keep the table cache on disc, and so need a directory.
143 12 Readonly my %DISC_CACHE_DRIVER => map { ($_ => 1) } qw(File FastMmap);
144  
145 =head1 NAME
146  
147 Database::BI - Web-based Business Intelligence viewer for data files
148  
149 =head1 VERSION
150  
151 0.024.0
152  
153 =head1 DESCRIPTION
154  
155 C<Database::BI> is a self-contained L<Mojolicious> web application that reads
156 and views arbitrary data (CSV, PSV, TSV, SQLite, JSON, XML, XLSX, etc.)
157 and presents them as styled, sortable, reorderable
158 HTML tables.
159 It has no persistent database of its own,
160 it reads your files on every request.
161  
162 Users navigate to pick a file, open the filesystem browser to navigate anywhere
163 on disc, drag-and-drop files to upload, join multiple tables in memory, apply
164 server-side filters, and export results as CSV, SQLite, JSON, or XLSX. Nine
165 D3.js v7 chart types, a pivot/crosstab table, per-column statistics, and
166 multi-visual saved canvases are available from the toolbar.
167  
168 A tutorial in plain English is built into the application at C</tutorial>.
169 It is written for people who do not know Perl, and it is the place to start.
170  
171 Key features:
172  
173 =over 4
174  
175 =item *
176  
177 B<File picker> -- the home page scans C<data_dir> and shows a card for
178 every supported file. Recently opened filesystem files appear in a
179 "Recently opened" section powered by C<localStorage>.
180  
181 =item *
182  
183 B<Filesystem browser> -- C</browse> lets the user navigate the entire
184 filesystem and open any supported data file, not just files in C<data_dir>.
185 A folder with two or more data files has a checkbox beside each (and Select
186 all; shift-click ticks a range), and Combine selected opens the ticked files
187 as one table, as the Combine data panel does. A folder of reports of one
188 format, such as a DMARC archive, is one click, and the table has a
189 C<source_file> column that names the file each row came from.
190  
191 =item *
192  
193 B<Column sort and reorder> -- clicking a header sorts the table; headers
194 are draggable to reorder. Both settings are persisted in C<localStorage>
195 by column name and survive page reloads. A table too long for one page is
196 sorted by the server (C<sort=> and C<dir=> in the address), every row of it,
197 so page 1 is the start of the sorted table and Next goes on from there.
198 A column sorts as dates when every cell is one, as numbers when every cell
199 is one (C<$1,234>, C<(5)> and C<45%> are numbers; C<T27> is not), and
200 otherwise as text, with case and accents ignored and the digits in it
201 compared as numbers, so C<T3> comes before C<T27>.
202  
203 =item *
204  
205 B<Left join> -- the "Merge data" panel on any table view lets the user
206 join one or more additional tables on a shared key via L<Database::Join>.
207 Every left row is kept; right-table columns are appended for matching rows.
208 Multiple joins can be chained.
209  
210 =item *
211  
212 B<Quick-filter bar> -- a column/operator/value row below the toolbar lets
213 the user add filter conditions without opening any panel. Pressing Enter
214 applies the filter. Each active filter chip has an individual remove (x)
215 button so conditions can be dropped one at a time. Operators: C<eq>,
216 C<ne>, C<contains>, C<starts>, C<lt>, C<le>, C<gt>, C<ge>, C<between>, C<empty>,
217 C<notempty>; and C<in>, which a link can carry but the bar does not offer: any
218 value of a JSON list, as in C<f=place:in:["Paris","Rome"]>, and C<differ>,
219 which the Delta button adds (see below). Filters are
220 applied server-side after all joins. C<lt>, C<le>,
221 C<gt> and C<ge> compare numbers, reading C<$1,234.56> and C<(1,234.56)> as
222 numbers too; a blank or a word in the cell matches none of them.
223 An operator that is none of these (operators are lower case) is a C<400> that
224 lists them, and so is a filter, or a time range's C<rcol=>, on a column the
225 view does not have (the message lists the columns): neither is taken as a
226 filter that keeps every row, or none. A canvas card's own saved filters are
227 the exception: one on a column its dataset no longer has is ignored.
228  
229 =item *
230  
231 B<Combine (UNION ALL)> -- the "Combine data" panel stacks rows from a
232 second (or further) file beneath the current rows, using a unified column
233 set and leaving blanks where a source file lacks a column.
234  
235 =item *
236  
237 B<Delta> -- the "Delta" button, to the right of Combine data, asks for two
238 columns and removes every row where they are identical, so only the rows
239 where they differ are left. It adds the filter C<f=first:differ:second> to the
240 view, so the table, charts, pivot, export and print all show the same rows,
241 and the chip can be removed like any other filter. "Identical" means the same
242 text: C<Ann> and C<ann>, or C<10> and C<10.0>, differ. An empty cell
243 is identical to another empty cell, so a row where both are empty is removed. Both columns must be in the view, or the request
244 is a C<400>. The names of the two columns must not contain a colon.
245  
246 =item *
247  
248 B<Charts> -- nine L<HTML::D3> D3.js v7 chart types are accessible from
249 the toolbar: line chart (brush-to-zoom, reference lines for min/avg/max and a trend line,
250 multi-series interactive legend), pie chart (click-a-slice to filter,
251 top-N, donut mode, configurable colour scheme), heatmap (two categorical
252 axes, count or sum mode), bar chart (horizontal or vertical, sort,
253 top-N), scatter/bubble plot (optional categorical colour and numeric
254 size dimensions), stacked bar chart, combo bar+line chart, treemap, and
255 histogram (server-side binning, C<?bins=N>). All charts can be resized
256 by dragging the bottom-right corner grip, or from the keyboard: the grip
257 takes focus, the arrow keys resize the chart (Shift takes bigger steps,
258 Home and End go to the narrowest and widest it can be) and the size is announced
259 as it changes. All chart pages include Copy-link and Export SVG/PNG/PDF buttons.
260 In a browser with the File System Access API (Chrome, Edge and other Chromium
261 browsers, on this machine or over https) each export opens the Save As box, so
262 the reader chooses the folder and the file name; the chart's own name is
263 suggested, and cancelling saves nothing. Other browsers download the file under
264 that name into their usual downloads folder. (The Export panel on a table is
265 different: it saves on the server, in C<export_dirs>.)
266  
267 =item *
268  
269 B<Maps> -- C<GET /map> plots the filtered view on an OpenStreetMap map, either
270 from latitude and longitude columns or from a place column geocoded by a
271 L<Geo::Coder::List> chain: L<Geo::Coder::Free>'s local data first, then
272 OpenStreetMap's Nominatim service (L<Geo::Coder::OSM>, at most one request a
273 second) for the places the local data does not know. Nominatim is asked over
274 https, and what it finds is also kept for a month in
275 C<E<lt>model_dirE<gt>/geocode-cache/>, or the C<cache_dir> set (see
276 L</Where caches are kept>). Each distinct place is
277 looked up once, remembered in the model store and shared by every dataset that
278 names it. Rows sharing a position become one marker.
279  
280 =item *
281  
282 B<Pivot table> -- the "Pivot table" panel builds a crosstab from any
283 combination of row dimensions, column dimensions, and measures
284 (C<sum|avg|min|max|count|count_distinct|median|stdev|first|last|range>, plus
285 C<pE<lt>NE<gt>> for the Nth percentile). The backend aggregates what it can;
286 the rest are computed in Perl from each group's values, subtotals and grand
287 total included, because a median is not the sum of the medians of its parts.
288 Supports subtotals, HAVING filters, top-N row groups, and direct export to
289 CSV, SQLite, JSON, or XLSX.
290  
291 =item *
292  
293 B<Column statistics> -- the column-stats button runs C<GET /stats>, which
294 returns one row per column: row count, null count, distinct count, first and
295 last, and (for numeric columns) min, max, range, mean, median, a chosen
296 percentile and the sample standard deviation. The arithmetic is the same one
297 the pivot's measures use.
298  
299 =item *
300  
301 B<Calculated fields> -- virtual columns defined by inline C<?c=name:expr>
302 URL params or stored persistently via C<POST /calc/save>. Expressions
303 support arithmetic, comparison, C<IF>, string, numeric, and date
304 functions, plus C<bin(value,width)> for histogram grouping. Calc fields
305 are applied before aggregation on all chart and pivot routes.
306  
307 =item *
308  
309 B<Relative time ranges> -- any data view, chart, pivot or saved canvas can be
310 limited to a named window worked out from today -- the last 24 hours, the last
311 7, 30 or 90 days, this or last month, quarter or year -- instead of typing
312 dates. The window is resolved on every request (C<?range=> with C<?rcol=>),
313 so a bookmark or a canvas still means the same thing tomorrow, and the filter
314 bar disables a window the data cannot answer.
315  
316 =item *
317  
318 B<Saved canvases> -- the "Save as Canvas" panel saves the current data
319 configuration as a named multi-visual canvas (C</a/:id>). Visuals are
320 arranged on a 12-column grid: drag a card by its header to any free cell
321 (the header also takes focus, and the arrow keys move the card a cell at a
322 time, Shift going to the edge), and resize it from the corner handle. A
323 card's width and height can also be set without a drag from the Size menu in
324 its header: full, half, a third or a quarter of the width, and one, two,
325 three or six rows high. The size the card is sits on the card itself, beside
326 that menu, so a width the corner grip left it at reads without the menu being
327 opened. Each move is announced -- the column and row the
328 card landed in, and any card the move pushed down -- and saved as you go. The whole position and size is
329 saved with the canvas, so a card put in row 4 stays in row 4 rather than
330 being packed up the page. B<Add text> in the toolbar adds a card of plain
331 text, for a title or an explanation, with a font, a size in points, colours and
332 an alignment of its own; it can hide its frame and header until it is pointed
333 at, and a row holding only one-row text cards is as tall as its text. Double-click the text, or use B<Edit text>, to change it or
334 to remove the card. B<Add current view> in the toolbar appends another
335 table, chart or map without leaving the canvas, and a status region announces
336 the card and the new visual count; when the card's script has drawn it, the
337 region says the chart or map has finished drawing, and if D3 or Leaflet could
338 not be loaded it names the missing library instead. A scatter card can be
339 coloured by a column and its bubbles sized by a number there, with the same
340 choices as the scatter page. A card that shows an
341 aggregated value picks its own function in that panel, from the vocabulary the
342 pivot uses and with the same names: Sum, Average, Min, Max, Count distinct,
343 Median, Std dev, First, Last, Range or a Percentile with its level, so a card
344 can show a median, a spread or a percentile where the chart pages behind it
345 could only sum. Canvases support
346 cross-filtering, drill-through hierarchies, parameterisation, bookmarks
347 with undo/redo, per-visual SVG, PNG and PDF download, and print to PDF/paper.
348  
349 =item *
350  
351 B<Drag-and-drop upload> -- any supported data file can be dropped directly
352 onto the application. The file is opened immediately; when the "Combine
353 data" panel is open the dropped file populates the right-table path field.
354  
355 =item *
356  
357 B<Export> -- the toolbar export panel writes the current logical view
358 (after joins, filters, and dedup) to a chosen filesystem path as CSV
359 (C<.csv>), SQLite (C<.sql>), or JSON (C<.json>). Only the columns the table
360 still shows are saved, in the table's order: a column you deleted is left out,
361 and a column you dragged to a new place is written there (JSON keys follow the
362 same order).
363  
364 =item *
365  
366 B<Print> -- the Print button, to the right of Refresh, prints the header row
367 and every row of the current view, not just the page on screen: the rows the
368 Export panel would save (after joins, filters, calculated and cross-row
369 columns, and dedup), read from C<GET /export?format=json>, with the columns in
370 the order the table shows them and sorted as it is sorted. Nothing else on
371 the page is printed, and the header row repeats on each printed page. A row
372 deleted from the page with Delete selected is still printed; a deleted column
373 is not.
374  
375 =item *
376  
377 B<URL import> -- C</import> fetches an HTML table from any public URL and
378 renders it in the browser without saving to disc.
379  
380 =item *
381  
382 B<Redis data source> (optional) -- when the C<Redis> or C<Redis::Fast> module
383 is installed, any Redis hash store can be opened as a read-only data table by
384 entering a C<redis:tablename|redis://host:port> spec in the path field or in a
385 join/combine panel. Redis keys must follow the C<tablename:entry> convention
386 used by L<Database::Abstraction>. Because C<Redis> is an optional dependency,
387 the application works fully without it; Redis support activates automatically
388 when the module is available.
389  
390 B<MariaDB and MySQL data source> (optional) -- a table on a server named in the
391 C<mariadb_servers> configuration opens as C<mariadb:server/table>, read-only, with
392 the columns in the table's own order and a page read with C<LIMIT>. See
393 L</MariaDB and MySQL servers>.
394  
395 =back
396  
397 =head2 UTF-8 and Encoding
398  
399 All file data is returned as Perl character strings. CSV/PSV/TSV files are
400 read by L<Text::xSV::Slurp> or L<DBD::CSV>, both of which pass bytes
401 through without re-encoding; the application serves the resulting page as
402 C<text/html; charset=UTF-8>, so full Unicode is displayed correctly as
403 long as the source file itself is UTF-8. A UTF-8 byte-order mark at the
404 start of a CSV, TSV, PSV or JSON file (Excel's "CSV UTF-8" writes one) is
405 read past, so it is not part of the first column's name.
406  
407 Filter values (C<f=col:op:val>) are decoded from the URL by Mojolicious
408 before reaching the controller and are compared against cell values as
409 Perl character strings. Unicode characters in filter values are therefore
410 supported transparently.
411  
412 URL-imported HTML tables are fetched with L<Database::BI::SafeUA> (see
413 L</Which addresses it may fetch>);
414 L<Database::Abstraction> uses the page's own charset declaration to decode
415 the body. If the remote page declares an incorrect charset, cell values
416 may contain mojibake -- this is a limitation of the source data, not the
417 application.
418  
419 =head1 SYNOPSIS
420  
421 B<Start the development server (restarts automatically when you edit a file):>
422  
423 script/database-bi
424  
425 C<morbo -l http://127.0.0.1:3000 script/database-bi> does the same thing (a bare
426 C<morbo script/database-bi> listens on every interface, so it starts only with a
427 password set), and
428 C<script/database-bi daemon> starts a plain server with no file watcher; any
429 other Mojolicious command word (C<routes>, C<get>, ...) is passed to the
430 application.
431  
432 B<Start it showing one database:>
433  
434 script/database-bi data/store.db
435  
436 The home address then shows that database, and its Home link leads to the usual
437 list. Only one can be named: more than one is an error (exit status 2), because
438 a join cannot be given on the command line, so open one and use Merge or Combine
439 in the browser. A file that is missing, cannot be read or is of an unsupported
440 type is the same error, before the server starts. A remote path, Redis spec or
441 MariaDB spec is accepted as it would be by C</open>, and is checked when it is first shown.
442 It listens on port 3000 of this machine only (C<http://127.0.0.1:3000>); see
443 L</Who can reach the server> to change the port or open it to other machines.
444 A plain server does the same with
445 C<BI_OPEN=/full/path/store.db script/database-bi daemon>; a file named after
446 C<daemon> is ignored.
447  
448 B<Start the production server:>
449  
450 hypnotoad script/database-bi # start, or restart with no downtime
451 hypnotoad -s script/database-bi # stop
452  
453 It listens on port 8080 of this machine only and ignores C<MOJO_LISTEN>; set the
454 port and anything else in C<database_bi.conf>, under
455 C<< hypnotoad => { listen => ['http://*:8080'] } >> (C<*> opens it to every machine).
456 It keeps its process id in F<script/hypnotoad.pid> unless C<pid_file> says
457 otherwise. It takes no database on its command line: use
458 C<BI_OPEN=/full/path/store.db hypnotoad script/database-bi>.
459  
460 B<Use a different data directory:>
461  
462 # In database_bi.conf (create this file in the same folder as script/):
463 { data_dir => '/home/user/data' }
464  
465 B<Change the language used for templates:>
466  
467 # In database_bi.conf:
468 { data_dir => 'data', language => 'fr', platform => 'web' }
469 # Then create templates/web/fr/ and put your French .html.tt files there.
470  
471 B<American spelling:> a browser that asks for English (United States) gets the
472 pages from C<templates/web/en-us/>; set C<< language => 'en-us' >> to make that
473 the default for every browser that names no other English.
474  
475 B<Run the test suite to verify everything is working:>
476  
477 make test
478  
479 B<Generate the Makefile for the first time or after editing Makefile.PL:>
480  
481 perl Makefile.PL
482  
483 =head1 ROUTES
484  
485 =over 4
486  
487 =item C<GET />
488  
489 Scans C<data_dir>, renders a card grid of available tables.
490  
491 When the server was started with the name of a database (see L</SYNOPSIS>), a
492 request from outside the application is redirected to C</open> for that
493 database. A request whose C<Referer> is this server, such as the Home link, gets
494 the card grid, so a browser that withholds C<Referer> always sees the database.
495  
496 =item C<GET /tutorial>
497  
498 Renders the tutorial that is part of the application. The chapters are data
499 in L<Database::BI::Tutorial>, not in this POD.
500  
501 =item C<GET /login>, C<POST /login>, C<POST /logout>
502  
503 The login, when C<password_hash> is set (see L</Logging in>). C<GET /login>
504 shows the form (with C<return=>, the page to go back to: a path on this site),
505 C<POST /login> takes C<password=> and C<return=>, and C<POST /logout> ends the
506 session. With no password set, C</login> says there is nothing to log in to.
507  
508 =item C<GET /preferences>
509  
510 Sets the reader's preferences: the theme, one of light, dark or the same as the
511 device (the default), and the rows a table or pivot shows on a page (25, 50,
512 100, 200 -- the default -- or All). The theme is kept in the browser's
513 C<localStorage> and the page size in its cookie C<bi_per_page>, because the
514 server reads it (a value other than 25, 50, 100, 200 or 0 is ignored, and the
515 page is 200 rows); neither is stored on the server, and both apply to every page.
516 Saved charts, printed pages and embedded canvases stay light. The Preferences
517 link at the top of each page passes C<back=> (that page), so the breadcrumb
518 here leads back to it.
519  
520 =item C<GET /view/:table>
521  
522 Opens the named table from C<data_dir>. Accepts C<?f=col:op:val>
523 (repeatable) to pre-filter results, and C<?range=name&rcol=column> to keep
524 only a relative window of rows (see L</Relative time ranges>).
525  
526 A long table is shown a page at a time: C<?page=> is the page, and
527 C<?per_page=> its size (else the reader's preference, else 200; up to 2000;
528 C<0> is every row on one page, and then C<page=> is ignored; a number below 1
529 is 1, and anything that is not a whole number written with the digits 0-9 is
530 taken as if it were not given). The page says
531 "Page 2 of 7", and its Rows per page list (25, 50, 100, 200, All) changes the
532 size, keeping the first row on screen. A pivot pages its row groups the same
533 way.
534  
535 C<?f=col:between:lo:hi> keeps the rows whose C<col> lies from C<lo> to C<hi>,
536 both included, whichever bound is written first. Two numbers (a range of
537 years, C<Year:between:1880:1900>) compare as numbers; two dates or timestamps
538 compare as times (C<when:between:2026-11-01T09:00:00:2026-11-01T17:00:00>
539 splits at the colon between them); any other pair compares as text, ignoring
540 case. The filter row offers it for date columns (two
541 date boxes) and number columns (two number boxes).
542  
543 A name that is not a table in C<data_dir> is a C<404> page that says so ("There
544 is no table called ..."), with the breadcrumb and site navigation; it does not
545 show the data directory.
546  
547 =item C<GET /browse>
548  
549 Filesystem navigator. Accepts C<?path=> to set the starting directory
550 (defaults to C<$HOME>). When the folder holds two or more data files the
551 page can tick several and send them to C</combine> (the first as C<l=>, the
552 others as C<c=>, with C<srccol=source_file>). A very long list makes a long
553 URL, so the request line may be up to 256 KiB (C<MOJO_MAX_LINE_SIZE>, which
554 is set to that at startup unless it is already set).
555  
556 =item C<GET /open>
557  
558 Opens any supported file by absolute path (C<?path=>). Accepts C<?f=>
559 filters. When the file is a multi-table SQLite database, passing
560 C<?it=E<lt>tableE<gt>> selects a specific internal table instead of the
561 auto-detected first one.
562  
563 =item C<GET /join>
564  
565 Performs one or more left joins and renders the merged table. Parameters:
566  
567 l=<spec> left table spec (see below)
568 j=<spec>|<lk>|<rk> join step (repeatable): right-spec, left key, right key
569 c=<spec> table to stack after the joins (repeatable; see /combine)
570 srccol=<name> with c=, a column naming each row's source file (see /combine)
571 f=<col>:<op>:<val> result filter (repeatable)
572 range=<name> relative time range, with rcol=<column> (see below)
573  
574 Spec formats:
575  
576 table:name named table from data_dir
577 table:file/table a table inside a multi-table SQLite file
578 (or a list in a JSON file) in data_dir
579 path:/abs/path/to/file.csv absolute local path
580 path:/abs/path/to/file.db#table one table of such a file anywhere else;
581 a file whose own name has a # is that file
582 /../hostname/dir/file.csv remote file via SFTP
583 redis:tablename|redis://host:port Redis hash store (requires Redis module)
584 mariadb:server/table a table on a server in mariadb_servers
585 mariadb:server lists that server's tables
586  
587 =item C<GET /api/columns>
588  
589 Returns C<{ "columns": [...] }> for a table (C<?table=name> or
590 C<?table=file/table> for a table inside a multi-table SQLite file) or file
591 (C<?path=/abs/path>, or C<?spec=path:/abs/path#table> for one of its tables). Used by the join UI to populate the right-key
592 dropdown without a page reload.
593  
594 =item C<GET /export>
595  
596 Exports the current logical view (same C<l=>, C<j=>, C<f=> parameters as
597 C</join>) as a file download. Additional parameter:
598  
599 format=csv (default) - RFC 4180 CSV; UTF-8; CRLF line endings
600 format=sqlite - SQLite 3 database with a single table named "data"
601 format=json - JSON array of row objects; keys follow the column order
602 xcol=<name> - (repeatable) keep only these columns, in this order;
603 names the view lacks are ignored, and none left means
604 every column
605  
606 The download filename is derived from the left table label with
607 non-alphanumeric characters replaced by underscores.
608  
609 =item C<POST /export>
610  
611 Writes the current logical view to a chosen filesystem path.
612 Body params: C<l=>, C<j=>, C<f=>, C<xcol=> (same as GET), plus
613 C<dir=> (target directory) and C<filename=> (name including extension;
614 extension determines format: C<.csv>, C<.sql> or C<.json>). The Export panel
615 sends one C<xcol=> for each column its table still shows.
616 Returns JSON C<{ saved: "/abs/path" }> or C<{ error: "..." }>.
617  
618 =item C<GET /api/dirs>
619  
620 Returns a JSON directory listing (subdirectories only) for the export
621 panel's inline directory browser. Accepts C<?path=> (defaults to
622 C<$HOME>). Returns C<{ path, parent, dirs: [{name, path}] }>.
623  
624 =item C<GET /api/stat>
625  
626 Returns filesystem metadata for a file path (C<?path=>).
627 Returns C<{ exists, path, mtime, size }>. For SQLite files
628 (C<.sql>, C<.sqlite>, C<.sqlite3>, C<.db>) an additional C<table_count>
629 integer is included when the file is a valid SQLite database; the field
630 is omitted for Berkeley DB or other non-SQLite payloads.
631 If the file does not exist, C<exists> is C<false> and the remaining
632 fields are absent (HTTP 200). Returns HTTP 400 when C<path> is missing.
633  
634 =item C<POST /upload>
635  
636 Accepts a multipart file upload (field name: C<file>), validates the
637 extension, saves to a managed C<.uploads/> subdirectory under the app
638 home, and returns JSON C<{ url, path }>.
639  
640 =item C<GET /import>
641  
642 Fetches an HTML table from a public URL (C<?url=>) and renders it as a
643 data grid. A URL that leads to this machine or a private network is refused
644 (see L</Which addresses it may fetch>). An optional C<?t=> parameter (zero-based integer) selects
645 which HTML table on the page to display when the page contains multiple
646 tables.
647  
648 =item C<GET /tables>
649  
650 Schema browser for multi-table SQLite databases. Accepts C<?l=E<lt>specE<gt>>
651 (same C<table:name> or C<path:/abs/path> spec as C</join>). Returns a card
652 grid listing every internal table with its columns; each card links to
653 C</open?path=...&it=E<lt>tableE<gt>>. Redirects to 404 when the spec is
654 absent, invalid, or the resolved file is not a multi-table SQLite database.
655  
656 =item C<GET /combine>
657  
658 Stacks rows from two or more tables vertically (UNION ALL) into a unified
659 view. All columns from all sources appear as headers; cells are blank
660 where a source file lacks a column. Parameters:
661  
662 l=<spec> left table: "table:name" or "path:/abs/path"
663 j=<spec>|<lk>|<rk> join step applied to the left table first (repeatable)
664 c=<spec> additional table to stack (repeatable)
665 f=<col>:<op>:<val> result filter applied after combining (repeatable)
666 srccol=<name> add a last column, <name>, holding the file or table
667 each row came from (a letter or underscore, then
668 letters, digits or underscores, at most 64; a name a
669 source already uses gets an underscore added). The
670 file browser's Combine selected passes source_file.
671 The panels, Export and Print carry it on.
672  
673 =item C<GET /graph>
674  
675 Renders a D3.js v7 zoomable line chart of any two columns. Parameters:
676  
677 l=<spec> left table (required)
678 x=<col> X-axis column name (required; any type, shown as labels)
679 y=<col> Y-axis column name (required; must be numeric after stripping
680 currency symbols and commas; accounting-notation negatives
681 like (1,234.56) are handled automatically)
682 span=<n><unit> bucket x into time buckets (optional; see "Time buckets")
683 agg=<fn> aggregate y per bucket, which is what makes this a
684 timechart (optional; default: one point per row)
685 series=<col> one line per value of this column (optional)
686 back=<url> URL for the second breadcrumb link (optional; default "/")
687 back2=<url> URL for the outermost breadcrumb link when three levels are
688 needed (optional; e.g. /tables?l=... for the schema browser)
689 back2_label=<text> Label for the back2 link (optional; default "Back")
690 j=, f=, d= pipeline params (same as /join)
691  
692 A one-line chart offers check boxes above it for reference lines: Min, Avg,
693 Max, and Trend, the straight line closest to the points (least squares, by
694 L<Statistics::LineFit>), labelled with its slope per point and its R squared
695 (a flat series is slope 0 and R squared 1: the line passes through every
696 point).
697 The points are evenly spaced along the axis, so the fit is of Y against each
698 point's place, not its label. After a zoom, every line is worked out again
699 from the points in view. None is offered on a chart with C<series=>, and Trend
700 needs two points.
701  
702 =item C<GET /pie>
703  
704 Renders a D3.js v7 animated pie chart grouped by a category column.
705 Clicking a slice or legend entry navigates to the table view filtered to
706 that category. Parameters:
707  
708 l=<spec> left table (required)
709 cat=<col> category column to group by (required)
710 val=<col> numeric column to sum per category (required)
711 donut=1 show a hole in the centre (optional)
712 back=<url> URL for the second breadcrumb link (optional; default "/")
713 back2=<url> URL for the outermost breadcrumb link (optional)
714 back2_label=<text> Label for the back2 link (optional; default "Back")
715 f= result filters applied before aggregating (repeatable)
716  
717 =item C<GET /heatmap>
718  
719 Renders a D3.js v7 grid heatmap with two categorical axes. Each cell
720 colour encodes a summed or counted numeric value. Parameters:
721  
722 l=<spec> left table (required)
723 x=<col> X-axis column name (required; categorical)
724 y=<col> Y-axis column name (required; categorical)
725 val=<col> numeric column to sum per cell (optional; omit to count rows)
726 scheme=<name> colour scheme: YlOrRd Blues Greens Purples RdPu YlGnBu
727 (optional; default YlOrRd)
728 show_val=1 print the value inside each cell (optional)
729 back=<url> URL for the second breadcrumb link (optional; default "/")
730 back2=<url> URL for the outermost breadcrumb link (optional)
731 back2_label=<text> Label for the back2 link (optional; default "Back")
732 j=, f=, d= pipeline params (same as /join)
733  
734 =item C<GET /bar>
735  
736 Renders a D3.js v7 bar chart grouped by a categorical column. Parameters:
737  
738 l=<spec> left table (required)
739 cat=<col> category (X-axis) column (required)
740 val=<col> numeric column to sum per category; omit or use __count__
741 to count rows instead of summing (optional)
742 orient=h horizontal bars (default: vertical)
743 sort=value|label sort bars by descending value or ascending label
744 max=N collapse bars beyond the top-N into an "Other" bar
745 back=<url> URL for the second breadcrumb link (optional; default "/")
746 back2=<url> URL for the outermost breadcrumb link (optional)
747 back2_label=<text> Label for the back2 link (optional; default "Back")
748 j=, f=, d= pipeline params (same as /join)
749  
750 =item C<GET /folder>
751  
752 Hierarchical folder view. Groups a data table by the letter-prefix of an
753 order-number column (e.g. A10, CT4, B3) and shows one card per prefix group.
754 Clicking a card with sub-prefixes drills down; clicking a leaf shows the
755 matching data rows. Parameters:
756  
757 l=<spec> left table (required)
758 col=<col> order-code column (auto-detected when absent)
759 prefix=<str> current drill-down prefix (top level when absent)
760 back=<url> URL for the back link (optional)
761 f= result filters (repeatable)
762  
763 =item C<POST /uploads/clear>
764  
765 Deletes every file from the C<.uploads/> staging directory. Returns JSON
766 C<{ "freed": <bytes>, "count": <n> }>. No request body is needed.
767  
768 =item C<GET /pivot>
769  
770 Renders a pivot/crosstab table. Parameters:
771  
772 l=<spec> left table (required)
773 rows=col1,col2 row-dimension column names (required)
774 cols=col3 column-dimension names (optional)
775 m=col:fn:alias measure spec, repeatable (fn: sum|avg|min|max|count|count_distinct
776 for the aggregates the backend computes, median|stdev|first|last|range
777 for those computed in Perl from the group's values, or p<N> for
778 the Nth percentile -- p50 is the median, and p1 to p100 are accepted)
779 totals=1 include subtotals column and grand-total row
780 topn=N keep only the top-N row groups
781 topn_col=<alias> measure alias to rank by (required when topn= is set)
782 max_cols=N collapse tail column combos beyond top-N into "Other"
783 format=csv|sqlite|json|xlsx stream result as a download
784 back=<url> URL for the back breadcrumb link
785 f= result filters applied before aggregating (repeatable)
786  
787 =item C<GET /stats>
788  
789 Per-column statistics view. Returns one row per column: row count, null
790 count, distinct count, first and last, and (for numeric columns) min, max,
791 range, mean, median, the percentile named by C<p=N> and sample standard
792 deviation. Parameters: C<l=E<lt>specE<gt>> (required), C<f=> filters and
793 C<p=N> for the percentile column (1 to 100, default 95).
794  
795 =item C<GET /scatter>
796  
797 D3.js v7 scatter/bubble plot. Parameters:
798  
799 l=<spec> left table (required)
800 x=<col> X-axis column (required; numeric)
801 y=<col> Y-axis column (required; numeric)
802 series=<col> categorical colour dimension (optional)
803 size=<col> numeric bubble-radius dimension (optional)
804 scheme=<name> colour scheme when series= is set: tableau10 (default),
805 category10, set2, set3 or paired; any other is a 400
806 min_r=N smallest bubble radius in px with size= (1-40, default 3)
807 max_r=N largest bubble radius in px with size= (1-40, default 15)
808 back=<url>, back2=<url>, back2_label=<text> breadcrumb links
809 f= result filters (repeatable)
810  
811 =item C<GET /stacked>
812  
813 D3.js v7 stacked bar chart. Parameters:
814  
815 l=<spec> left table (required)
816 cat=<col> X-axis categories (required)
817 series=<col> stack segments (required; seg= is a backwards-compatible alias)
818 val=<col> measure column (optional; omit to count rows)
819 scheme=<name> colour scheme (optional)
820 back=<url>, back2=<url>, back2_label=<text> breadcrumb links
821 f= result filters (repeatable)
822  
823 =item C<GET /combo>
824  
825 D3.js v7 combo bar+line chart. Parameters:
826  
827 l=<spec> left table (required)
828 cat=<col> X-axis categories (required; x= is a backwards-compatible alias)
829 bar_val=<col> bar measure column (required)
830 line_val=<col> line measure column (required)
831 scheme=<name> bar and line colours: the first two of tableau10,
832 category10, set2, set3 or paired (optional; steel blue and
833 red without it, and for any other name)
834 back=<url>, back2=<url>, back2_label=<text> breadcrumb links
835 f= result filters (repeatable)
836  
837 =item C<GET /treemap>
838  
839 D3.js v7 treemap. Parameters:
840  
841 l=<spec> left table (required)
842 group=<col> tile label column (required; cat= is a backwards-compatible alias)
843 size=<col> tile area column, summed (optional, counting rows without it;
844 val= is a backwards-compatible alias)
845 topn=N keep only the top-N tiles; remainder merged into "Other"
846 scheme=<name> colour scheme (optional)
847 color=<col> shade each tile by this column instead (optional), folded
848 over the tile's rows; "Other" is folded over the rows it holds
849 color_agg=F how color= is folded: avg (default), sum, min, max, median or
850 any other aggregate function; an unknown one is a 400
851 color_scheme=S scale for color=: YlOrRd (default), Blues, Greens, Purples,
852 RdPu or YlGnBu; any other name is YlOrRd
853 back=<url>, back2=<url>, back2_label=<text> breadcrumb links
854 f= result filters (repeatable)
855  
856 =item C<GET /histogram>
857  
858 D3.js v7 histogram with server-side binning. Parameters:
859  
860 l=<spec> left table (required)
861 col=<col> numeric column to bin (required)
862 bins=N bin count (default 10; clamped to range 1--200)
863 scheme=S bar colour: the first colour of tableau10, category10, set2,
864 set3 or paired (optional; steelblue without it, and for any
865 other name)
866 back=<url>, back2=<url>, back2_label=<text> breadcrumb links
867 f= result filters (repeatable)
868  
869 =item C<GET /wordcloud>
870  
871 Word cloud of a text column, drawn with HTML::TagCloud. Each row contributes
872 its words once, so a word's size is the number of rows that use it rather than
873 the number of times one long note repeats it. Common English words are
874 removed. Parameters:
875  
876 l=<spec> left table (required)
877 col=<col> text column to read (required)
878 topn=N number of different words to show (default 50; range 1--500)
879 minlen=N shortest word kept (default 3; range 1--64)
880 stop=<words> extra words to ignore, comma or space separated (optional)
881 back=<url>, back2=<url>, back2_label=<text> breadcrumb links
882 f= result filters (repeatable)
883  
884 With C<back=>, each word links to the rows that contain it.
885  
886 The same cloud is available as a card on a saved canvas: C<POST
887 /api/analyses/:id/visuals> takes C<< kind => wordcloud >> with C<encode.col>,
888 and the card counts the words of its own rows -- its filters, the page's
889 cross-filter and its own options -- so a canvas that is narrowed to one
890 region shows the words of that region.
891  
892 =item C<GET /map>
893  
894 OpenStreetMap map of the filtered view, drawn with HTML::OSM. A row's position
895 comes from a location column that is geocoded (C<loc=>, one lookup per distinct
896 value, remembered once in the model store and shared with every dataset that
897 names it) or from coordinate columns (C<lat=> and C<lon=>). Rows sharing a
898 position become one marker. When some rows cannot be plotted, the note that
899 says so counts them by reason (empty, not a place name, not found, or not looked
900 up yet), links to all of them in the table, and opens onto a list of their
901 places, each with its number of rows, why it was not plotted and a link to
902 those rows. Markers are clustered with
903 Leaflet.markercluster, so a dense map draws a count at low zoom and splits it
904 as it is zoomed in. Clustering is always on. The map has a scale bar, opens
905 on every marker unless C<zoom=> is given, and draws its key (colours, and
906 bubble sizes) on the map; the colours listed are those of the markers in view,
907 so the key changes as the map is zoomed and moved.
908  
909 Places that are not in the cache yet are looked up after the page is shown.
910 The map draws what the cache already knows, and a progress bar names each
911 place as it is looked up ("Looking up 5 of 10: 10 Downing St, London"). Each
912 answer is saved at once, through C<POST /geo/lookup>, and the map is drawn
913 again when the last one is in. Cancel stops the lookups and draws the map with
914 the places found so far. The places left are listed as not looked up yet, with
915 a link to look them up. Without JavaScript, or for a client that is not a
916 browser, the page waits for the lookups instead (C<geocode=wait>). Parameters:
917  
918 l=<spec> left table (required)
919 loc=<col> column of places to geocode (required unless lat= and lon= are);
920 repeat it for a place written across columns, which are joined
921 with ", " in that order (loc=Address&loc=Country)
922 loc_text=<text> text added to the end of each place before it is looked
923 up, after ", " (loc=County&loc_text=Virginia, USA looks up
924 "Accomack, Virginia, USA"); one line, at most 200 characters;
925 a row with no place is still not looked up
926 lat=<col> latitude column, -90..90
927 lon=<col> longitude column, -180..180
928 popup=<col> column shown in the marker popup (repeatable; default every
929 column but the place or coordinates)
930 max=N markers to draw (default map_max_markers, 2000)
931 zoom=N initial zoom 0..19 (default: fit the markers)
932 max_zoom=N tile layer maxZoom 0..28 (default: map_max_zoom, if set)
933 tiles=<name> named tile source from the tile_sources config key
934 heat=1 add a heatmap layer over the markers
935 bounds=<level> draw the outline of the area around each marker: country,
936 state, county, city, town or neighbourhood
937 weight=<col> numeric heatmap intensity column (normalised to 0..1)
938 size=<col> numeric bubble-radius column; markers become circles
939 color=<col> colour markers from a column
940 color_rule=<op>:<value>:<colour> repeatable; op is gt, ge, lt, le, eq or ne
941 color_default=<colour> fallback colour (default #3388ff)
942 series=<col> colour markers by category (not with color=)
943 scheme=<name> palette for series=: tableau10, category10, set2, set3, paired
944 geocode=wait look up the places not cached yet before the page is sent
945 (the default for a client that is not a browser)
946 geocode=cached look nothing up: plot what the cache knows (where Cancel leads)
947 back=<url>, back2=<url>, back2_label=<text> breadcrumb links
948 f= result filters (repeatable)
949  
950 With C<bounds=> (the map panel's "Show boundaries"), the map draws the outline
951 of the area each marker is in, with a checkbox on the map to hide them. The
952 level says how large an area:
953  
954 country the country
955 state a US or Indian state, a Canadian province, a New Zealand
956 region, England or Scotland
957 county the division below a state; see below
958 city a city, or the district named after it: Toronto, Manchester,
959 the district of Canterbury, Hamilton City in New Zealand.
960 Where OpenStreetMap has no city round a point, or has it only
961 as a point (York, Pune), the authority at the county's rank
962 town a town or a city ward: Margate, Toronto Centre
963 neighbourhood a neighbourhood, suburb or civil parish
964  
965 OpenStreetMap has a shape for every country, state and county, but not for
966 every smaller place: many towns and most suburbs are mapped as a single point
967 (Cliftonville and Garlinge in Margate are), and a marker there has no outline at
968 that level. The list under the map says which markers those are. Larger areas
969 are simplified more, so an outline is a few kilobytes at any level.
970  
971 The outlines come from Nominatim's reverse lookup, which is sent each
972 marker's position rounded to three decimal places (about 110 metres), and only
973 when C<map_geocode_online> allows it. Each outline is remembered under
974 C<model_dir> (C<boundary-cache>), with the points found in it, so a point inside
975 an outline already known costs no lookup; each level is remembered apart. A
976 county is the division of a
977 country below its states, whose place rank in Nominatim depends on the country:
978 12 (a US county or independent city, an English county, a German Landkreis), or
979 10 for India, Bangladesh, China and Spain (district, prefecture, province), or 8
980 for Kenya. Australia, Brazil and Japan have nothing at that level. Config
981 C<map_bounds_ranks> (C<< { lk => 10 } >>: two-letter codes, ranks 8, 10 or 12)
982 adds or changes countries for the county level; startup refuses anything else. Each reply names its
983 country, so a point is asked at the rank of the last country seen, and again
984 at its own when that differs.
985 Outlines not known yet are looked up as places are: by the progress bar, through
986 C<POST /geo/boundary>, or in the request for C<geocode=wait>; at most
987 C<map_geocode_online_max> in one request. The checkbox needs L<HTML::OSM> 0.15;
988 with 0.14 the outlines are always shown.
989  
990 With C<heat=1> as well, each outline is coloured by what is in it: the
991 C<weight=> column summed over every row inside it (or its rows counted, with no
992 C<weight=>), from green for the smallest total to red for the largest. The
993 colour follows the size of the total on a logarithmic scale: each step up the
994 colours is the same multiple, so totals close in size share a colour and skewed
995 totals (one county with 500 times the people of another) still spread across
996 the scale. When a total is zero or less the colours go by rank instead. With
997 one outline, or totals all alike, there is nothing to compare, so the outlines
998 stay grey. Each outline's popup gives its total, and the line under the title
999 says what the colours mean. The checkbox, the key and that line call an
1000 outline what its country does (a district in India, a province in Spain, an
1001 area when the map mixes them). With L<HTML::OSM>
1002 0.16 a key in the map's bottom right corner lists each colour, highest first,
1003 with the totals it covers, rounded to two figures ("30,000 to 37,000"); it hides with the outlines'
1004 checkbox.
1005  
1006 When the markers are coloured (C<color=>), the outlines take their colours
1007 instead, with or without C<heat=1>, so a border never disagrees with the
1008 markers inside it. With L<HTML::OSM> 0.17 each coloured outline, here and on the heat scale, is
1009 drawn just inside its own edge, so where two counties of different colours
1010 meet the border is a line twice as wide, one colour on each side. An outline
1011 whose markers differ gets a line of each of their colours, side by side, the
1012 colour most of its markers have outermost. An older HTML::OSM draws each
1013 outline along its edge in that first colour alone, one over another where they
1014 meet. Outlines are simplified to about 100 metres one at a time, so zoomed
1015 well in, neighbours' lines can part or overlap a little. The markers' key explains the colours, so the outlines have none of
1016 their own.
1017  
1018 A map can have fewer outlines than markers, and a list under it says why: each
1019 outline that holds more than one marker, with the places in it, and the markers
1020 in no outline at all, each with a link to its rows in the table. Often that is
1021 as it should be (several shops in one county). Where the places were looked up
1022 by name it can also be a wrong answer, since a name may be ambiguous, and the
1023 list says so; C<loc_text=>, or latitude and longitude columns, make a lookup
1024 surer. The list names at most 50 outlines, the fullest first. While some
1025 places have no outline yet (not looked up, or OpenStreetMap did not answer),
1026 the note above the map links to their rows and, for those not looked up, to
1027 the map again to look them up.
1028  
1029 Outlines are written into the page, about 7 KB each before compression, so a
1030 map of a state's counties is well under a megabyte, and one of every county in
1031 a large country would be very large: filter the rows first.
1032  
1033 C<shade=E<lt>columnE<gt>> (Colour shade, in the map panel) fills each outline in a
1034 shade of one colour, the darker the larger that column's total over the rows
1035 inside it, as a census map is drawn. There are five shades, placed on the same
1036 logarithmic scale, from a light tint up to the colour itself: C<shade_color=>
1037 (a colour name or C<#rrggbb>) chooses it, orange by default. A key lists each
1038 shade in use, darkest first, with the totals it covers, as filled boxes with
1039 L<HTML::OSM> 0.18 (lines before), and each outline's popup, which now opens from
1040 anywhere inside it, gives its total. The lines stay grey, or take the markers'
1041 colours: with a shade the heat layer no longer colours them, since the fill
1042 says the same. With one outline, or totals all alike, nothing is filled.
1043  
1044 When the markers are coloured (C<color=>) and no C<shade_color=> is given, each
1045 outline is shaded in its own markers' colour instead, each colour a scale of its
1046 own: the further a total is into what the colour stands for, the stronger the
1047 shade. For a rule on the shaded column that reads "less than" (C<lt>, C<le>)
1048 that means the smaller total: with C<color_rule=lt:20000:green> a county of
1049 2,000 is a stronger green than one of 19,000, while under
1050 C<color_rule=gt:100000:red> the largest county is the strongest red. The key
1051 lists every shade by size, the largest totals at the top, so it runs from the
1052 strongest red down to the strongest green. It then stands for the markers'
1053 colours as well, so the markers' own key of those colours is left out while the outlines are
1054 shown. With L<HTML::OSM> 0.19 it comes back when the reader hides the outlines
1055 with their checkbox, and goes again when they are shown; an older HTML::OSM
1056 leaves it out throughout. The markers' key always stays when the shade is of
1057 another column or of one colour, where nothing else says what the marker
1058 colours mean. Give C<shade_color=> to shade
1059 every outline in one colour as before.
1060  
1061 A marker stands for every row at its place, and its popup lists them all: a
1062 value every row shares is shown once ("Person: Valentin Puntar"), and the
1063 columns that differ are a small table, one line a row. The table shows at most
1064 C<map_popup_rows> rows (default 10) in a box that scrolls, so a busy place does
1065 not cover the map; the rest are counted, with a link to them in the table the
1066 map came from.
1067  
1068 An unknown C<tiles=> or C<scheme=> is a 400, as is an unknown column, C<color=>
1069 together with C<series=>, or a transposed lat/lon pair. The page never shows
1070 the L<HTML::OSM> Nominatim search box (C<search =E<gt> 0> is always passed), so
1071 nothing typed on the map is sent anywhere. With C<loc=>, a place the local
1072 data does not know is sent to Nominatim, as the place name alone; set
1073 C<map_geocode_online> to 0 to keep every lookup local. L<HTML::OSM> 0.14 or
1074 later is the renderer; an older optional install still returns the page with a
1075 warning.
1076  
1077 =item C<GET /line>
1078  
1079 Alias for C<GET /graph>. All C</graph> parameters accepted.
1080  
1081 =item C<GET /canvases>
1082  
1083 Lists the saved canvases, as cards that open them, with Import canvas. It is
1084 the main navigation's Canvases link; the home page shows the same list,
1085 without Import canvas. With
1086 no canvases, the page says how to make one. A canvas's breadcrumb leads back
1087 here unless its C<back=> names another page.
1088  
1089 =item C<GET /a/:id>
1090  
1091 Renders a saved canvas (analysis) as a full multi-visual page. Accepts
1092 cross-filter params C<?cf=E<lt>colE<gt>&cv=E<lt>valE<gt>>, drill-through
1093 params C<?dd=E<lt>colE<gt>&dl=E<lt>levelE<gt>>, parameter overrides
1094 C<?p.E<lt>nameE<gt>=E<lt>valueE<gt>>, and a relative time range
1095 C<?range=E<lt>nameE<gt>&rcol=E<lt>columnE<gt>> that narrows every card on the
1096 canvas (see L</Relative time ranges>).
1097  
1098 =item C<GET /api/analyses>
1099  
1100 Returns C<{ analyses: [{id, name, datasets, updated}] }>.
1101  
1102 =item C<POST /api/analyses>
1103  
1104 Creates a new analysis from a JSON request body. Required fields: C<name>
1105 and C<datasets> (array; each entry must have a C<spec> starting with
1106 C<table:>, C<path:>, C<url:> or C<redis:>, or being C<mariadb:server/table>).
1107 Returns C<201 { id, created: 1 }>.
1108  
1109 =item C<GET /api/analyses/:id>
1110  
1111 Returns the full analysis document.
1112  
1113 =item C<PUT /api/analyses/:id>
1114  
1115 Full replacement of an analysis document.
1116  
1117 =item C<PATCH /api/analyses/:id>
1118  
1119 Partial update; merges the supplied top-level keys. C<id> and C<created>
1120 are immutable. The C<layout> key places the visuals on the canvas grid: an
1121 array of C<{ visual, x, y, w, h }>, where C<visual> indexes the C<visuals>
1122 array and C<x>, C<y>, C<w> and C<h> are 1-based grid columns and rows (the
1123 grid is 12 columns wide, C<x + w - 1> cannot exceed 12, and one visual may
1124 span at most 6 rows). Positions are
1125 stored as given - a gap is a gap - but two visuals may not share a cell, so
1126 an overlapping set is rejected with C<400> and the stored layout is left
1127 alone.
1128  
1129 =item C<POST /api/analyses/:id/visuals>
1130  
1131 Appends one visual to a saved canvas. Body: C<{ kind, encode, options,
1132 title, query }>, with C<kind> one of C<table>, C<bar>, C<pie>, C<line>,
1133 C<graph>, C<scatter>, C<heatmap>, C<stacked>, C<combo>, C<treemap>,
1134 C<histogram>, C<wordcloud>, C<map> or C<text>. A C<text> card reads no data, and
1135 its C<options> are C<text> (required, up to 20,000 characters), C<font>
1136 (C<arial>, C<georgia>, C<times>, C<verdana>, C<trebuchet> or C<courier>), C<size>
1137 (8 to 96 points), C<colour> and C<background> (C<#rrggbb>; leaving out C<colour>
1138 follows the theme), C<align> (C<left>, C<center> or C<right>), C<bold>, C<italic>
1139 and C<plain>. The text is shown as plain text, never as markup. A map's C<encode> names either C<loc> (a place column
1140 to geocode) or C<lat> and C<lon>. A C<wordcloud> card's C<encode> names the
1141 text column to read in C<col>, and its C<options> take the same C<topn>,
1142 C<minlen> and C<stop> the C<GET /wordcloud> page takes, so the two count and
1143 rank words with one function. A C<scatter> card's C<encode> names C<x>
1144 and C<y>, and optionally C<series> (colour by value) and C<size> (bubble size); its
1145 C<options> take C<scheme>, C<min_r> and C<max_r> as C<GET /scatter> does,
1146 except that an unknown C<scheme> draws the default colours. A C<line>
1147 or C<graph> card's C<encode> takes an optional C<series>, one line per value.
1148 A C<histogram> card's C<options> take C<bins> and C<scheme> as C<GET /histogram>
1149 does. A C<treemap> card's C<encode> takes an optional C<color>, with
1150 C<options> C<color_agg> and C<color_scheme> as C<GET /treemap>'s C<color=>,
1151 C<color_agg=> and C<color_scheme=>; an unknown function is the card's error.
1152 A C<combo> card's C<options> take C<scheme> as C<GET /combo> does.
1153 The optional C<query> is the canvas page's
1154 query string: C<cf> (cross-filter), C<c> (calculated columns) and
1155 C<p.E<lt>nameE<gt>> (bound parameter values) are read from it, so a card added
1156 while the canvas is filtered or parameterised is drawn through the same state
1157 as the cards already on screen. The visual is rendered against the canvas's
1158 datasets, joins and calculated fields before it is stored, so an unknown
1159 column or an undrawable visual is rejected with C<400> and nothing is appended.
1160 Returns C<201 { id, visual, kind, title, html, head, nonce, cf_col }>, where
1161 C<visual> is the new visual's index, C<head> is any stylesheet and script the
1162 page must add once to draw the card (Leaflet, for a map), C<nonce> is the
1163 Content-Security-Policy nonce the scripts in C<html> carry (the canvas page
1164 runs only those, giving each its own nonce), and C<cf_col> is the
1165 column the card's marks cross-filter by. The card is left unplaced in
1166 C<layout>; it is auto-placed after the saved cards until the reader moves or
1167 resizes it.
1168  
1169 A C<kind> that aggregates a value column -- C<bar>, C<pie>, C<stacked>,
1170 C<treemap>, C<heatmap> and C<combo> -- reads an optional C<encode.agg>: the
1171 function its value column is aggregated with. It takes C<sum> (the default),
1172 C<avg>, C<min>, C<max>, C<count_distinct>, C<median>, C<stdev>, C<first>,
1173 C<last>, C<range>, or a percentile named C<pE<lt>NE<gt>> from C<p1> to C<p100>
1174 -- the same vocabulary and the same spelling a pivot's C<m=> spec uses, so a
1175 card can show a median, a spread or a percentile where the chart pages it came
1176 from could only sum. C<count> is accepted as well: it counts rows and ignores
1177 the value column. The function is checked whatever the kind is, so a misspelt
1178 one is a C<400> rather than a chart drawn some other way, as is a function that
1179 needs a column (C<median>, unlike C<count>) when the card names no value column
1180 or names the value menu's "Count (no column needed)". A combo aggregates both
1181 its series with the one function. A card's derived title says which function it
1182 used (C<median(amount) by region>); a plain sum keeps the title it has always
1183 had.
1184  
1185 A card may bring a cross-row plan of its own in C<cross_row>, in the spelling
1186 the canvas page's C<cs>, C<by> and C<order> use:
1187 C<< { cs => [ I<col:fn:name[:arg]> ... ], by => I<col>, order => [ I<col:dir> ... ] } >>.
1188 The card then runs that plan instead of the page's, so one card of a canvas can
1189 show a running total while the cards beside it show raw rows, and
1190 C<< { cs => [] } >> is a card that runs no cross-row pass at all -- which is how a
1191 card opts out of the page's. A card that sends no C<cross_row> inherits the
1192 page's plan. The plan is checked against the canvas's columns on every render,
1193 not only here, so a saved spec that no longer names a column is that card's
1194 error while a bad page-level C<cs> is the page's C<400>.
1195  
1196 =item C<DELETE /api/analyses/:id/visuals/:visual>
1197  
1198 Removes a text card; any other kind answers C<400>. Later cards move down one
1199 index, and the layout and any C<cv=> saved in a bookmark move with them.
1200  
1201 =item C<PATCH /api/analyses/:id/visuals/:visual>
1202  
1203 Changes the columns of one stored visual without removing it. Body:
1204 C<{ encode, query }>; C<encode> replaces the visual's encoding in place (for
1205 a map, C<{ loc }> or C<{ lat, lon }>), and the optional C<query> is the
1206 canvas page's query string, read for C<cf>, C<c> and C<p.E<lt>nameE<gt>> so
1207 the redrawn card matches the page it is on. The visual keeps its index, so
1208 its layout position, size and title are unchanged. The replacement is
1209 rendered before it is stored, so an unknown column or an undrawable map is a
1210 C<400> and the saved visual is left alone. Returns
1211 C<{ id, visual, kind, title, html, head, nonce, cf_col }>; C<nonce> is the one
1212 the scripts in C<html> carry, which the canvas page gives its own when it runs
1213 them.
1214  
1215 =item C<DELETE /api/analyses/:id>
1216  
1217 Removes the analysis. Returns C<200 { deleted: 1 }>.
1218  
1219 =item C<GET /api/analyses/:id/export>
1220  
1221 Downloads the analysis document as a C<.json> file.
1222  
1223 =item C<POST /api/analyses/import>
1224  
1225 Creates an analysis from an uploaded C<.json> file (multipart C<file>
1226 field) or a raw JSON request body. Caller-supplied C<id>, C<created>,
1227 and C<updated> are stripped. "Import canvas", on C</canvases>, sends the file
1228 that a canvas's Share panel downloads; that panel also makes the read-only
1229 C</share/:id> link (C<POST /api/analyses/:id/share>) and its C</embed/:id>
1230 code.
1231  
1232 =item C<GET /calc/list>
1233  
1234 Returns C<{ fields: { name: expr } }> for stored virtual calc fields
1235 for a given spec. Accepts C<?l=E<lt>specE<gt>>.
1236  
1237 =item C<POST /calc/save>
1238  
1239 Saves a named calc field to C<.bi/models.json>. Body:
1240 C<l=E<lt>specE<gt>&name=E<lt>identE<gt>&expr=E<lt>expressionE<gt>>.
1241 Returns C<{ saved: 1 }> or C<{ error: "..." }> (400 for hostile input).
1242  
1243 =item C<POST /calc/delete>
1244  
1245 Removes a named calc field. Body:
1246 C<l=E<lt>specE<gt>&name=E<lt>identE<gt>>.
1247  
1248 =item C<GET /groups/list>
1249  
1250 Returns C<{ groups: { label: [vals] } }> for named value groups for
1251 a column. Accepts C<?l=E<lt>specE<gt>&col=E<lt>colE<gt>>.
1252  
1253 =item C<POST /groups/save>
1254  
1255 Saves a named value group. Body: C<l=&col=&group=&values=> (values
1256 is a newline-separated list of raw cell values). The group column,
1257 C<E<lt>colE<gt>_group>, appears in the table page as well as in its charts and
1258 exports.
1259  
1260 =item C<POST /groups/delete>
1261  
1262 Removes a named value group. Body: C<l=&col=&group=>.
1263  
1264 =item C<GET /dates/list>
1265  
1266 Returns C<{ patterns: { col: pattern } }> for stored date-normalisation
1267 patterns. Accepts C<?l=E<lt>specE<gt>>. A column with only a date pattern is
1268 reported as the pattern string; one with a time part as well is reported as
1269 C<{ date, time }>, plus C<as> when the normalised value is filed under a name
1270 of its own.
1271  
1272 =item C<POST /dates/save>
1273  
1274 Saves a date-normalisation pattern for a column. Body: C<l=&col=&pattern=>,
1275 plus optional C<time=> and C<as=>. Supported patterns: C<%m/%d/%Y> (US),
1276 C<%d/%m/%Y> (EU), C<%d-%b-%Y> (DD-Mon-YYYY). With C<time=> (C<%H:%M> or
1277 C<%H:%M:%S>) the column is normalised to a timestamp, C<2026-10-27T14:05:00>,
1278 which is what C<epoch()>, C<span()> and a C<last_24_hours> range can read;
1279 C<as=> names the column the normalised value is written to (default: the
1280 column itself). Without a time part the stored value is the date pattern
1281 string, unchanged, so no existing store needs migrating.
1282  
1283 =item C<POST /dates/delete>
1284  
1285 Removes a date-normalisation pattern. Body: C<l=&col=>.
1286 Omit C<col=> to clear all patterns for the spec.
1287  
1288 =item C<GET /lookups/list>
1289  
1290 Returns C<{ lookups: { name: { file, key, col, fields, default } } }> for the
1291 stored lookups of C<?l=E<lt>specE<gt>>; C<col>, C<fields> and C<default> appear
1292 only when they were given. See L</Stored lookups>.
1293  
1294 =item C<POST /lookups/save>
1295  
1296 Saves a lookup. Body: C<l=&name=&file=&key=>, plus optional C<col=>,
1297 C<fields=> and C<default=>. The file is read when it is saved, so a bad one is
1298 a 400 at once.
1299  
1300 =item C<POST /lookups/delete>
1301  
1302 Removes a lookup. Body: C<l=&name=>. Omit C<name=> to remove every lookup of
1303 the spec.
1304  
1305 =item C<GET /extract/list>
1306  
1307 Returns C<{ extractions: { name: { col, pattern, fields } } }> for the stored
1308 field extractions of C<?l=E<lt>specE<gt>>. See L</Field extraction>.
1309  
1310 =item C<POST /extract/save>
1311  
1312 Saves an extraction. Body: C<l=&name=&col=&pattern=>, plus optional
1313 C<fields=>. The pattern is compiled when it is saved, so a bad one is a 400 at
1314 once. The reply names the columns it will add: C<{ ok: 1, fields: [...] }>.
1315  
1316 =item C<POST /extract/delete>
1317  
1318 Removes an extraction. Body: C<l=&name=>. Omit C<name=> to remove every
1319 extraction of the spec.
1320  
1321 =item C<GET /geo/list>
1322  
1323 Returns C<{ columns: { col: { kind: "lat"|"lon"|"location"|"location_suffix" } } }>
1324 for the saved coordinate-column preferences of the given C<l=> spec, with
1325 C<loc_text> when the text added to each place is remembered too.
1326  
1327 =item C<POST /geo/save>
1328  
1329 Saves a coordinate-column preference. Body: C<l=&col=&kind=>,
1330 where C<kind> is C<lat>, C<lon>, C<location> or C<location_suffix>. C<col=> and
1331 C<kind=> may repeat in pairs, so a latitude and a longitude are saved in one
1332 request, and C<replace=1> forgets the spec's saved columns first. C<loc_text=>
1333 remembers the text added to each place (as C<loc_text=> on C</map>, and refused
1334 as it would be there). The map panel's "Remember columns" sends all of them,
1335 so a new choice replaces the old one; its "Forget remembered columns" calls
1336 C</geo/delete>.
1337  
1338 =item C<POST /geo/delete>
1339  
1340 Removes a coordinate-column preference. Body: C<l=&col=>.
1341 Omit C<col=> to clear all preferences for the spec, and its C<loc_text>.
1342  
1343 =item C<POST /geo/lookup>
1344  
1345 Looks up one place for the map page's progress bar, and saves the answer in
1346 the shared place cache at once. Body: C<place=&sig=>, where C<sig> is the
1347 signature the map page gave the place (any other place is refused with 403),
1348 plus C<online=0> to keep the lookup on this machine. Returns
1349 C<{ place, status, stored, online_failed, messages }>, where C<status> is
1350 C<found>, C<not_found>, C<held> (not looked up now, and not remembered) or
1351 C<refused>. See L</Maps>.
1352  
1353 =item C<POST /geo/boundary>
1354  
1355 Finds the outline of the area around one point, for the map page's progress
1356 bar, and remembers it at once. Body: C<point=&level=&sig=>, where C<level> is
1357 one that C<bounds=> takes,
1358 C<point> is C<lat,lon> rounded to three places and C<sig> the signature the map
1359 page gave it (any other point is refused with 403), plus C<online=0> to ask
1360 nothing. Returns C<{ point, status, stored, online_failed, name }>, where
1361 C<status> is C<found>, C<nowhere> (no such area there, such as the sea) or C<held>
1362 (not settled now, and not remembered).
1363  
1364 =item C<GET /insights>
1365  
1366 Automatic statistical insights for a dataset. Runs the same pipeline as
1367 C</join> then detects outliers (Tukey IQR fence), period-over-period deltas,
1368 top movers, and seasonality (lag-1 autocorrelation). No LLM or network call
1369 is made. Every insight links to a chart or stats view that shows it.
1370 Parameters: C<l=E<lt>specE<gt>> (required), repeatable C<f=> filters.
1371  
1372 =item C<POST /api/ask>
1373  
1374 Natural language to analysis spec (Phase 5.1). Body params: C<l=E<lt>specE<gt>>
1375 (required), C<q=E<lt>questionE<gt>> (required), repeatable C<f=> filters.
1376 Returns C<{ spec, url, valid =E<gt> 1 }> on success. The model receives only
1377 column names and types -- never raw row data or file paths. Returns 503 when
1378 C<ai_api_key> is not configured; 400 for missing params or a question over 500
1379 characters; 422 for an unparseable or invalid-column spec; 502 for a provider
1380 error; 429 once the hour's provider calls are used up (C<ai_calls_per_hour>,
1381 below).
1382  
1383 Every call spends C<ai_api_key>, so each server process makes at most
1384 C<ai_calls_per_hour> provider calls (default 60; C<0> for no limit) in any
1385 hour, counting C</api/ask> and C</api/summary> together. Like the other
1386 routes, both need the login when C<password_hash> is set.
1387  
1388 =item C<POST /api/summary>
1389  
1390 Narrative summary of an analysis (Phase 5.3). Body params: C<l=E<lt>specE<gt>>
1391 (required), repeatable C<f=> filters, C<ai=1> (optional, honours
1392 C<ai_api_key> config). Returns C<{ text, source, cached }>. Two paths:
1393 deterministic template sentences (always available, works offline) and
1394 optional LLM-polished prose when C<ai=1> is passed and C<ai_api_key> is
1395 set. Only aggregate insight facts are sent to the LLM. Results are cached
1396 in-process for one hour keyed on the analysis fingerprint. Once the hour's
1397 provider calls are used up (C<ai_calls_per_hour>), C<ai=1> gives the template
1398 text with C<source =E<gt> 'template_limited'>, not cached.
1399  
1400 =back
1401  
1402 =head2 Breadcrumbs and missing pages
1403  
1404 Every page shows where it is: Home, then each page between Home and this one,
1405 then this page, which is not a link. The trail is read from the page's own
1406 URL -- a chart's C<back=>, drilled rows' C<back2=>, a file's folder -- and each
1407 step is named from its own URL ("Bar chart: amount by region", "sales (region
1408 = North)"). Text from the URL is shown only if it is short and has no markup,
1409 a C<back=> to another site or scheme is not followed, and a chain of C<back=>
1410 links stops after eight steps.
1411  
1412 An address that matches no route, a missing table (C</view/:table>) and a
1413 missing canvas (C</a/:id>) answer C<404> with an HTML page that keeps the
1414 breadcrumb and the site navigation. The JSON API (C</api/...>) still answers
1415 a C<404> with a JSON body.
1416  
1417 A request that is refused -- a chart of a column the view does not have, a
1418 calculated field that does not compile -- answers C<400> with the reason as
1419 plain text. When a browser asked for the page (a C<GET> whose C<Accept> names
1420 C<text/html>), the reason is shown on the same page as a missing one instead,
1421 with the breadcrumb back to the table and a Back button. Scripts, C<fetch()>
1422 and C</api/...> routes still get plain text or JSON.
1423  
1424 =head2 Saved columns that cannot be applied
1425  
1426 Calculated fields, lookups and extractions are saved for a dataset and applied
1427 to every page of it. When the file changes under one -- a lookup file is
1428 deleted, a column an extraction reads is dropped -- its charts and exports
1429 refuse with the reason. The table page (C</view>, C</open>, C</join>,
1430 C</combine>) is still drawn: without that dataset's saved calculated fields,
1431 lookups and extractions, with a note that names the one at fault and buttons
1432 that open the panels to correct or delete it. A mistake in the request's own
1433 C<c=> is still a C<400>.
1434  
1435 =head2 Relative time ranges
1436  
1437 Every data route accepts a named window in place of a pair of dates:
1438  
1439 GET /view/sales?range=last_30_days&rcol=sale_date
1440 GET /a/mycanvas?range=this_quarter&rcol=order_date
1441  
1442 C<range=> names the window and C<rcol=> names the column it applies to. The
1443 window is worked out when the request arrives, so a link, a bookmark or a
1444 saved canvas keeps meaning the same thing whenever it is opened rather than the
1445 dates it happened to resolve to when it was written. The vocabulary is
1446  
1447 last_24_hours the 24 hours ending now, to the second
1448 today, yesterday
1449 last_7_days, last_30_days, last_90_days including today
1450 this_month, last_month
1451 this_quarter, last_quarter
1452 this_year, last_year
1453  
1454 A C<this> period ends today; the completed one is C<last_month>,
1455 C<last_quarter> and so on.
1456  
1457 The range is applied as two ordinary filters on that column --
1458 C<< col:ge:lo >> and C<< col:le:hi >> -- so the table view, every chart, the
1459 pivot, the column statistics, the insights page, the exports and a saved canvas
1460 all show the same rows, and one chip in the toolbar names the window with an
1461 C<x> to remove it. Filters the reader wrote are untouched: the range travels in
1462 the URL as itself, so submitting a panel form or reopening a link does not turn
1463 it into frozen dates.
1464  
1465 The table page offers Time range in its filter bar only when one of the columns
1466 on the page holds dates or date-times (C<YYYY-MM-DD>, the same with a time after
1467 C<T> or a space, or C<M/D/YYYY>) in every non-empty cell, and its column menu
1468 lists only those columns. A range already in force stays in the bar, so it can
1469 be changed or removed.
1470  
1471 A window narrower than a day (C<last_24_hours>) is compared to the second, so
1472 it is exact only on a column that holds a time as well as a date. A
1473 day-granular window compared against a column of timestamps covers each day it
1474 reaches in full, which is what a date filter does on its own as well.
1475  
1476 The filter bar offers the same windows: choose one and the column it applies
1477 to. Entries whose window falls entirely outside the data are disabled, with the
1478 column's own earliest and latest value -- from C<GET /api/range> -- in the
1479 tooltip, so a window that can only show nothing says so before it is chosen.
1480 An unknown C<range=> is a 400 rather than a silently unfiltered view, and a
1481 range with no C<rcol=> is a 400 as well.
1482  
1483 On a saved canvas the range narrows every card, and a card added while one is
1484 active is drawn through it: C<query> in C<POST /api/analyses/:id/visuals>
1485 carries C<range=>/C<rcol=> as it carries C<cf=>.
1486  
1487 =head2 Time buckets
1488  
1489 The aggregating routes bucket the dimension they already take:
1490  
1491 GET /bar?l=table:sales&cat=at&val=amount&span=1h
1492 GET /pivot?l=table:sales&rows=at&m=amount:sum:total&span=1mon
1493 GET /view/sales?span=1d&tcol=at
1494 GET /graph?l=table:sales&x=at&y=amount&span=1h&agg=sum&series=region
1495  
1496 The chart and pivot panels carry a C<Time bucket> menu for it, and the line
1497 graph panel an C<Aggregate> menu beside it and a C<Lines by> menu, which
1498 sends C<series=>.
1499  
1500 C<span=> takes a count and one of C<s>, C<m>, C<h>, C<d>, C<w>, C<mon>, C<q>
1501 or C<y> -- C<15m>, C<6h>, C<2d>, C<3mon>, C<1q> -- and is refused, naming the
1502 interval and the parameter, when the count is zero or the unit is not one of
1503 those. It expands into the calculated field a reader could have typed,
1504 C<< <col>_span:span(<col>,'1h') >>, so there is one pipeline and one set of
1505 semantics; C<tcol=> names the column where the route has no single dimension or
1506 names more than one, and C<as=> names the bucket column. C<tcol=> without a
1507 C<span=>, an unknown column, a name that is already a column and a C<span=> that
1508 disagrees with the reader's own calculated field are each a 400.
1509  
1510 Labels are ISO at the bucket's own resolution -- C<2026-10-27T14:00:00>,
1511 C<2026-10-27>, C<2026-10-01> -- so they sort chronologically as strings and a
1512 bucketed chart comes out in the right order with no second sort. C<d>, C<w>,
1513 C<mon>, C<q> and C<y> are computed from the local calendar, so a daylight-saving
1514 day is one bucket and a leap day is its own date; C<s>, C<m> and C<h> floor the
1515 interval out of the epoch. A value that cannot be read as a time lands in one
1516 visible C<(unparseable)> bucket rather than disappearing.
1517  
1518 C<agg=> on C</graph> is the timechart: one point per bucket, aggregated with
1519 the measure vocabulary a pivot's C<m=> uses (C<sum>, C<avg>, C<min>, C<max>,
1520 C<count>, C<count_distinct>, C<median>, C<stdev>, C<first>, C<last>,
1521 C<range>, C<pE<lt>NE<gt>>). Without C<agg=> every row is still plotted.
1522  
1523 The same bucket is available by hand, because it is a calculated field:
1524 C<?c=hour:span(at,'1h')>. The timestamp functions are C<epoch(v[, fmt])>,
1525 C<hour(v)>, C<minute(v)>, C<second(v)> and C<span(v, interval)>; see
1526 L<Database::BI::Calc> for the shapes each reads and the local-time rule.
1527  
1528 =head2 Cross-row columns
1529  
1530 Every data route, C</export> and a saved canvas accept a cross-row plan: a
1531 column worked out from many rows and written beside each one.
1532  
1533 cs=<column>:<function>:<alias>[:<count>] repeatable
1534 by=<column>[,<column>...] partition (optional)
1535 order=<column>[:asc|desc] the order the rows are read in
1536  
1537 C<pct_of_total>, C<rank> and C<zscore> need no order. C<running_total>,
1538 C<running_count>, C<running_pct>, C<window_sum>, C<window_avg>, C<lag>,
1539 C<delta> and C<pct_change> need C<order=>; only C<window_sum> and
1540 C<window_avg> take the C<count>, the width of the window. The pass runs after
1541 the filters and before pagination, so page 2 continues page 1's running total.
1542 An unknown function or column, or a parameter where none is taken, is a 400.
1543 A calculated field can read the new column, as in
1544 C<c=half:ytd/2>, and C<cs=> can read a calculated field or a time bucket, as in
1545 C<span=1mon&tcol=at&order=at_span&cs=amount:running_total:ytd>. A filter runs
1546 before the pass, so a window is over the rows it leaves, unless it names a
1547 column the pass writes: C<f=ytd:gt:50> runs last, and selects rows without
1548 changing their totals. On a canvas, a card's own filters and a cross-filter
1549 follow the same rule.
1550 The table page's Cross-row panel builds the same parameters. See
1551 L<Database::BI::Controller::Dashboard/Cross-row columns> for the full rules.
1552  
1553 =head2 Stored lookups
1554  
1555 A lookup adds columns to every row of a dataset from a second file, matched on
1556 one key: a shop code in the orders gains the shop's city and region.
1557  
1558 POST /lookups/save l=table:orders&name=shops&file=lookups/shops.csv
1559 &key=code&col=shop&fields=city,region&default=unknown
1560  
1561 C<file=> is a data file under C<data_dir> (a relative path is read from there),
1562 of at most 8 MiB; a file outside it, a symlink that leads outside it, a URL and
1563 a remote path are refused. C<key=> is the lookup file's key column and C<col=>
1564 the dataset's (default: the same name). C<fields=> lists the columns to add
1565 (default: all but the key). Keys are compared as text after trimming spaces,
1566 and case matters. When the file has a key twice, the first row is used and the
1567 log says so. A row whose key is not in the file gets C<default=>, or nothing.
1568  
1569 A field keeps its own name unless the dataset already has a column of that
1570 name; it is then called C<E<lt>nameE<gt>_E<lt>fieldE<gt>> (C<shops_region>). A
1571 source column is never overwritten.
1572  
1573 The table page's Lookups panel saves, lists and deletes them, and can skip one
1574 in the current view. Stored lookups apply on every route, a canvas and
1575 C</export>, before calculated fields and filters, so either can read the new
1576 columns. A total
1577 grouped or filtered by one is worked out in Perl, never sent to SQL. For one request,
1578 C<nolk=E<lt>nameE<gt>> skips a stored lookup, and C<lk=E<lt>nameE<gt>> applies
1579 a lookup stored for another dataset. Both repeat, and the panels carry them on.
1580 A lookup is not a join: for more than one key, or rows that match many rows,
1581 use Merge.
1582  
1583 =head2 Accelerated datasets
1584  
1585 A large CSV, TSV, PSV, XLSX or XML file can be read from a SQLite copy of
1586 itself, an I<extract>, which is faster to page through and lets totals be
1587 worked out in SQL. C<script/bi-extract --spec table:sales> marks the dataset
1588 accelerated and builds the extract under C<E<lt>model_dirE<gt>/extracts/>, or in
1589 the cache directory set (see L</Where caches are kept>).
1590  
1591 An extract is used only while it matches the file: its name is a fingerprint
1592 of the spec and the file's modification time and size. Once the file changes,
1593 the file itself is read, and the table page says the extract is stale and how
1594 to rebuild it. Stale numbers are never shown. The table page also says when
1595 a dataset is read from its extract, and when that was built.
1596  
1597 An extract is a cache. Deleting its folder loses nothing: each accelerated
1598 dataset reads its file until the next build. Nothing is written under
1599 C<data_dir>, and a C<model_dir> inside it is refused. Only a C<table:> or
1600 C<path:> spec naming a local file can be accelerated; a SQLite file is one
1601 already. C<table:sales> and C<path:/data/sales.csv> are separate datasets, each
1602 accelerated on its own.
1603  
1604 =head2 Field extraction
1605  
1606 A regular expression can pull values out of a column. For one value, use
1607 C<rx()> in a calculated field:
1608  
1609 c=country:rx(ref,'^([A-Z]{2})-','1')
1610  
1611 To make several columns from one pattern, store an extraction. Each named
1612 group, C<(?E<lt>nameE<gt>...)>, becomes a column:
1613  
1614 POST /extract/save l=table:invoices&name=parts&col=ref
1615 &pattern=^(?<country>[A-Z]{2})-(?<year>\d{4})-
1616  
1617 C<fields=country> keeps only the groups it names. The table page's Extract
1618 fields panel saves, lists and deletes them. Stored extractions apply on
1619 every route, a canvas and C</export>, after the lookups and before calculated
1620 fields and filters, so either can read the new columns. A row the pattern does
1621 not match gets C<(unparseable)> in each column, as a calculated field's row
1622 does, so those rows group visibly instead of vanishing; they are not blank. A
1623 group that took no part in a match is empty. Columns are named as a lookup's
1624 are: the group's own name, or C<E<lt>nameE<gt>_E<lt>groupE<gt>> when the
1625 dataset has a column of that name. A capture is cut to 200 characters.
1626  
1627 A pattern is refused when it is over 200 characters, when it does not compile,
1628 or when it uses C<(?{>, C<(??{>, C<(?p> or C<(*>, which run code or steer the
1629 engine. These checks are not a sandbox. Perl's regular expressions have no
1630 timeout, so a pathological pattern such as C<(a+)+$> stalls the request that
1631 uses it. Patterns are entered by whoever runs the server, never by a remote
1632 party. See L<Database::BI::Calc/Regular expressions>.
1633  
1634 =head1 CONFIGURATION
1635  
1636 Place a C<database_bi.conf> file in the application root to override
1637 defaults:
1638  
1639 {
1640 data_dir => 'data', # directory scanned for data files on the home page
1641 uploads_dir => '.uploads', # staging directory for uploaded files
1642 platform => 'web', # VWF template dimension
1643 language => 'en', # VWF template dimension
1644  
1645 # Browser-side libraries. d3_url overrides the chart and canvas
1646 # script; the leaflet_* keys override the map assets, and tile_url
1647 # overrides the tile server. See "Self-hosting D3 and Leaflet"
1648 # below.
1649 d3_url => 'https://cdnjs.cloudflare.com/ajax/libs/d3/7.9.0/d3.min.js',
1650 }
1651  
1652 C<uploads_dir> is where C<POST /upload> stages the files a user drags onto the
1653 page, and the directory C<POST /uploads/clear> empties. It defaults to
1654 C<.uploads> under the application home. A relative value resolves against the
1655 application home, an absolute one is used as given, so a deployment whose
1656 application directory is read-only can stage uploads somewhere writable:
1657  
1658 { uploads_dir => '/var/tmp/database-bi-uploads' }
1659  
1660 =head2 Where caches are kept
1661  
1662 The places OpenStreetMap found for maps, the extracts of accelerated datasets
1663 (see L</Accelerated datasets>), the page cache when C<page_cache_dir> turns it
1664 on, and the table cache when C<< cache => { driver => 'File' } >> (or
1665 C<FastMmap>) asks for one, are kept on disc. Each object that keeps one
1666 chooses its directory when it is made (L<Database::BI::CacheDir>), from the
1667 first of these that is set:
1668  
1669 =over 4
1670  
1671 =item 1. C<cache_dir> through L<Object::Configure>, for the class making the
1672 cache: its config files, then the environment variable
1673 C<E<lt>ClassE<gt>__cache_dir> (C<Database__BI__Model__Geocode__cache_dir> for
1674 the places, C<Database__BI__Extract__cache_dir> for the extracts,
1675 C<Database__BI__cache_dir> for the page and table caches);
1676  
1677 =item 2. C<$ENV{CACHEDIR}>;
1678  
1679 =item 3. C<$ENV{CACHE_DIR}>;
1680  
1681 =item 4. C<cache_dir> here (relative: under the application home):
1682  
1683 { cache_dir => '/var/cache/database-bi' }
1684  
1685 =item 5. F<E<lt>model_dirE<gt>/geocode-cache> for the places,
1686 F<E<lt>model_dirE<gt>/extracts> for the extracts, C<page_cache_dir> for the
1687 page cache, F<E<lt>model_dirE<gt>/cache> for the table cache.
1688  
1689 =back
1690  
1691 Caches sharing a directory each keep to their own namespace in it; the
1692 extracts go in its F<database-bi-extracts/> folder. A cache directory inside
1693 C<data_dir> is not used for the extracts, which then stay in C<model_dir>: each
1694 is a C<.db> file the home page would list. C<page_cache_dir> still decides
1695 whether pages are cached at all (see L</Compression and the page cache>): a
1696 cache directory set only says where. A C<< cache => { root_dir } >> names the
1697 table cache's directory outright. C<script/bi-geocode> and
1698 C<script/bi-extract> read the same settings, and F<database_bi.conf> from
1699 C<MOJO_CONFIG> or the current folder (C<bi-extract> through the application).
1700  
1701 =head2 Who can reach the server
1702  
1703 A server started by C<script/database-bi> (with no arguments, a database, or
1704 C<daemon> or C<prefork>) listens on C<http://127.0.0.1:3000>, so only this
1705 machine can reach it: unless a password is set (see L</Logging in>), there
1706 is no login, and Mojolicious on its own would listen on every interface.
1707 C<listen> changes that:
1708  
1709 { listen => 'http://127.0.0.1:8000' } # another port, still this machine only
1710 { listen => 'http://*:3000' } # every machine that can reach this one
1711 { listen => ['http://127.0.0.1:3000', 'http://[::1]:3000'] } # IPv6 loopback too
1712  
1713 It takes a location, several separated by commas, or a list. A location
1714 that is not C<http://> or C<https://> stops the start. C<MOJO_LISTEN> and the
1715 C<-l> option of C<daemon> and C<prefork> still win over it.
1716 C<morbo script/database-bi> opens its port before it loads the application, so
1717 it does not read C<listen>; give it C<-l>, or run C<script/database-bi>.
1718  
1719 Anywhere but this machine needs a password: a C<listen> (or C<MOJO_LISTEN>, or
1720 C<-l>, or under hypnotoad its own C<listen>) that is not loopback stops the start
1721 unless C<password_hash> is set (see L</Logging in>). The message says what to
1722 change. The defaults are loopback, so they start as before.
1723  
1724 C<hypnotoad> reads its own C<< hypnotoad => { listen } >>, which defaults to
1725 C<http://127.0.0.1:8080>, this machine only:
1726  
1727 { hypnotoad => { listen => ['http://*:8080'] } } # every machine
1728  
1729 Behind a reverse proxy on the same machine, leave both at their defaults. The
1730 proxy can still bring other machines' requests in, so without a password a
1731 request from an address that is not loopback is refused (C<403>), including one
1732 a trusted proxy names in C<X-Forwarded-For>. For the public, set a password.
1733  
1734 B<This machine is not one person.> Loopback keeps other machines out, not
1735 other people on this one: any account on the same machine, or a container that
1736 shares its network, can reach C<127.0.0.1:3000>, and read, list and save files
1737 as the account running the server. On a machine with other users, set a
1738 password even when it listens on this machine only.
1739  
1740 =head2 Which folders it may use
1741  
1742 C</browse>, C</open>, the Export panel's folder list (C</api/dirs>), a C<path:>
1743 data source anywhere (a table, a chart, a merge, a canvas card) and
1744 C<POST /export> reach the whole filesystem, as far as the account running the
1745 server can. C<file_roots> fences them in:
1746  
1747 { file_roots => ['/srv/reports', 'shared'] } # 'shared' is under the application home
1748  
1749 C<data_dir> and C<uploads_dir> are always among them. Browsing starts at the
1750 home folder if it is inside, else at the first root, and stops at the roots. A
1751 folder or file outside is refused (C<403>, or a C<path:> source is not found),
1752 whether or not it is there, so the refusal says nothing about what is outside;
1753 a link inside that leads outside is outside. A path that climbs out with C<..>
1754 past what exists is refused too. A root that is not a folder that exists stops
1755 the start. Remote files (C</../host/...>), Redis and MariaDB are not files on
1756 this machine, and are not affected; neither are the command-line tools.
1757  
1758 Saving is the riskier half: an export replaces a C<.csv>, C<.json> or C<.sql>
1759 file of the same name, and some such files are settings another program obeys
1760 (a project's F<package.json> names commands that C<npm> runs). A server other
1761 people use keeps exports to folders of their own, so with C<password_hash> set,
1762 C<export_dirs> is required, and the start stops without it:
1763  
1764 { export_dirs => ['/srv/reports/exports'] } # a relative one is under the application home
1765  
1766 C<POST /export> then saves only in them (or below them), and the Export panel
1767 opens on the first and lists no other. Reading is unaffected: that is
1768 C<file_roots>. An export folder that does not exist, is outside C<file_roots>
1769 or is a dot-folder stops the start. Whatever is set, an export never replaces
1770 a link, a folder or anything else that is not a plain file, so a link inside
1771 the allowed folders cannot carry it outside them; it is written beside its name
1772 and renamed into place, so nobody reads half a file, and a file it replaces
1773 keeps its permissions.
1774  
1775 =head2 Requests from other sites
1776  
1777 Unless a password is set (see L</Logging in>), there is no login: whatever can
1778 reach the server can read any file it can (C</open>) and write exports into
1779 any folder it can (C<POST /export>). Even with one, a logged-in reader's
1780 browser carries the login to every request it sends here. Listening
1781 on this machine only keeps other machines out, but not the pages of other
1782 sites open in the reader's browser. So every request is checked first, and
1783 refused with C<403> when another site's page made it:
1784  
1785 =over 4
1786  
1787 =item * A write (any method but C<GET>, C<HEAD> and C<OPTIONS>) is refused when
1788 the browser's C<Sec-Fetch-Site> says it came from another site, or, without
1789 that header, when its C<Origin> is not this server. A form posted from
1790 another site needs no permission from this one, so this is what stops it. A
1791 script such as C<curl> sends neither header and is let through.
1792  
1793 =item * Any request is refused when its C<Host> is a name other than
1794 C<localhost> or C<*.localhost>, and is not an IP address. A page whose own
1795 name has been made to resolve to C<127.0.0.1> (DNS rebinding) counts as this
1796 server to the browser, but it still sends its own name. To reach the server
1797 by a name, list it:
1798  
1799 { allowed_hosts => ['bi.example.com', '*.corp.example'] } # '*' for any name
1800  
1801 Behind a trusted reverse proxy, the C<Host> is whatever the proxy sends, so it
1802 is checked only when C<allowed_hosts> is set; set it there too.
1803  
1804 =back
1805  
1806 C<POST /export> also refuses a folder or file whose name starts with a dot
1807 (F<~/.config>, F<.vscode/settings.json>), since those hold other programs'
1808 settings. The folder list in the Export panel leaves them out already.
1809  
1810 =head2 Which addresses it may fetch
1811  
1812 C</import> and a C<url:> data source make the server fetch a URL, so a page
1813 could point it at what only the server can reach: a service on this machine, a
1814 database on the office network, or a cloud's metadata service on
1815 C<169.254.169.254>, which hands out its credentials. So the server refuses a
1816 URL that leads to this machine, a private or shared network
1817 (C<10.0.0.0/8>, C<172.16.0.0/12>, C<192.168.0.0/16>, C<100.64.0.0/10>,
1818 C<fc00::/7>), link-local addresses, multicast or a reserved range.
1819  
1820 It is what the name I<resolves to> that counts, not how the URL reads:
1821 C<http://localtest.me/> and C<http://127.0.0.1.nip.io/> are names whose DNS
1822 answers C<127.0.0.1>, and C<http://2130706433/> or C<http://0x7f000001/> are
1823 C<127.0.0.1> written another way; all are refused. An address is looked up
1824 once, checked, and that address is the one connected to, so a name that answers
1825 differently the second time (DNS rebinding) gains nothing. Each redirect is
1826 checked the same way, and at most 5 are followed. Over C<https> the
1827 certificate must still be the site's. The refusal says why, for example
1828 C<localtest.me is 127.0.0.1, which is this machine>.
1829  
1830 To read from an intranet site, name it:
1831  
1832 { url_private_hosts => ['reports.corp.example', '*.corp.example'] }
1833  
1834 Those names may resolve to a private address; every other name is still
1835 checked, and an address written as such (C<http://10.1.2.3/>) is never let
1836 through. A name that is not a host name, or C<*> alone, stops the start.
1837 This check is not a firewall: where the server's machine can reach something it
1838 should not, rules on outgoing connections are the stronger defence.
1839  
1840 =head2 Logging in
1841  
1842 With C<password_hash> set, every page asks for a password first. A server
1843 other machines can reach must have one (see L</Who can reach the server>); on
1844 this machine alone it is optional. Make the line with
1845  
1846 script/database-bi password
1847  
1848 which asks for the password twice (without showing it) and prints
1849  
1850 password_hash => 'pbkdf2-sha256$200000$...',
1851  
1852 to put in C<database_bi.conf>. Only the hash is kept: PBKDF2-HMAC-SHA256 with
1853 a random salt (L<Database::BI::Password>). A plain password there stops the
1854 start, so it is never left in the file by mistake. To change the password,
1855 make a new line; every session is then logged out.
1856  
1857 There is one password, not one per person. A browser asking for a page is
1858 sent to C</login> and, once the password is right, back to that page; any other
1859 request (a script, a panel's request, a download) gets C<401> until it carries a
1860 logged-in session. C<POST /logout>, the Log out button at the top of each page,
1861 ends it. C</share/:id> and C</embed/:id> need no login: their signed, expiring
1862 token is their permission, so anyone holding the link sees that canvas, and
1863 only that one, for 30 days. The canvas itself (C</a/:id>) and the rest still
1864 ask for the password.
1865  
1866 The token is signed with C<share_secret> when it is set (at least 16
1867 characters), else with a key derived from C<secrets>. Without either, the key
1868 is new at each start, so a restart ends every share link, and the Share panel
1869 says so; set C<secrets> (which keeps logins too) or C<share_secret> to keep
1870 them. Changing either ends the links made with the old one. Before 0.021.0 a
1871 missing C<share_secret> meant a fixed key, the same on every install, with which
1872 anyone could sign a link to any canvas; that key in C<share_secret> stops the
1873 start.
1874  
1875 {
1876 password_hash => 'pbkdf2-sha256$200000$...',
1877 export_dirs => ['/srv/reports/exports'], # required with a password
1878 login_expiration => 8 * 60 * 60, # seconds idle before logging out; the default
1879 secrets => ['a long random string'], # or each restart logs everyone out
1880 }
1881  
1882 The session is a cookie signed with C<secrets>: C<HttpOnly>, C<SameSite=Lax>,
1883 and C<Secure> whenever the request came over https (directly, or through a
1884 trusted proxy that says so), so it is never sent back over plain http. Over
1885 plain http anyone on the network path can read the password and the cookie: a
1886 server other machines reach should be behind https. Ten wrong passwords from
1887 one address within 15 minutes lock that address out for the rest of the 15
1888 minutes (C<429>); each server process counts its own.
1889  
1890 =head2 Time zones
1891  
1892 A timestamp that names its zone (C<2026-11-06T23:30:00Z>, C<...+01:00>) is read
1893 as written unless C<time_zone> is set. With it, such a value is moved to that
1894 zone's clock first, so the day and hour a filter, the Time range, a formula
1895 (C<hour>, C<minute>) and the C<span=> buckets see are the ones on that clock,
1896 and "today", "this month" and the other Time range presets are that zone's too.
1897 A value with no zone written is taken to be on that clock already, and a table
1898 still shows each cell as it was written.
1899  
1900 {
1901 time_zone => 'UTC', # or '-05:00', '+05:30', or 'local'
1902 }
1903  
1904 C<local> is the server's own zone, daylight saving included (set C<TZ> to
1905 change it). Named zones such as C<America/New_York> are not read: use C<local>
1906 with C<TZ>, or an offset. Anything else stops the start.
1907  
1908 =head2 MariaDB and MySQL servers
1909  
1910 A server is opened by name. Each entry of C<mariadb_servers> is one database:
1911  
1912 {
1913 mariadb_servers => {
1914 shop => {
1915 host => 'db.example.com', # default: localhost
1916 port => 3306, # optional
1917 database => 'shop', # required
1918 username => 'bi_reader',
1919 password => 'secret',
1920 },
1921 },
1922 }
1923  
1924 The home page then has a card for each name, leading to the list of its tables.
1925 C<mariadb:shop/orders> opens one anywhere a source is taken: the path field, C<l=>,
1926 C<j=>, C<c=> and a canvas's C<datasets>. C<mariadb:shop> lists them.
1927  
1928 The spec holds a name and no more, because a spec travels in URLs, bookmarks,
1929 shared links, saved canvases and server logs. So the password stays in the
1930 configuration file, which should be readable only by the account that runs the
1931 application, and no request can point the application at another server.
1932  
1933 L<DBD::MariaDB> is recommended; L<DBD::mysql> serves if it is the one installed.
1934 Without either, opening a server says so and the rest of the application is
1935 unaffected. Rows are read from the server each time, and never cached. The tests
1936 are C<t/mariadb.t>, which mocks the server, and C<t/mariadb_live.t>, which runs when
1937 C<MARIADB_SERVER> is set, for example to C<mariadb://user:pass@host/test>, and which
1938 creates its own tables and drops them.
1939  
1940 =head2 Compression and the page cache
1941  
1942 Every response goes through L<Mojolicious::Plugin::Buffer>: it is compressed
1943 (gzip or Brotli, as the browser accepts), HTML whitespace is minified (inline
1944 scripts and styles are left alone), and a C<200> to C<GET> or C<HEAD> carries
1945 an C<ETag>, so a repeat request can be answered C<304 Not Modified>. There
1946 is no C<Last-Modified>: the plugin would date a page by the code, not the data,
1947 which lets a browser reuse a stale reply without asking. File
1948 downloads (C</export> as CSV, SQLite or JSON, the pivot as XLSX, and a canvas
1949 card's data from C</a/:id/visual/:n/:fmt>) opt out and are sent as they are.
1950  
1951 Two optional keys keep finished pages on disc:
1952  
1953 {
1954 page_cache_dir => '/var/cache/database-bi', # relative: under the application home
1955 page_cache_duration => '5 minutes', # the default
1956 }
1957  
1958 When C<page_cache_dir> is set, C</catalog> and C</tutorial> are stored in a
1959 L<CHI> File cache there (or in the cache directory set: see
1960 L</Where caches are kept>), one copy per C<Accept-Language>, and served from it
1961 until they expire. No other page is cached, because the rest read data files
1962 that can change between requests. Without the key nothing is cached.
1963  
1964 =head2 Self-hosting D3 and Leaflet
1965  
1966 The chart pages load D3 from a public CDN by default, and the map pages load
1967 Leaflet and leaflet.markercluster from unpkg. A deployment with no outbound
1968 network access, or one that prefers to serve its own assets, sets the URLs in
1969 C<database_bi.conf>:
1970  
1971 {
1972 d3_url => '/static/d3/d3.min.js',
1973 leaflet_js_url => '/static/leaflet/leaflet.js',
1974 leaflet_css_url => '/static/leaflet/leaflet.css',
1975 leaflet_cluster_js_url => '/static/leaflet/leaflet.markercluster.js',
1976 leaflet_cluster_css_url => '/static/leaflet/MarkerCluster.css',
1977 leaflet_cluster_default_css_url => '/static/leaflet/MarkerCluster.Default.css',
1978 tile_url => 'https://tiles.internal/{z}/{x}/{y}.png',
1979 }
1980  
1981 An absolute path is served like any other static file: put the library under
1982 the application's C<public/> directory, so C</static/d3/d3.min.js> is
1983 C<public/static/d3/d3.min.js>. The five Leaflet keys may be set on their own;
1984 any left out keeps L<HTML::OSM>'s pinned CDN URL. Use a path beginning with
1985 C</>, or a full URL; a path without the leading slash is relative to the page. The versions to copy are the
1986 ones the defaults name: D3 7.9.0, Leaflet 1.9.4, and leaflet.markercluster 1.5.3.
1987 C<tile_url> points the map layer at a self-hosted tile server instead of
1988 OpenStreetMap. It keeps Leaflet's C<{z}>, C<{x}> and C<{y}> placeholders, and
1989 C<{s}> too if the server uses subdomains. Set it, and C<map_geocode_online>
1990 to 0, and every request needed to draw a map can stay on the local network. The OpenStreetMap attribution stays
1991 on the map, since it is the usual credit for OSM-derived tiles. There is no
1992 in-page place search: L<HTML::OSM> is always constructed with C<search =E<gt> 0>,
1993 so nothing typed on a map page is sent anywhere.
1994  
1995 Map-specific config keys: C<map_geocode_max> (new geocoder lookups per request,
1996 default 500), C<map_geocode_online> (0 keeps geocoding on this machine: a place
1997 the local data does not know is not sent to OpenStreetMap's Nominatim, nor a
1998 marker's position for its outline; default 1), C<map_geocode_online_max>
1999 (places, and outlines, asked of Nominatim per request, default 20;
2000 at one a second, the rest are left for the next request or for
2001 C<script/bi-geocode>; the map page's progress bar asks one place a request, so
2002 it reaches every place), C<secrets> (a list; the first signs the places a map
2003 page lists for C<POST /geo/lookup>. Without it each start makes a random one), C<map_max_markers> (markers per request, default 2000), C<map_popup_rows>
2004 (rows listed in one marker's popup, default 10),
2005 C<map_region> (a two-letter country hint for ambiguous places),
2006 C<map_bounds_ranks> (the place rank that is a county, by country; see above), C<map_max_zoom>
2007 (the default tile-layer maxZoom) and C<tile_sources> (a hashref of named tile
2008 sources, each C<< { url =E<gt> ... } >>, selected with C<tiles=>).
2009  
2010 B<Map colour rules.> C<color=> names the column and C<color_rule=> supplies
2011 C<< E<lt>opE<gt>:E<lt>valueE<gt>:E<lt>colourE<gt> >> rules; they are tried in
2012 the order given and the first match wins. The operators are C<gt>, C<ge>,
2013 C<lt>, C<le>, C<eq> and C<ne>; a comparison is numeric when both the cell and
2014 the rule's value look like numbers, and otherwise only C<eq>/C<ne> are
2015 meaningful (case-insensitive). A colour is C<#rgb>, C<#rrggbb> or a CSS name
2016 such as C<red> or C<teal>. A value that matches no rule gets C<color_default=>,
2017 which the legend shows as "Other". C<series=> is the categorical
2018 alternative: each distinct value takes the next colour from C<scheme=>,
2019 cycling through the palette, and the legend lists the categories. C<color=>
2020 and C<series=> are mutually exclusive.
2021  
2022 =head2 Content-Security-Policy
2023  
2024 Every HTML page is sent with a C<Content-Security-Policy> header. The pages
2025 show cells from files this application did not write, so the policy backs up
2026 the escaping. Scripts, stylesheets and images may come only from this site
2027 and from the hosts that C<d3_url>, the C<leaflet_*_url> keys, C<tile_url> and
2028 C<tile_sources> name. The defaults allow cdnjs.cloudflare.com, unpkg.com and
2029 OpenStreetMap's tile servers. A page's scripts may talk only to this site
2030 (C<connect-src 'self'>), and no other site may show a page in a frame
2031 (C<frame-ancestors 'self'>). JSON replies and downloads carry no policy.
2032  
2033 Every HTML page also carries C<X-Frame-Options: SAMEORIGIN>, whatever the
2034 policy keys below say. A report-only policy only reports C<frame-ancestors>,
2035 a policy written out in full may leave it out, and older browsers read only
2036 this header, so framing by another site is refused in each of those cases.
2037  
2038 Every reply carries C<Referrer-Policy: strict-origin-when-cross-origin>. A
2039 request a page starts sends its whole URL to this site, only the origin to
2040 another, and nothing from https to http. Specs, filter values and share
2041 tokens travel in the query string, and an older browser's default would send
2042 all of it to the CDNs, the tile servers and any site a reader follows a link
2043 to. It is not C<no-referrer>, because OpenStreetMap's tile policy asks pages
2044 for a C<Referer>.
2045  
2046 Every reply also carries C<X-Content-Type-Options: nosniff>, so a browser
2047 takes it for what its C<Content-Type> says and never guesses. A guess could
2048 read a CSV export, or text from a data file, as HTML or script. A
2049 self-hosted library under C<public/> keeps working, because Mojolicious names
2050 C<.js> and C<.css> files for what they are; one served some other way must be
2051 sent as C<text/javascript> or C<text/css>, or the browser will not load it.
2052  
2053 Every page carries C<Cross-Origin-Opener-Policy: same-origin>: a window that
2054 another site opened, or that a page opened on another site, gets no handle on
2055 the page through C<window.opener>. No page opens a window or reads an
2056 opener, and every link to a new window is C<rel="noopener">.
2057 C<cross_origin_opener_policy> sets another of C<same-origin>,
2058 C<same-origin-allow-popups>, C<noopener-allow-popups> and C<unsafe-none>, or
2059 C<''> or C<0> for none; any other value stops the application at startup. No
2060 C<Cross-Origin-Embedder-Policy> is sent: it would refuse the libraries and
2061 tiles the CDNs and OpenStreetMap serve, and nothing here needs the isolation
2062 it gives.
2063  
2064 Every reply carries a C<Permissions-Policy> that turns off the browser
2065 features no page uses: the camera, the microphone, location, payment, USB,
2066 serial and HID devices, screen capture, full screen, reading the clipboard and
2067 the rest, for this site and any frame it holds. Writing to the clipboard
2068 stays (C<clipboard-write=(self)>), for the Copy link buttons. A script that
2069 got in cannot ask the reader for any of them. C<permissions_policy> replaces
2070 the value (C<''> or C<0> for none); one that cannot be a header value stops
2071 the application at startup:
2072  
2073 { permissions_policy => 'camera=(), geolocation=(self)' }
2074  
2075 A reply to a request that came over https carries
2076 C<Strict-Transport-Security: max-age=31536000>, so the browser comes back over
2077 https for a year. It binds this host only; set C<strict_transport_security>
2078 to add C<includeSubDomains> or C<preload>, which reach every site of the
2079 domain and are hard to take back, or to C<''> or C<0> to send none. A value
2080 a browser would not read stops the application at startup:
2081  
2082 { strict_transport_security => 'max-age=63072000; includeSubDomains' }
2083  
2084 Over http no such header is sent, since a browser ignores it there, and none
2085 is sent to C<localhost> or to an IP address: it binds the host, not the port,
2086 so from C<https://localhost:8443> it would send every other server on that
2087 machine to https, and browsers ignore it for an address. Behind a proxy that
2088 ends TLS, a request is https only when Mojolicious is told to trust the proxy
2089 (C<MOJO_REVERSE_PROXY=1>, or C<< hypnotoad => { proxy => 1 } >>) and the proxy
2090 sends C<X-Forwarded-Proto: https>; otherwise the proxy must send the header
2091 itself.
2092  
2093 An inline script runs only if it carries the request's nonce, a random value
2094 made for each request and named in the policy (C<'nonce-...'>). Every
2095 C<E<lt>scriptE<gt>> the templates write carries it, and so do those that
2096 L<HTML::D3> (0.30 or later) and L<HTML::OSM> (0.14 or later) write, because
2097 the application passes it to them. A script that came in with a cell's text
2098 cannot know it, so it does not run; nor does an C<onclick> or C<onerror>
2099 attribute, which no nonce can cover, so the pages use none. Style attributes
2100 are still allowed (C<style-src 'unsafe-inline'>).
2101  
2102 A canvas card added without a reload arrives as JSON with the nonce its
2103 scripts were written with. The page runs only the scripts that carry it, and
2104 gives each the page's own nonce. A page kept in the page cache is stored with
2105 its header, so the nonce in each still matches when it is served again.
2106  
2107 Two keys change the policy:
2108  
2109 {
2110 content_security_policy_report_only => 1, # report breaches, block nothing
2111 content_security_policy => "default-src 'self'; script-src 'self' 'nonce-{nonce}'",
2112 }
2113  
2114 C<content_security_policy> is the whole policy, sent as written except that
2115 C<{nonce}> becomes the request's nonce; without it no inline script runs. Set
2116 to C<''> or C<0> it sends no header. A policy written out in full is not
2117 updated when the library keys change.
2118  
2119 =head3 Embedding a canvas on another site
2120  
2121 By default only pages of this site may show C</embed/:id> in a frame.
2122 C<embed_frame_ancestors> names other sites that may:
2123  
2124 { embed_frame_ancestors => [ 'https://intranet.example.com', 'https://*.corp.example' ] }
2125  
2126 Each entry is an origin: C<http> or C<https>, a host (a C<*> may stand for its
2127 first label only) and an optional port, with no path. Anything else stops the
2128 application at startup, because a security setting that does not do what it
2129 says should not be dropped quietly. The sites are added to that page's
2130 C<frame-ancestors>, and to no other page's. With a report-only policy, with
2131 none, or with one written out without C<frame-ancestors>, the page carries a
2132 second, enforced policy of C<frame-ancestors> alone, so naming one site never
2133 lets every site in. A policy written out with its own C<frame-ancestors> is
2134 left to say who may. C<X-Frame-Options: SAMEORIGIN> stays: browsers that know
2135 C<frame-ancestors> follow it instead, and those that know only the older
2136 header refuse the frame. The canvas's Share panel names the sites its embed
2137 code works on.
2138  
2139 =head1 METHODS
2140  
2141 =head2 startup
2142  
2143 Called once by Mojolicious when the application is loaded, by
2144 C<script/database-bi>, C<morbo>, C<hypnotoad> or C<< Test::Mojo->new('Database::BI') >>.
2145 It is not called directly.
2146  
2147 =head3 API SPECIFICATION
2148  
2149 =head4 INPUT
2150  
2151 $self # the Database::BI application object
2152  
2153 Configuration comes from C<database_bi.conf> in the application home, if it is
2154 there (see L</CONFIGURATION>), or from the hashref given to
2155 C<< Test::Mojo->new('Database::BI', { ... }) >>. Unset keys default to
2156 C<< data_dir => 'data' >>, C<< platform => 'web' >>, C<< language => 'en' >> and the
2157 public D3 URL.
2158  
2159 =head4 OUTPUT
2160  
2161 Nothing useful is returned. By the time it returns, the application has:
2162  
2163 =over 4
2164  
2165 =item * the login session (L<Database::BI::Sessions>), and C<require_login> in
2166 front of every route but the login, share and embed links (see
2167 L</Logging in>); a C<password_hash> that is not a hash, or a C<login_expiration>
2168 under 60 seconds, croaks; so does a C<listen> other machines could reach when
2169 there is no password, and a password without C<export_dirs>;
2170  
2171 =item * a C<file_roots> that is not a list of folders that exist croaks (see
2172 L</Which folders it may use>); so does a C<url_private_hosts> that is not a
2173 list of host names (see L</Which addresses it may fetch>);
2174  
2175 =item * the C<before_dispatch> hook that refuses requests from other sites (see
2176 L</Requests from other sites>); an C<allowed_hosts> that is not a list of host
2177 names croaks;
2178  
2179 =item * C<MOJO_LISTEN> set from C<listen> (default C<http://127.0.0.1:3000>) when it
2180 was unset, and C<< hypnotoad => { listen } >> defaulted to C<http://127.0.0.1:8080>
2181 (see L</Who can reach the server>); a C<listen> that is not a location croaks;
2182  
2183 =item * a 50 MiB limit on request bodies (an upload over it is answered C<413>);
2184  
2185 =item * Template Toolkit registered as handler C<tt>, and the Buffer plugin
2186 (see L</Compression and the page cache>);
2187  
2188 =item * the CHI cache for tables (the C<Memory> driver unless C<cache =E<gt> { driver }>
2189 names another; a C<File> or C<FastMmap> one is kept where L</Where caches are kept>
2190 says), and the page cache when C<page_cache_dir> is set;
2191  
2192 =item * the C<before_dispatch> hooks for relative time ranges, cross-row plans and
2193 the view context, and the C<before_render> hook that sets the breadcrumb, the help link
2194 and the HTML 404 page;
2195  
2196 =item * every route in L</ROUTES>.
2197  
2198 =back
2199  
2200 A configuration file that does not parse makes the C<Config> plugin croak, and
2201 the application does not start.
2202  
2203 =head1 COMMAND-LINE TOOLS
2204  
2205 The scripts in C<script/> are installed with the distribution, each with a
2206 manual page (C<man bi-extract>, C<man bi-geocode>, C<man bi-alert>,
2207 C<man database-bi>). The maintenance scripts use the same data and model
2208 directories as the web application, found from the folder they are run in or
2209 given with C<--data-dir> and C<--model-dir>, and are safe to run from cron.
2210  
2211 =head2 script/database-bi password
2212  
2213 Asks for a password (twice, without echo, at a terminal; once from a pipe) and
2214 prints the C<password_hash> line for C<database_bi.conf>. See L</Logging in>.
2215  
2216 =head2 script/bi-geocode
2217  
2218 Warms the shared geocode cache for one column, so later map requests make no
2219 lookups:
2220  
2221 ./script/bi-geocode --spec table:customers --col city \
2222 [--text TEXT] [--data-dir DIR] [--model-dir DIR] \
2223 [--openaddr PATH] [--region CC] [--dry-run] [--verbose]
2224  
2225 C<--text> is the map panel's I<Add to each place> (C<loc_text=>): with
2226 C<--col county --text 'Virginia, USA'> it looks up C<Accomack, Virginia, USA>,
2227 the place the map then asks for.
2228  
2229 It is idempotent: a second run against a warm cache resolves nothing and says
2230 so. Exit status is 0 on success, 1 when the column is missing or no rows load,
2231 and 2 on bad arguments or an unopenable source.
2232  
2233 =head2 script/bi-extract
2234  
2235 Builds the extracts of accelerated datasets (see L</Accelerated datasets>):
2236  
2237 ./script/bi-extract --spec table:sales [--spec ...] # accelerate, and build
2238 ./script/bi-extract --all # rebuild every one
2239 ./script/bi-extract --remove --spec table:sales # stop, and remove its extract
2240 ./script/bi-extract --list
2241 [--data-dir DIR] [--model-dir DIR]
2242  
2243 It prints a line for each extract it builds: the rows, the columns, the file
2244 and the time. Exit status is 0 on success, 1 when an extract could not be built
2245 (the others still are), and 2 on bad arguments. Run C<--all> from cron after
2246 the data files are refreshed.
2247  
2248 =head2 script/bi-alert
2249  
2250 Reports one or more saved analyses, and turns a crossed threshold into a
2251 non-zero exit status so cron can act on it:
2252  
2253 ./script/bi-alert --analysis ID [--analysis ID ...] \
2254 [--threshold MEASURE:OP:VALUE] \
2255 [--threshold ANALYSIS:MEASURE:OP:VALUE ...] \
2256 [--suppress DURATION] [--state-file PATH] [--recovery] \
2257 [--notify-cmd COMMAND] \
2258 [--data-dir DIR] [--model-dir DIR] [--dry-run]
2259  
2260 The digest goes to STDOUT and nothing leaves the machine unless
2261 C<--notify-cmd> says where: otherwise pipe it into mail, a webhook or a ticket
2262 creator yourself. Exit status is 0 when nothing is announced, 1 when a
2263 threshold is crossed and announced, 2 on error, and 3 when a crossing that was
2264 announced has ended and C<--recovery> was asked to announce that. C<--dry-run>
2265 reports without recording anything against the throttle and without running the
2266 delivery command.
2267  
2268 Both of those options may be repeated, so one run can watch several analyses
2269 and several measures:
2270  
2271 ./script/bi-alert --analysis abc123 --analysis def456 \
2272 --threshold count:gt:1000 \
2273 --threshold def456:sum:lt:50 --suppress 1h
2274  
2275 A threshold with no analysis prefix belongs to the first C<--analysis>; the
2276 C<ANALYSIS:MEASURE:OP:VALUE> form names another of those listed. Each analysis
2277 is reported in full, and each (analysis, threshold) pair is a check of its own:
2278 it prints its own line, keeps its own entry in the state file, and is throttled
2279 and recovered on its own schedule. One crossing never silences, recovers or
2280 delivers another. When a run announces both a crossing and a recovery it exits
2281 1, so a threshold that is still crossed is not reported as an all-clear.
2282  
2283 C<--suppress> throttles a threshold that stays crossed, so a condition that is
2284 still true on the next cron run is not reported as news again: it takes a
2285 duration (C<30s>, C<15m>, C<6h>, C<2d>, C<1w>, or a bare number of seconds), the
2286 first crossing is announced, and repeats inside the period are not. The
2287 throttle is one small JSON file, C<alerts-state.json> in the model directory
2288 unless C<--state-file> names elsewhere, keyed by analysis and threshold and
2289 written atomically. It is kept only when C<--suppress> is used or such a file
2290 already exists, so with no C<--suppress> the script is as stateless as it has
2291 always been and writes nothing.
2292  
2293 A run inside the period prints C<THRESHOLD SUPPRESSED> and exits 0: it is not
2294 announcing anything, so a cron wrapper keyed on the exit status stays quiet.
2295 When the crossing ends the run prints C<THRESHOLD CLEARED> once and drops its
2296 entry, which means the next crossing is announced immediately instead of
2297 waiting out a period that belonged to an incident that is over. A state file
2298 that cannot be read is reported and treated as empty, so a damaged file costs
2299 one repeated alert rather than silence, and C<--dry-run> records nothing, so a
2300 rehearsal cannot use up the alert a real run depends on.
2301  
2302 C<--recovery> announces that ending instead of merely reporting it: the run
2303 prints C<THRESHOLD RECOVERED> and exits 3, so a wrapper that mails on any
2304 non-zero status mails the all-clear as well as the alert, and a wrapper that
2305 should not is a wrapper that does not pass C<--recovery>. The recovery goes
2306 through the same state file, which is what makes it possible: an entry is the
2307 record of a crossing that was announced, so finding one is what tells the run
2308 that an incident has ended rather than that a threshold was never crossed. It
2309 is therefore said once per crossing and only for a crossing somebody was told
2310 about, which is also why C<--recovery> keeps that file even with no C<--suppress>
2311 to throttle. The recovery names both dates -- C<crossed since> and C<cleared>.
2312  
2313 C<--notify-cmd> delivers the announcement itself, so a cron line is one command
2314 rather than a shell wrapper around this one:
2315  
2316 ./script/bi-alert --analysis abc123 --threshold count:gt:1000 --suppress 1h \
2317 --recovery --notify-cmd 'mail -s "$BI_ALERT_SUBJECT" oncall@example.com'
2318  
2319 The command runs once per run, through the shell, and only when something is
2320 announced: a crossing (exit 1), or its end with C<--recovery> (exit 3). A
2321 suppressed repeat, an uncrossed threshold, an error and a C<--dry-run> run it
2322 not at all, and twenty checks still send one mail. The whole run's text arrives
2323 on standard input, and three variables say what it is -- C<BI_ALERT_EVENT>
2324 (C<crossed> if any crossing was announced, otherwise C<recovery>),
2325 C<BI_ALERT_SUBJECT> (the verdict line when one thing was announced, otherwise a
2326 count such as C<2 threshold crossings, 1 recovery>) and
2327 C<BI_ALERT_MESSAGE_FILE> (the same text in a file, for a command that has to
2328 post a body: C<curl -d @$BI_ALERT_MESSAGE_FILE ...>). A delivery that fails is
2329 reported on STDERR and leaves the exit status alone, but the announcements are
2330 not recorded, so the next run announces them again rather than the alert being
2331 lost for the rest of the period.
2332  
2333 C<script/database-bi> is the web application launcher: run with no arguments it
2334 starts the reloading development server, with the name of one database it does
2335 the same and shows that database, with a command word it runs that command, and C<hypnotoad script/database-bi> starts a preforking server (see
2336 L</SYNOPSIS>).
2337  
2338 =head1 COMMON PITFALLS
2339  
2340 =over 4
2341  
2342 =item B<The launcher's shebang must name perl, not morbo>
2343  
2344 morbo starts the application as C<perl script/database-bi daemon>, and perl
2345 hands a script whose C<#!> line does not mention perl to the interpreter that
2346 line names. With a C<morbo> shebang every worker therefore started another
2347 morbo: the chain grew a process a second, kept the listening port, and only
2348 stopped when the environment copied to each child was too large for C<exec>
2349 (F<Argument list too long>). The shebang is perl and the script starts the
2350 server itself when it is given no arguments.
2351  
2352 =item B<The launcher's last statement must be its call to start_app>
2353  
2354 C<hypnotoad> loads the launcher instead of running it, with no arguments, and
2355 takes the value of its last statement as the application. So the launcher must
2356 start the development server only when C<MOJO_APP_LOADER> is not set, and must
2357 not end in C<1;>. Otherwise C<hypnotoad script/database-bi> hangs in a
2358 development server or refuses to start.
2359  
2360 =item B<The configuration file is optional but must be valid Perl if present>
2361  
2362 C<database_bi.conf> is loaded by C<Mojolicious::Plugin::Config>, which
2363 evaluates it as a Perl data structure. If the file exists but contains a
2364 syntax error, the application will refuse to start. If the file does not
2365 exist, built-in defaults are used and no error occurs. The file must return
2366 a hashref:
2367  
2368 # database_bi.conf -- correct
2369 { data_dir => 'data', platform => 'web', language => 'en' }
2370  
2371 # WRONG -- missing braces
2372 data_dir => 'data'
2373  
2374 =item B<data_dir is relative to the application home directory, not the process cwd>
2375  
2376 Setting C<data_dir =E<gt> 'data'> looks for a folder called C<data/> in the
2377 same directory as the C<script/database-bi> launcher, regardless of where you
2378 run the server from. An absolute path works on any system:
2379  
2380 { data_dir => '/var/db/mydata' }
2381  
2382 =item B<The download_dir default is computed once at startup>
2383  
2384 When the application starts, it picks the export directory in this order:
2385 the first of C<export_dirs> (if set, as its real path), C<~/Downloads> (if it exists), then
2386 C<$HOME>, then the system temp directory.
2387 This value is fixed for the life of the process. Renaming or creating
2388 C<~/Downloads> after the server starts has no effect. To force a different
2389 default, set it before starting:
2390  
2391 { data_dir => 'data' } # and create ~/Downloads before starting the server
2392  
2393 =item B<Adding a new language requires a template directory, not just a config change>
2394  
2395 Setting C<language =E<gt> 'de'> in C<database_bi.conf> tells the controller
2396 to look for templates in C<templates/web/de/>. If that directory does not
2397 exist, the controller automatically falls back to the default language, and
2398 the same fallback applies when a browser asks for a language no directory
2399 serves. To add German support: (1) create C<templates/web/de/>, (2) copy and
2400 translate the C<.html.tt> files from C<templates/web/en/>, then (3) set the
2401 config.
2402  
2403 A directory may also name a region, as C<templates/web/en-us/> does: a browser
2404 whose Accept-Language asks for that region (C<en-US>) gets it, and every other
2405 request for the language (C<en-GB>, C<en-CA>, plain C<en>) gets
2406 C<templates/web/en/>. C<< language => 'en-us' >> makes it the default.
2407  
2408 The distribution ships C<en> (British English) and C<en-us> (American
2409 English). C<en-us> is not edited by hand: it is made from C<en> by
2410 C<author/make-en-us>, which respells the prose (colour, centre, summarise) and
2411 leaves the names the code reads alone. Run it after changing an C<en>
2412 template; C<t/en-us.t> fails until the two agree.
2413  
2414 The server's messages (errors, warnings, refusals) follow the same choice.
2415 L<CGI::Lingua> picks the language from the request's C<Accept-Language>, or,
2416 for the command-line scripts, from the locale (C<LANG=en_US.UTF-8>), and
2417 L<Database::BI::I18N> gives each message in it. A translation is a module,
2418 L<Database::BI::I18N::en_us> for American English, listing only the messages
2419 that read differently; C<t/i18n.t> fails when a British message needs an
2420 American spelling it does not list. The tutorial's text is still in British
2421 English.
2422  
2423 =item B<Supported data file extensions are: csv, db, sql, sqlite, sqlite3, xml, psv, tsv, xlsx, json, jsonl, ndjson>
2424  
2425 The application recognises C<.csv>, C<.db>, C<.sql>, C<.sqlite>, C<.sqlite3>,
2426 C<.xml>, C<.psv>, C<.tsv>, C<.xlsx>, C<.json>, C<.jsonl> and C<.ndjson> files. All three SQLite extensions
2427 (C<.sql>, C<.sqlite>, C<.sqlite3>) are treated identically -- C<inventory.sqlite>
2428 and C<inventory.sqlite3> are both opened as SQLite databases without renaming.
2429 Excel C<.xlsx> files are read by L<Database::Abstraction>, using
2430 C<Spreadsheet::ParseXLSX>.
2431  
2432 A C<.json> file is a table when it is a list of objects (each one a row), an
2433 object of objects (each key a row, shown in a column C<id>, or C<key> when the
2434 rows have an C<id> of their own), or an object holding lists of objects, as a
2435 report does: C<{"tool": "scan", "findings": [...], "hosts": [...]}>. Each
2436 such list is a table, as a SQLite file's tables are: a file with more than one
2437 opens on C</tables>, with a card for each, and other values beside the lists
2438 (a date, a count, an object of totals) are left out. A cell holding an object
2439 or a list shows as its JSON text, C<true> and C<false> as words and C<null> as
2440 an empty cell, and the columns are in the order the file first names them. A
2441 file of another format with the same name in the same folder is the one read.
2442  
2443 A C<.jsonl> or C<.ndjson> file (JSON Lines, one object a line, as logs and API
2444 exports write it) is a table with a row for each line. It is read as a stream,
2445 and so is a C<.json> list of objects over 16 MiB, so a large file does not
2446 need memory for its text and its parse as well. Set C<json_flatten> to 1 in
2447 C<database_bi.conf> and a nested object becomes a column for each of its
2448 values, named by its path (C<address.city>), instead of one cell of JSON text;
2449 lists stay text. It is off by default, and applies to C<.json> and JSON Lines
2450 alike.
2451  
2452 URLs will work.
2453 For example enter
2454 L<https://worldpopulationreview.com/country-rankings/immigration-by-country>
2455 into the C<Import from a web page> field on the dashboard.
2456  
2457 =item B<The open_table helper lowercases the table name>
2458  
2459 When the router matches C<GET /view/Sales> or C<GET /view/SALES>, the table
2460 name is lowercased to C<sales> before being passed to the helper. The data
2461 file on disc must therefore also be lowercase (C<sales.csv>, not
2462 C<Sales.csv>).
2463  
2464 =item B<Redis support requires the Redis or Redis::Fast module>
2465  
2466 Redis data source access is an optional feature. If neither C<Redis> nor
2467 C<Redis::Fast> is installed, entering a C<redis:...> spec returns a 404.
2468 To enable Redis support, install either module:
2469  
2470 cpanm Redis::Fast # recommended -- C bindings, faster
2471 cpanm Redis # pure-Perl fallback
2472  
2473 Redis keys must follow the C<tablename:entry> convention: each key is the
2474 table name, a colon, and an entry identifier; the value is a Redis hash
2475 whose fields become the row columns. For example:
2476  
2477 HSET players:row1 name Alice score 10
2478 HSET players:row2 name Bob score 20
2479  
2480 Opening C<redis:players|redis://localhost:6379> then displays a two-row table
2481 with columns C<entry>, C<name>, and C<score>.
2482  
2483 =back
2484  
2485 =head1 LIMITATIONS
2486  
2487 =over 4
2488  
2489 =item *
2490  
2491 The login is one shared password. There are no accounts, so every reader who
2492 knows it can do everything, and the log cannot say who did what.
2493  
2494 =item *
2495  
2496 Only read operations on data files are supported. Write-back (editing
2497 cell values in the browser and saving them to the data file) is not
2498 implemented.
2499  
2500 =item *
2501  
2502 A MariaDB table is read, never written, but the application does not enforce
2503 that on the server: give it an account with only C<SELECT>. Anyone who can reach
2504 the application can open any table that account can read.
2505  
2506 =item *
2507  
2508 Only a page of an unfiltered table is read with C<LIMIT>. A filter, Merge, Combine
2509 or an export reads the whole MariaDB table into memory, so a very large table is
2510 better opened through a view that narrows it.
2511  
2512 =item *
2513  
2514 A MariaDB table or view whose name holds anything but letters, digits and
2515 underscores cannot be opened. C</tables> shows it with a C<CREATE VIEW> statement
2516 that gives it a usable name.
2517  
2518 =item *
2519  
2520 A relative time range is resolved against the server's clock. An ISO
2521 timestamp, C<YYYY-MM-DDTHH:MM:SS> (a space instead of the C<T>, no seconds, a
2522 fraction of a second, and a trailing C<Z> or offset such as C<+01:00> are all
2523 accepted), is read as written: the zone is not applied, so
2524 C<2026-11-06T13:00:00Z> and C<2026-11-06T13:00:00+05:00> are the same time to
2525 a filter. A non-ISO timestamp is read as far as its C<YYYY-MM-DD> prefix, so
2526 C<last_24_hours> is exact only for ISO timestamps in the server's zone.
2527  
2528 =item *
2529  
2530 Multi-table left joins are performed in memory by L<Database::Join>. All
2531 component tables are fetched into RAM before the merge; this is not
2532 suitable for files that do not fit in the process's available memory.
2533  
2534 =item *
2535  
2536 Upload staging is managed automatically. On every server startup,
2537 C<Database::BI> evicts upload subdirectories whose modification time is
2538 older than 24 hours. The "Clear upload cache" button (C<POST
2539 /uploads/clear>) triggers an immediate full purge regardless of age.
2540  
2541 =item *
2542  
2543 C<Sub::Protected>/:Protected enforcement relies on the CHECK compilation
2544 phase. When a module is loaded dynamically at test time (e.g. via
2545 C<Test::Mojo->new(...)>), the CHECK phase has already passed and the
2546 "Too late to run CHECK block" warning is emitted -- the access
2547 restriction is not enforced in that test context. This does not affect
2548 production (morbo/hypnotoad) deployments where modules are compiled on
2549 startup. Unlike the former C<Sub::Private> approach, C<Sub::Protected>
2550 does not delete stash entries, so OO dispatch C<< $self->_method() >>
2551 works correctly in production without any special workarounds.
2552  
2553 =back
2554  
2555 =head1 ROADMAP
2556  
2557 Features planned for future releases (post-0.019.0). Items are ordered by
2558 priority. Items shipped before this release (XLSX export, the copy-link
2559 button, the column statistics panel, folder filter/join propagation, the
2560 aggregate/measure layer and the C<between> and C<in> filter operators) are no
2561 longer listed.
2562  
2563 =over 4
2564  
2565 =item * B<Multi-sheet XLSX> (Medium) -- C<_detect_file_info> reads only the
2566 first worksheet. A C<?sheet=> URL param with a sheet-name picker would
2567 expose the full workbook.
2568  
2569 =item * B<SSE streaming for large join results> (Low) -- The join pipeline
2570 blocks the HTTP response until all rows are assembled. Mojolicious supports
2571 server-sent events, which could progressively stream rows to a JS table
2572 renderer, giving visible progress on slow joins.
2573  
2574 =item * B<Boundary overlay on maps> (Low) -- C<HTML::OSM> can draw GeoJSON and
2575 choropleth layers. A C<gj=E<lt>pathE<gt>> parameter would overlay a local
2576 GeoJSON file, optionally shaded by an aggregated measure. This is the one
2577 Phase 6 item not implemented: it is optional in the phase spec, and no boundary
2578 data is shipped or downloaded.
2579  
2580 =back
2581  
2582 =cut
2583  
2584 # =============================================================================
2585 # KNOWN GAPS & ROADMAP
2586 # =============================================================================
2587 #
2588 # Items marked [NEW 0.010.0] were identified during the 0.010.0 gap analysis.
2589 # Items completed in 0.012.0:
2590 # A. Pagination -- done: /view, /open, /join, /combine, /export all paginate.
2591 # 1. dbi_source() proxy -- done: DataSource::dbi_source() delegating method added.
2592 # 2. limit/offset plumbing -- done: /join, /combine, /export thread pagination.
2593 # 3. order_by delegation -- done: ?sort=col&dir=asc|desc on /join and /combine.
2594 # 4. Filter pushdown -- done: _filter_specs_to_criteria translates f= specs to
2595 # SQL criteria for SQLite sources; _grouped_totals and _fetch_page both use it.
2596 # 5. Schema warnings UI -- done: every route that builds a join compares the
2597 # declared types at each step (DataSource::schema, _schema_type_warnings),
2598 # and the join page shows a banner. The chart/export pipeline records the
2599 # same warnings; /export returns them in the X-BI-Warnings header.
2600 # Database::Join's own warn_schema_type_mismatch cannot fire here, because
2601 # these joins always pass a collision_prefix for the right table.
2602 # 6. updated() in DataSource -- done: DataSource::updated() delegates to inner DA.
2603 #
2604 # ---- POST-RELEASE FEATURE ROADMAP ----
2605 #
2606 # Completed since 0.010.0, so no longer listed here: XLSX export (B), the
2607 # copy-link button on chart pages (C), the column statistics panel (D), and
2608 # folder-view filter/join propagation (F). The same list lives in the POD
2609 # ROADMAP above; keep the two in step.
2610 #
2611 # E. [NEW 0.010.0] Multi-sheet XLSX (Medium priority)
2612 # _detect_file_info reads only worksheet index 0. A ?sheet= URL param
2613 # with a sheet-name picker would expose the full workbook.
2614 #
2615 # H. [NEW 0.010.0] SSE streaming for large join results (Low priority)
2616 # The join pipeline blocks the HTTP response until all rows are assembled.
2617 # Mojolicious write_chunk / finish can progressively stream rows, giving
2618 # visible progress on slow multi-table joins.
2619 #
2620 # ---- OPEN INTEGRATION GAPS ----
2621 #
2622 # I. parallel => 1 for multi-step join chains
2623 # --------------------------------------------
2624 # When the user chains three or more j= join steps, Database::BI creates a
2625 # single Database::Join object with multiple secondary databases. Enabling
2626 # parallel => 1 on that object would issue the secondary DA fetches
2627 # concurrently when the threads module is available. However: DataSource is
2628 # not thread-safe (it holds a CHI cache handle and open file handles). Before
2629 # enabling parallel, DataSource must be audited for thread safety -- at minimum
2630 # the CHI driver must be confirmed re-entrant, or a separate DataSource clone
2631 # created per thread.
2632 # Short-term: do not enable parallel => 1; add a FIXME comment to the join
2633 # route noting why it is disabled. Longer-term: implement DataSource::clone()
2634 # that creates an independent handle per thread.
2635 #
2636 # J. per-table filters => on the join pipeline
2637 # --------------------------------------------
2638 # The /join route accepts f=col:op:val filters that are applied as post-join
2639 # in-memory filtering in the template. Database::Join 0.007.0's filters =>
2640 # constructor parameter applies per-database criteria at spill time on the
2641 # SQLite backend, which is far cheaper for large tables. When a filter column
2642 # is known to belong to a specific source table (i.e. it appears in
2643 # $join->columns() but also in one component DA's columns()), the join route
2644 # could partition filters by owning database and pass them as filters => to
2645 # the Database::Join constructor. Filters on the merged view (post-join
2646 # computed columns) must remain as template-side filtering.
2647 #
2648 # K. collision_prefix exposure in the join UI
2649 # --------------------------------------------
2650 # When two joined tables share a column name, Database::Join's default
2651 # last-table-wins behaviour silently discards one table's value. The join
2652 # UI (the "Merge data" panel) could offer a "rename duplicate columns from
2653 # right table" text field so users can configure collision_prefix without
2654 # writing code. The entered prefix would be passed as
2655 # collision_prefix => { 1 => $prefix } when constructing Database::Join.
2656 # =============================================================================
2657  
2658 # _table_cache_root($app, \%cache_conf) -> (root_dir => $dir) | ()
2659 #
2660 # A driver that keeps the table cache on disc (File, FastMmap) is given a
2661 # directory: cache => { root_dir } when the config names one, else the one
2662 # Database::BI::CacheDir chooses for this class (Object::Configure, CACHEDIR,
2663 # CACHE_DIR, cache_dir in this config, then <model_dir>/cache). CHI's own
2664 # default would be a folder under the system temp directory. The Memory
2665 # driver keeps nothing on disc and takes no directory.
2666 143 ▶sub _table_cache_root ($app, $cache_conf) {
Subroutine _table_cache_root: called CC=6 SCAR=31.0
2667 143 ▶ my $driver = $cache_conf->{driver} // 'Memory';
Condition50%1/2
$cache_conf->{"driver"} // "Memory"
l!l
0143
MC/DC0%0/1
$cache_conf->{"driver"} // "Memory"
$cache_conf->{"driver"}
Truth table50%1/2
A
A= $cache_conf->{"driver"}
Aresult
11
00
2668  
2669 143 ▶ return () unless $DISC_CACHE_DRIVER{$driver};
Branch: 1 branch
BranchTrueFalseTotal
unless $DISC_CACHE_DRIVER{$driver} 143 0 143
2670 0 ▶ return (root_dir => $cache_conf->{root_dir}) if defined $cache_conf->{root_dir};
Branch: 1 branch
BranchTrueFalseTotal
if defined $cache_conf->{"root_dir"} 0 0 0
2671  
2672 0 require Database::BI::CacheDir;
2673  
2674 0 ▶ my $model_dir = Mojo::File->new($app->config('model_dir') // '.bi');
Condition0%0/2
$app->config("model_dir") // ".bi"
l!l
00
MC/DC0%0/1
$app->config("model_dir") // ".bi"
$app->config("model_dir")
Truth table0%0/2
A
A= $app->config("model_dir")
Aresult
11
00
2675 0 ▶ $model_dir = $app->home->child($model_dir->to_string) unless $model_dir->is_abs;
Branch: 1 branch
BranchTrueFalseTotal
unless $model_dir->is_abs 0 0 0
2676  
2677 0 return (root_dir => Database::BI::CacheDir::resolve(
2678 class => __PACKAGE__,
2679 config => $app->config,
2680 home => $app->home->to_string,
2681 default => $model_dir->child('cache')->to_string,
2682 ));
2683 }
2684  
2685 145 ▶sub startup ($self) {
Subroutine startup: called CC=27 SCAR=34.5
Pod documented
2686 145 $self->plugin('Config', {
2687 default => {
2688 data_dir => $DEFAULT_DATA_DIR,
2689 platform => $DEFAULT_PLATFORM,
2690 language => $DEFAULT_LANGUAGE,
2691 d3_url => $DEFAULT_D3_URL,
2692 }
2693 });
2694  
2695 # The key the map page signs the places it lists with (/geo/lookup checks
2696 # it). Mojolicious would use the moniker, which anyone can read; a config
2697 # secrets => [...] keeps lists valid across restarts, and without one each
2698 # start makes its own. This runs before hypnotoad forks, so every worker
2699 # shares it.
2700 # The sites that may frame /embed/. A mistake here is a security setting
2701 # that does not do what it says, so it stops the start rather than being
2702 # dropped quietly.
2703 145 _check_embed_frame_ancestors($self->config('embed_frame_ancestors'));
2704 145 _check_strict_transport_security($self->config('strict_transport_security'));
2705 145 _check_permissions_policy($self->config('permissions_policy'));
2706 145 _check_cross_origin_opener_policy($self->config('cross_origin_opener_policy'));
2707 145 _check_allowed_hosts($self->config('allowed_hosts'));
2708 145 _check_file_roots($self->config('file_roots'), $self->home);
2709 145 _check_url_private_hosts($self->config('url_private_hosts'));
2710 145 _check_map_bounds_ranks($self->config('map_bounds_ranks'));
2711 145 _check_share_secret($self->config('share_secret'));
2712 145 _check_export_dirs($self, $self->config('export_dirs'));
2713 145 ▶ croak 'ai_calls_per_hour: give a whole number of provider calls an hour, or 0 for no limit'
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->config("ai_calls_per_hour") and not $self->config("ai_calls_per_hour") =~ /\A[0-9]+\z/u 0 145 145
Condition33%1/3
defined $self->config("ai_calls_per_hour") and not $self->config("ai_calls_per_hour") =~ /\A[0-9]+\z/u
!ll&&!rl&&r
14500
MC/DC0%0/2
defined $self->config("ai_calls_per_hour") and not $self->config("ai_calls_per_hour") =~ /\A[0-9]+\z/u
defined $self->config("ai_calls_per_hour") not $self->config("ai_calls_per_hour") =~ /\A[0-9]+\z/u
Truth table33%1/3
A and not(B)
A= defined $self->config("ai_calls_per_hour")B= not $self->config("ai_calls_per_hour") =~ /\A[0-9]+\z/u
ABresult
0X0
100
111
2714 if defined $self->config('ai_calls_per_hour') && $self->config('ai_calls_per_hour') !~ /\A[0-9]+\z/;
2715 145 _check_login($self->config('password_hash'), $self->config('login_expiration'));
2716 # Read once: a bad time_zone stops the start, as the other settings do.
2717 145 my $time_zone = Database::BI::Util::parse_zone($self->config('time_zone'));
2718 145 _require_export_dirs_with_password($self->config('password_hash'), $self->config('export_dirs'));
2719  
2720 # Only this machine can reach a server unless the configuration says
2721 # otherwise. Mojolicious's own default is every interface, which put an
2722 # application with no login on the local network. -l and MOJO_LISTEN still
2723 # win: the daemon and prefork commands read MOJO_LISTEN only when started,
2724 # after this, and -l replaces it.
2725 145 my @listen = _listen_locations($self->config('listen'));
2726 # Stacking a folder of files puts every path in the URL; Mojo's 8 KiB line limit is too small.
2727 145 ▶ $ENV{MOJO_MAX_LINE_SIZE} ||= 262_144;
Condition100%2/2
$ENV{"MOJO_MAX_LINE_SIZE"} ||= 262144
l!l
13510
MC/DC100%1/1
$ENV{"MOJO_MAX_LINE_SIZE"} ||= 262144
$ENV{"MOJO_MAX_LINE_SIZE"}
Truth table100%2/2
A
A= $ENV{"MOJO_MAX_LINE_SIZE"}
Aresult
11
00
2728 145 ▶ $ENV{MOJO_LISTEN} = join(',', @listen) unless length($ENV{MOJO_LISTEN} // '');
Branch: 1 branch
BranchTrueFalseTotal
unless length($ENV{"MOJO_LISTEN"} // "") 12 133 145
Condition100%2/2
$ENV{"MOJO_LISTEN"} // ""
l!l
13312
MC/DC100%1/1
$ENV{"MOJO_LISTEN"} // ""
$ENV{"MOJO_LISTEN"}
Truth table100%2/2
A
A= $ENV{"MOJO_LISTEN"}
Aresult
11
00
2729 145 _default_hypnotoad_listen($self->config);
2730 145 _require_password_if_open($self, $ENV{MOJO_LISTEN}, $self->config->{hypnotoad});
2731  
2732 # script/database-bi password makes the password_hash line.
2733 143 push @{ $self->commands->namespaces }, 'Database::BI::Command';
2734  
2735 143 my $secrets = $self->config('secrets');
2736 0 ▶ $self->secrets((ref($secrets) eq 'ARRAY' && @{$secrets})
Branch: 1 branch
BranchTrueFalseTotal
ref $secrets eq 'ARRAY' && @{$secrets;} ? : 0 143 143
Condition33%1/3
ref $secrets eq "ARRAY" and @{$secrets;}
!ll&&!rl&&r
14300
MC/DC0%0/2
ref $secrets eq "ARRAY" and @{$secrets;}
ref $secrets eq "ARRAY" @{$secrets;}
Truth table33%1/3
A and B
A= ref $secrets eq "ARRAY"B= @{$secrets;}
ABresult
0X0
100
111
2737 ? $secrets : [ Mojo::Util::generate_secret() ]);
2738  
2739 # The login session (see "Logging in"). The cookie is signed with the
2740 # secrets, HttpOnly, SameSite=Lax, and Secure whenever the request came over
2741 # https; it lasts login_expiration seconds from the last request. With no
2742 # secrets => [...] each start makes a new key, so a restart logs everyone out.
2743 143 ▶ $self->sessions(Database::BI::Sessions->new(
Condition66%2/3
$self->config("login_expiration") // $DEFAULT_LOGIN_EXPIRATION
l!l&&r!l&&!r
013310
MC/DC50%1/2
$self->config("login_expiration") // $DEFAULT_LOGIN_EXPIRATION
$self->config("login_expiration") $DEFAULT_LOGIN_EXPIRATION
Truth table66%2/3
A // B
A= $self->config("login_expiration")B= $DEFAULT_LOGIN_EXPIRATION
ABresult
1X1
011
000
2744 cookie_name => 'database_bi',
2745 default_expiration => $self->config('login_expiration') // $DEFAULT_LOGIN_EXPIRATION,
2746 samesite => 'Lax',
2747 ));
2748  
2749 # Cap inbound request body size. When the limit fires, Mojolicious sets
2750 # req->is_limit_exceeded and still dispatches to the controller (with partial
2751 # content in the upload asset). The controller checks is_limit_exceeded and
2752 # returns 413 before writing to disc.
2753 143 $self->max_request_size($MAX_REQUEST_SIZE);
2754  
2755 # Default export/save directory: ~/Downloads when it exists, else HOME,
2756 # else system tmpdir. Resolved once per process and stored as a stash
2757 # default so every action can read $self->stash('download_dir').
2758 # With export_dirs, the first of them: the panel would open on a refusal.
2759 # Resolved as the export checks resolve it (_real_folders), so the panel
2760 # opens on the folder spelled as /api/dirs and the rest of the application
2761 # spell it (on Windows, child() joins with \, realpath gives /, and a
2762 # link is followed by hand).
2763 143 ▶ my $home = $ENV{HOME} // '';
Condition50%1/2
$ENV{"HOME"} // ""
l!l
1430
MC/DC0%0/1
$ENV{"HOME"} // ""
$ENV{"HOME"}
Truth table50%1/2
A
A= $ENV{"HOME"}
Aresult
11
00
2764 143 ▶ my $dl_dir = ($home && -d "$home/Downloads") ? "$home/Downloads"
Branch: 1 branch
BranchTrueFalseTotal
$home && -d "$home/Downloads" ? : 0 143 143
Condition33%2/6
$home and -d "$home/Downloads"
!ll&&!rl&&r
01430
$home or "File::Spec"->tmpdir
l!l&&r!l&&!r
14300
MC/DC0%0/2
$home and -d "$home/Downloads"
$home -d "$home/Downloads"
MC/DC0%0/2
$home or "File::Spec"->tmpdir
$home "File::Spec"->tmpdir
Truth table33%1/3
A and B
A= $homeB= -d "$home/Downloads"
ABresult
0X0
100
111
Truth table33%1/3
A or B
A= $homeB= "File::Spec"->tmpdir
ABresult
1X1
011
000
2765 : ($home || File::Spec->tmpdir());
2766 143 my $exports = $self->config('export_dirs');
2767 143 ▶ if (ref($exports) eq 'ARRAY' && @{$exports}) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $exports eq "ARRAY" and @{$exports;}) 1 142 143
Condition66%2/3
ref $exports eq "ARRAY" and @{$exports;}
!ll&&!rl&&r
14201
MC/DC50%1/2
ref $exports eq "ARRAY" and @{$exports;}
ref $exports eq "ARRAY" @{$exports;}
Truth table66%2/3
A and B
A= ref $exports eq "ARRAY"B= @{$exports;}
ABresult
0X0
100
111
2768 1 my $first = $exports->[0];
2769 1 ▶ my $dir = File::Spec->file_name_is_absolute($first) ? Mojo::File->new($first) : $self->home->child($first);
Branch: 1 branch
BranchTrueFalseTotal
'File::Spec'->file_name_is_absolute($first) ? : 1 0 1
2770 1 require Database::BI::Controller::Dashboard;
2771 1 ▶ $dl_dir = (-e "$dir" ? Database::BI::Controller::Dashboard::_resolved_path("$dir") : undef) // "$dir";
Branch: 1 branch
BranchTrueFalseTotal
-e "$dir" ? : 1 0 1
Condition50%1/2
(-e "$dir" ? Database::BI::Controller::Dashboard::_resolved_path("$dir") : undef) // "$dir"
l!l
10
MC/DC0%0/1
(-e "$dir" ? Database::BI::Controller::Dashboard::_resolved_path("$dir") : undef) // "$dir"
(-e "$dir" ? Database::BI::Controller::Dashboard::_resolved_path("$dir") : undef)
Truth table50%1/2
A
A= (-e "$dir" ? Database::BI::Controller::Dashboard::_resolved_path("$dir") : undef)
Aresult
11
00
2772 }
2773 143 $self->defaults(download_dir => $dl_dir);
2774  
2775 # Register the TT plugin as 'tt' (not the default 'tt2') so that template
2776 # files keep the .html.tt extension and handler => 'tt' in render() calls
2777 # resolves correctly via Template::Provider::Mojo. TT options must live
2778 # under the 'template' key; top-level keys are plugin options only.
2779 143 $self->plugin('TemplateToolkit', {
2780 name => 'tt',
2781 template => {
2782 POST_CHOMP => 1,
2783 TRIM => 1,
2784 },
2785 });
2786  
2787 # Response compression (gzip/Brotli), ETag/304 handling, and HTML
2788 # whitespace minification. Level 1 leaves <script>/<style> content
2789 # alone; level 2 runs aggressive JS minification and is not safe with
2790 # the inline JavaScript in the dashboard and home templates.
2791 # vary_by adds Accept-Language to the cache key so VWF language
2792 # detection stores one copy per language.
2793 143 my $page_cache_dir = $self->config->{page_cache_dir};
2794 143 my $page_chi;
2795 143 ▶ if ($page_cache_dir) {
Branch: 1 branch
BranchTrueFalseTotal
if ($page_cache_dir) 1 142 143
2796 # page_cache_dir turns the page cache on, and is where it goes when no
2797 # cache directory is set (Object::Configure, CACHEDIR, CACHE_DIR,
2798 # cache_dir in this config). The pages keep to their own namespace,
2799 # so they can share that directory with the other caches.
2800 1 my $default = Mojo::File->new($page_cache_dir);
2801 1 ▶ $default = $self->home->child($page_cache_dir) unless $default->is_abs;
Branch: 1 branch
BranchTrueFalseTotal
unless $default->is_abs 0 1 1
2802 1 require Database::BI::CacheDir;
2803 1 my $dir = Mojo::File->new(Database::BI::CacheDir::resolve(
2804 class => __PACKAGE__,
2805 config => $self->config,
2806 home => $self->home->to_string,
2807 default => $default->to_string,
2808 ));
2809 1 $dir->make_path;
2810 1 $page_chi = CHI->new(
2811 driver => 'File',
2812 root_dir => $dir->to_string,
2813 namespace => 'Database::BI::Pages',
2814 );
2815 }
2816 # No Last-Modified: the plugin's date is that of the code and templates, not
2817 # of the data, and with it and no Cache-Control a browser may reuse a reply
2818 # without asking. A panel that reopened after a save then listed what was
2819 # saved before it. The ETag alone makes every reuse a revalidation.
2820 $self->plugin('Buffer', {
2821 optimise_content => 1,
2822 last_modified => 0,
2823 vary_by => ['accept-language'],
2824 ($page_chi ? (
2825 cache => $page_chi,
2826 143 ▶ cache_duration => $self->config->{page_cache_duration} // '5 minutes',
Branch: 1 branch
BranchTrueFalseTotal
$page_chi ? : 1 142 143
Condition50%1/2
$self->config->{"page_cache_duration"} // "5 minutes"
l!l
01
MC/DC0%0/1
$self->config->{"page_cache_duration"} // "5 minutes"
$self->config->{"page_cache_duration"}
Truth table50%1/2
A
A= $self->config->{"page_cache_duration"}
Aresult
11
00
2827 ) : ()),
2828 });
2829  
2830 # The Content-Security-Policy nonce for this request. Every <script> the
2831 # templates write carries it, as do those HTML::D3 and HTML::OSM write
2832 # (given nonce => $c->csp_nonce), and the policy runs no inline script
2833 # without it. It is made before the action runs, so a template rendered
2834 # before anything asked for it still has one, and it is fresh for every
2835 # request: markup that reached a page through its data cannot know it.
2836 3294 ▶ $self->hook(before_dispatch => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
2837 3294 shift->stash(csp_nonce => _new_nonce());
2838 143 });
2839  
2840 # The language this request's messages are given in, chosen by CGI::Lingua
2841 # from its Accept-Language (Database::BI::I18N::choose), with the
2842 # configured language when it names none we have. It is set with local
2843 # around the whole dispatch, so a message raised anywhere while the request
2844 # is answered - a refusal in the hook below, a model's croak - is in the
2845 # reader's language, and the next request starts afresh. Every action
2846 # answers before it returns; one that answered later, from the event loop,
2847 # would need to set it again there.
2848 3294 ▶ $self->hook(around_dispatch => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
2849 3294 my ($next, $c) = @_;
2850 3294 local $Database::BI::Util::ZONE = $time_zone;
2851 local $Database::BI::I18N::LANGUAGE = Database::BI::I18N::choose(
2852 accept => scalar $c->req->headers->accept_language,
2853 default => $c->app->config->{language},
2854 3294 );
2855 3294 return $next->();
2856 143 });
2857 # Refuse what another site's page asks of this one through the reader's
2858 # browser: a form posted from there, or a page whose name was made to
2859 # resolve to this machine (DNS rebinding). Nothing here asks who the
2860 # reader is, so this is what stands between another site and POST /export,
2861 # which writes files, and /open, which reads them. A refusal is 403, as
2862 # JSON for a write (the panels read JSON back) and as text otherwise.
2863 3294 ▶ $self->hook(before_dispatch => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
2864 3294 my $c = shift;
2865 3294 require Database::BI::Controller::Dashboard;
2866 3294 ▶ my $refusal = Database::BI::Controller::Dashboard::request_refusal($c) // return;
Condition100%2/2
Database::BI::Controller::Dashboard::request_refusal($c) // (return)
l!l
33291
MC/DC100%1/1
Database::BI::Controller::Dashboard::request_refusal($c) // (return)
Database::BI::Controller::Dashboard::request_refusal($c)
Truth table100%2/2
A
A= Database::BI::Controller::Dashboard::request_refusal($c)
Aresult
11
00
2867 3 $c->stash(buffer => 0);
2868 3 ▶ return $c->render(json => { error => $refusal }, status => 403)
Branch: 1 branch
BranchTrueFalseTotal
unless $c->req->method =~ /\A(?:GET|HEAD)\z/u 1 2 3
2869 if $c->req->method !~ /\A(?:GET|HEAD)\z/;
2870 2 $c->res->headers->content_type('text/plain; charset=utf-8');
2871 2 return $c->render(data => Mojo::Util::encode('UTF-8', $refusal), status => 403);
2872 143 });
2873 1802 ▶ $self->helper(csp_nonce => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
2874 1802 my $c = shift;
2875 1802 my $nonce = $c->stash('csp_nonce');
2876 1802 ▶ $c->stash(csp_nonce => ($nonce = _new_nonce())) unless defined $nonce;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $nonce 2 1800 1802
2877 1802 return $nonce;
2878 143 });
2879  
2880 # A Content-Security-Policy on every HTML reply. The pages draw cells from
2881 # files nobody here wrote, so the policy is the second line behind the
2882 # escaping: script runs only from this site, the hosts the configuration
2883 # names, and inline blocks that carry this request's nonce; style and
2884 # images come only from this site and those hosts; nothing a page runs may
2885 # send data to another server, and no other site may frame a page. Built
2886 # per reply from the config, as d3_url is, so a test can change it.
2887 #
2888 # Mojolicious runs after_dispatch hooks last registered first, so this runs
2889 # before Buffer's: a page Buffer keeps in its page cache is stored with the
2890 # header, and when it is served again Buffer puts back the header with the
2891 # body, so the nonce in each still matches the other. The header is left
2892 # alone when it is already there for that reason.
2893 3301 ▶ $self->hook(after_dispatch => sub {
Subroutine __ANON__: called CC=20 SCAR=38.3
2894 3301 my $c = shift;
2895  
2896 3301 my $headers = $c->res->headers;
2897  
2898 # On every reply, not only pages: a download opened in the browser, or
2899 # a JSON reply viewed there, can follow a link too.
2900 3301 ▶ $headers->header('Referrer-Policy' => $REFERRER_POLICY)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $headers->header("Referrer-Policy") 3301 0 3301
2901 unless defined $headers->header('Referrer-Policy');
2902  
2903 # The browser features no page uses are turned off, so a script that
2904 # got in cannot ask the reader for the camera, a location or a payment.
2905 3301 ▶ if (defined(my $features = _permissions_policy($c->app->config))) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $features = _permissions_policy($c->app->config))) 3301 0 3301
2906 3301 ▶ $headers->header('Permissions-Policy' => $features)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $headers->header("Permissions-Policy") 3301 0 3301
2907 unless defined $headers->header('Permissions-Policy');
2908 }
2909  
2910 # Over https, the browser is told to come back only over https. Sent on
2911 # every such reply, as browsers read it from any of them.
2912 3301 ▶ if (defined(my $hsts = _strict_transport_security($c))) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $hsts = _strict_transport_security($c))) 0 3301 3301
2913 0 ▶ $headers->header('Strict-Transport-Security' => $hsts)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $headers->header("Strict-Transport-Security") 0 0 0
2914 unless defined $headers->header('Strict-Transport-Security');
2915 }
2916  
2917 # A reply is what its Content-Type says, on every reply: a browser that
2918 # guessed could take a CSV export or an uploaded file's text for HTML or
2919 # script, and run what a cell holds. Every route names its type, and
2920 # the static files have theirs from their extensions.
2921 3301 ▶ $headers->header('X-Content-Type-Options' => 'nosniff')
Branch: 1 branch
BranchTrueFalseTotal
unless defined $headers->header("X-Content-Type-Options") 3301 0 3301
2922 unless defined $headers->header('X-Content-Type-Options');
2923  
2924 3301 ▶ return unless ($headers->content_type // '') =~ m{\Atext/html\b}i;
Branch: 1 branch
BranchTrueFalseTotal
unless ($headers->content_type // "") =~ m[\Atext/html\b]iu 1905 1396 3301
Condition100%2/2
$headers->content_type // ""
l!l
32965
MC/DC100%1/1
$headers->content_type // ""
$headers->content_type
Truth table100%2/2
A
A= $headers->content_type
Aresult
11
00
2925  
2926 # Framing is refused whatever the policy says. frame-ancestors does
2927 # that in the policy, but a report-only policy only reports it, a
2928 # policy of the deployment's own may leave it out, and '' sends none;
2929 # older browsers read only this header. Where both are sent, a
2930 # browser that knows frame-ancestors follows it and ignores this.
2931 1396 ▶ $headers->header('X-Frame-Options' => 'SAMEORIGIN')
Branch: 1 branch
BranchTrueFalseTotal
unless defined $headers->header("X-Frame-Options") 1385 11 1396
2932 unless defined $headers->header('X-Frame-Options');
2933  
2934 # A page keeps its window to itself: another site that opened it, or
2935 # that it opened, cannot reach it through window.opener. For pages
2936 # only, as it is a property of the document a window shows.
2937 1396 ▶ if (defined(my $coop = _cross_origin_opener_policy($c->app->config))) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $coop = _cross_origin_opener_policy($c->app->config))) 1396 0 1396
2938 1396 ▶ $headers->header('Cross-Origin-Opener-Policy' => $coop)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $headers->header("Cross-Origin-Opener-Policy") 1396 0 1396
2939 unless defined $headers->header('Cross-Origin-Opener-Policy');
2940 }
2941  
2942 # /embed/ stashes the other sites embed_frame_ancestors allows.
2943 1396 my $framers = $c->stash('csp_frame_ancestors');
2944 1396 ▶ $framers = [] unless ref $framers eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $framers eq "ARRAY" 1396 0 1396
2945  
2946 1396 my $policy = _content_security_policy($c->app->config, $c->csp_nonce, $framers);
2947 1396 my $report_only = $c->app->config('content_security_policy_report_only');
2948 1396 ▶ my $name = $report_only ? 'Content-Security-Policy-Report-Only' : 'Content-Security-Policy';
Branch: 1 branch
BranchTrueFalseTotal
$report_only ? : 0 1396 1396
2949 1396 ▶ $headers->header($name => $policy) if defined $policy && !defined $headers->header($name);
Branch: 1 branch
BranchTrueFalseTotal
if defined $policy and not defined $headers->header($name) 1396 0 1396
Condition33%1/3
defined $policy and not defined $headers->header($name)
!ll&&!rl&&r
001396
MC/DC0%0/2
defined $policy and not defined $headers->header($name)
defined $policy not defined $headers->header($name)
Truth table33%1/3
A and not(B)
A= defined $policyB= not defined $headers->header($name)
ABresult
0X0
100
111
2950  
2951 # Allowing other sites to frame /embed/ must never allow every site.
2952 # Unless an enforced policy above already says who may, a policy of
2953 # frame-ancestors alone is added: with report-only, no policy, or one
2954 # written out without it, the page would otherwise rely on
2955 # X-Frame-Options, which these browsers ignore once frame-ancestors is
2956 # anywhere. (Browsers that know only X-Frame-Options refuse the frame.)
2957 1396 ▶ if (@{$framers}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$framers;}) 0 1396 1396
2958 0 ▶ my $enforced = $report_only ? undef : $policy;
Branch: 1 branch
BranchTrueFalseTotal
$report_only ? : 0 0 0
2959 0 ▶ $headers->add('Content-Security-Policy' => _frame_ancestors_directive($framers))
Branch: 1 branch
BranchTrueFalseTotal
unless defined $enforced and $enforced =~ /(?:\A|;)\s*frame-ancestors\b/iu 0 0 0
Condition0%0/3
defined $enforced and $enforced =~ /(?:\A|;)\s*frame-ancestors\b/iu
!ll&&!rl&&r
000
MC/DC0%0/2
defined $enforced and $enforced =~ /(?:\A|;)\s*frame-ancestors\b/iu
defined $enforced $enforced =~ /(?:\A|;)\s*frame-ancestors\b/iu
Truth table0%0/3
A and B
A= defined $enforcedB= $enforced =~ /(?:\A|;)\s*frame-ancestors\b/iu
ABresult
0X0
100
111
2960 unless defined $enforced && $enforced =~ /(?:\A|;)\s*frame-ancestors\b/i;
2961 }
2962 143 });
2963  
2964 # A relative time range named in the URL (?range=last_30_days&rcol=when)
2965 # becomes the f= filters every data route already applies, so the table
2966 # view, every chart, the pivot, stats, insights, the exports and a saved
2967 # canvas all narrow to the same rows without any per-route code. It runs
2968 # before dispatch because the range has to be part of the request's filter
2969 # list by the time a route reads it, and a range that cannot be honoured
2970 # answers 400 here rather than filtering the wrong rows.
2971 3294 ▶ $self->hook(before_dispatch => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
2972 3294 my $c = shift;
2973  
2974 3294 require Database::BI::Controller::Dashboard;
2975 3294 return Database::BI::Controller::Dashboard::_time_range_request($c);
2976 143 });
2977  
2978 # A filter whose operator is not one the pipeline knows is refused here,
2979 # for every route, rather than keeping every row and saying nothing.
2980 3294 ▶ $self->hook(before_dispatch => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
2981 3294 my $c = shift;
2982 3294 ▶ return if $c->res->code; # already answered (a range refused above)
Branch: 1 branch
BranchTrueFalseTotal
if $c->res->code 222 3072 3294
2983  
2984 3072 require Database::BI::Controller::Dashboard;
2985 3072 return Database::BI::Controller::Dashboard::_filter_request($c);
2986 143 });
2987  
2988 # Cross-row columns (?cs=/by=/order=) are part of the view: the table page
2989 # draws a chip for each one and its panel edits them, and every chart panel
2990 # carries them to its route, which runs the same pass over the same rows.
2991 # It is a hook rather than four stash lines in each of the seven actions that
2992 # render the dashboard, so a new action cannot silently lose them.
2993 3294 ▶ $self->hook(before_dispatch => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
2994 3294 my $c = shift;
2995  
2996 3294 require Database::BI::Controller::Dashboard;
2997 3294 $c->stash(Database::BI::Controller::Dashboard::_cross_row_ui_state($c));
2998 143 });
2999  
3000 # The rest of the view a request carries -- the join type, the reader's
3001 # filters, the files stacked in with c= and de-duplication -- for the same
3002 # reason: the dashboard's panels pass it on through one macro, and every
3003 # chart page names it under its breadcrumb, so a chart never looks like
3004 # the whole file when it is drawn from part of it.
3005 3294 ▶ $self->hook(before_dispatch => sub {
Subroutine __ANON__: called CC=7 SCAR=19.6
3006 3294 my $c = shift;
3007  
3008 3294 ▶ my $jtype = $c->param('jtype') // '';
Condition100%2/2
$c->param("jtype") // ""
l!l
2573037
MC/DC100%1/1
$c->param("jtype") // ""
$c->param("jtype")
Truth table100%2/2
A
A= $c->param("jtype")
Aresult
11
00
3009 $c->stash(
3010 view_join_type => ($jtype =~ /\A(?:left|inner|outer)\z/ ? $jtype : ''),
3011 355 view_filters => [ grep { length } @{ $c->every_param('f') } ],
3012 286 ▶ view_combines => [ grep { /\A(?:path|table|url|redis|mariadb):/i } @{ $c->every_param('c') } ],
Branch: 2 branches
BranchTrueFalseTotal
$c->param('d') ? : 4 3290 3294
($c->param('srccol') // '') =~ /\A[A-Za-z_][A-Za-z0-9_]{0,63}\z/u ? : 0 3294 3294
Condition50%1/2
$c->param("srccol") // ""
l!l
03294
MC/DC0%0/1
$c->param("srccol") // ""
$c->param("srccol")
Truth table50%1/2
A
A= $c->param("srccol")
Aresult
11
00
3013 view_dedup => ($c->param('d') ? 1 : 0),
3014 # srccol= names the column that says which file a stacked row came from.
3015 view_srccol => (($c->param('srccol') // '') =~ /\A[A-Za-z_][A-Za-z0-9_]{0,63}\z/ ? $c->param('srccol') : ''),
3016 # lk=/nolk= turn a stored lookup on or off for this view, as name=value
3017 # pairs so the macro can write them back in the order they came.
3018 6588 view_lookups => [ map { my $k = $_; map { { name => $k, value => $_ } } grep { length } @{ $c->every_param($k) } } qw(lk nolk) ],
3019 # Names only: the rest of an entry is credentials.
3020 3294 ▶ mariadb_server_names => [ sort keys %{ $c->app->config('mariadb_servers') // {} } ],
Branch: 1 branch
BranchTrueFalseTotal
$jtype =~ /\A(?:left|inner|outer)\z/u ? : 2 3292 3294
Condition50%1/2
$c->app->config("mariadb_servers") // {}
l!l
03294
MC/DC0%0/1
$c->app->config("mariadb_servers") // {}
$c->app->config("mariadb_servers")
Truth table50%1/2
A
A= $c->app->config("mariadb_servers")
Aresult
11
00
3021 );
3022 143 });
3023  
3024 # Every page names the tutorial chapter that helps with it. The layout
3025 # turns this into a "Help: ..." link beside the main Tutorial link, so a
3026 # reader on the pie chart screen lands on the pie chart chapter. It lives
3027 # here rather than in every action: a new action is one entry in the action
3028 # map in Database::BI::Tutorial, and t/tutorial.t checks it is there.
3029 3300 ▶ $self->hook(before_render => sub {
Subroutine __ANON__: called CC=34 SCAR=38.8
3030 3300 my ($c, $args) = @_;
3031  
3032 # The language is the one the action already chose, if it got that far
3033 # (_resolve_template is protected, so it cannot be asked from here).
3034 147 ▶ my $page_template = sub {
Subroutine __ANON__: called CC=6 SCAR=18.6
3035 147 my ($name) = @_;
3036 147 my $conf = $c->app->config;
3037 147 ▶ my $platform = $conf->{platform} // 'web';
Condition100%2/2
$conf->{"platform"} // "web"
l!l
1416
MC/DC100%1/1
$conf->{"platform"} // "web"
$conf->{"platform"}
Truth table100%2/2
A
A= $conf->{"platform"}
Aresult
11
00
3038 147 ▶ my $language = $c->stash('language') // '';
Condition50%1/2
$c->stash("language") // ""
l!l
0147
MC/DC0%0/1
$c->stash("language") // ""
$c->stash("language")
Truth table50%1/2
A
A= $c->stash("language")
Aresult
11
00
3039 147 ▶ $language = $conf->{language} // 'en'
Branch: 1 branch
BranchTrueFalseTotal
unless $language =~ /\A[a-z]{2}(?:[-_][A-Za-z]{2})?\z/u and -d $c->app->home->child("templates/$platform/$language") 147 0 147
Condition60%3/5
$language =~ /\A[a-z]{2}(?:[-_][A-Za-z]{2})?\z/u and -d $c->app->home->child("templates/$platform/$language")
!ll&&!rl&&r
14700
$conf->{"language"} // "en"
l!l
1416
MC/DC0%0/2
$language =~ /\A[a-z]{2}(?:[-_][A-Za-z]{2})?\z/u and -d $c->app->home->child("templates/$platform/$language")
$language =~ /\A[a-z]{2}(?:[-_][A-Za-z]{2})?\z/u -d $c->app->home->child("templates/$platform/$language")
MC/DC100%1/1
$conf->{"language"} // "en"
$conf->{"language"}
Truth table33%1/3
A and B
A= $language =~ /\A[a-z]{2}(?:[-_][A-Za-z]{2})?\z/uB= -d $c->app->home->child("templates/$platform/$language")
ABresult
0X0
100
111
Truth table100%2/2
A
A= $conf->{"language"}
Aresult
11
00
3040 unless $language =~ /\A[a-z]{2}(?:[-_][A-Za-z]{2})?\z/
3041 && -d $c->app->home->child("templates/$platform/$language");
3042 147 $c->stash(language => $language);
3043 147 return "$platform/$language/$name";
3044 3300 };
3045  
3046 # A request refused in plain text is a dead end in a browser: no
3047 # navigation, and no way back but the Back button. A page the browser
3048 # navigated to -- a GET whose Accept names text/html, which fetch() and
3049 # scripts do not send -- gets the error page instead: the trail back to
3050 # the table, and the reason, escaped by the template. Everything else
3051 # keeps the plain text below.
3052 3300 ▶ my $status = $args->{status} // 0;
Condition100%2/2
$args->{"status"} // 0
l!l
15031797
MC/DC100%1/1
$args->{"status"} // 0
$args->{"status"}
Truth table100%2/2
A
A= $args->{"status"}
Aresult
11
00
3053 3300 ▶ if (defined $args->{text} && ($status == 400 || $status == 403)
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{"text"} and $status == 400 || $status == 403 and $c->req->method eq "GET" and ($c->req->headers->accept // "") =~ m[\btext/html\b]u and not $c->req->url->path->to_string =~ m[\A/api/]u) 0 3300 3300
Condition76%13/17
defined $args->{"text"} and $status == 400 || $status == 403 and $c->req->method eq "GET" and ($c->req->headers->accept // "") =~ m[\btext/html\b]u and not $c->req->url->path->to_string =~ m[\A/api/]u
!ll&&!rl&&r
330000
defined $args->{"text"} and $status == 400 || $status == 403 and $c->req->method eq "GET" and ($c->req->headers->accept // "") =~ m[\btext/html\b]u
!ll&&!rl&&r
26016990
defined $args->{"text"} and $status == 400 || $status == 403 and $c->req->method eq "GET"
!ll&&!rl&&r
25983699
defined $args->{"text"} and $status == 400 || $status == 403
!ll&&!rl&&r
2461137702
$status == 400 or $status == 403
l!l&&r!l&&!r
6948137
$c->req->headers->accept // ""
l!l
0699
MC/DC0%0/6
defined $args->{"text"} and $status == 400 || $status == 403 and $c->req->method eq "GET" and ($c->req->headers->accept // "") =~ m[\btext/html\b]u and not $c->req->url->path->to_string =~ m[\A/api/]u
defined $args->{"text"} $status == 400 $status == 403 $c->req->method eq "GET" $c->req->headers->accept not $c->req->url->path->to_string =~ m[\A/api/]u
Truth table50%5/10
A and B or C and D and E and not(F)
A= defined $args->{"text"}B= $status == 400C= $status == 403D= $c->req->method eq "GET"E= $c->req->headers->acceptF= not $c->req->url->path->to_string =~ m[\A/api/]u
ABCDEFresult
0XXXXX0
100XXX0
11X0XX0
1010XX0
11X10X0
10110X0
11X1100
1011100
11X1111
1011111
3054 && $c->req->method eq 'GET'
3055 && ($c->req->headers->accept // '') =~ m{\btext/html\b}
3056 && $c->req->url->path->to_string !~ m{\A/api/}) {
3057 $c->stash(
3058 title => $status == 403 ? 'This is not available here' : 'This page cannot be drawn',
3059 error_msg => delete $args->{text},
3060 0 ▶ error_400 => 1,
Branch: 1 branch
BranchTrueFalseTotal
$status == 403 ? : 0 0 0
3061 );
3062 0 $args->{template} = $page_template->('not_found');
3063 0 $args->{handler} = 'tt';
3064 0 $args->{format} = 'html';
3065 }
3066  
3067 # Mojolicious sends render(text => ...) as text/html. The error replies
3068 # that use it repeat what was asked for (a column, a range), so as HTML a
3069 # crafted link would run script on this site. A template or JSON escapes
3070 # for itself; plain text only has to say that it is plain text.
3071 $args->{format} //= 'txt'
3072 3300 ▶ if defined $args->{text} && !defined $c->stash('format');
Branch: 1 branch
BranchTrueFalseTotal
if defined $args->{"text"} and not defined $c->stash("format") 839 2461 3300
Condition60%3/5
defined $args->{"text"} and not defined $c->stash("format")
!ll&&!rl&&r
24610839
$args->{"format"} //= "txt"
l!l
0839
MC/DC50%1/2
defined $args->{"text"} and not defined $c->stash("format")
defined $args->{"text"} not defined $c->stash("format")
MC/DC0%0/1
$args->{"format"} //= "txt"
$args->{"format"}
Truth table66%2/3
A and not(B)
A= defined $args->{"text"}B= not defined $c->stash("format")
ABresult
0X0
100
111
Truth table50%1/2
A
A= $args->{"format"}
Aresult
11
00
3073  
3074 # AI availability flag used by dashboard and insights templates.
3075 3300 ▶ $c->stash(ai_available => (length($c->app->config('ai_api_key') // '') ? 1 : 0))
Branch: 2 branches
BranchTrueFalseTotal
unless defined $c->stash("ai_available") 3296 4 3300
length($c->app->config('ai_api_key') // '') ? : 87 3209 3296
Condition100%2/2
$c->app->config("ai_api_key") // ""
l!l
873209
MC/DC100%1/1
$c->app->config("ai_api_key") // ""
$c->app->config("ai_api_key")
Truth table100%2/2
A
A= $c->app->config("ai_api_key")
Aresult
11
00
3076 unless defined $c->stash('ai_available');
3077  
3078 # The chart pages and canvases read this from the stash. Resolving it
3079 # per request rather than once at startup means a deployment (and a
3080 # test) can point D3 at a local copy by changing the config.
3081 3300 my $d3_url = $c->app->config('d3_url');
3082 3300 ▶ $c->stash(d3_url =>
Branch: 1 branch
BranchTrueFalseTotal
defined $d3_url && !ref($d3_url) && length $d3_url ? : 2909 391 3300
Condition66%4/6
defined $d3_url and not ref $d3_url and length $d3_url
!ll&&!rl&&r
39102909
defined $d3_url and not ref $d3_url
!ll&&!rl&&r
39102909
MC/DC33%1/3
defined $d3_url and not ref $d3_url and length $d3_url
defined $d3_url not ref $d3_url length $d3_url
Truth table50%2/4
A and not(B) and C
A= defined $d3_urlB= not ref $d3_urlC= length $d3_url
ABCresult
0XX0
10X0
1100
1111
3083 (defined $d3_url && !ref $d3_url && length $d3_url)
3084 ? $d3_url : $DEFAULT_D3_URL);
3085  
3086 # Time range filters on a date or time column, so the table page
3087 # offers it only when the rows drawn have one (seven actions render
3088 # that page; this is the one place they all pass). A range already
3089 # in force keeps its column, so it can be changed or removed even
3090 # when it leaves no rows to judge by.
3091 3300 ▶ if (($args->{template} // '') =~ m{/dashboard\z}) {
Branch: 1 branch
BranchTrueFalseTotal
if (($args->{"template"} // "") =~ m[/dashboard\z]u) 348 2952 3300
Condition100%2/2
$args->{"template"} // ""
l!l
14001900
MC/DC100%1/1
$args->{"template"} // ""
$args->{"template"}
Truth table100%2/2
A
A= $args->{"template"}
Aresult
11
00
3092 348 require Database::BI::Controller::Dashboard;
3093 348 ▶ my $columns = $args->{columns} // $c->stash('columns');
Condition33%1/3
$args->{"columns"} // $c->stash("columns")
l!l&&r!l&&!r
34800
MC/DC0%0/2
$args->{"columns"} // $c->stash("columns")
$args->{"columns"} $c->stash("columns")
Truth table33%1/3
A // B
A= $args->{"columns"}B= $c->stash("columns")
ABresult
1X1
011
000
3094 348 ▶ my $records = $args->{records} // $c->stash('records');
Condition33%1/3
$args->{"records"} // $c->stash("records")
l!l&&r!l&&!r
34800
MC/DC0%0/2
$args->{"records"} // $c->stash("records")
$args->{"records"} $c->stash("records")
Truth table33%1/3
A // B
A= $args->{"records"}B= $c->stash("records")
ABresult
1X1
011
000
3095 348 my @time = @{ Database::BI::Controller::Dashboard::_time_columns($columns, $records) };
3096 348 my $active = $c->stash('time_range');
3097 push @time, $active->{col}
3098 0 ▶ if ref($active) eq 'HASH' && !grep { $_ eq $active->{col} } @time;
Branch: 1 branch
BranchTrueFalseTotal
if ref $active eq "HASH" and not grep({$_ eq $active->{"col"};} @time) 0 348 348
Condition33%1/3
ref $active eq "HASH" and not grep({$_ eq $active->{"col"};} @time)
!ll&&!rl&&r
34800
MC/DC0%0/2
ref $active eq "HASH" and not grep({$_ eq $active->{"col"};} @time)
ref $active eq "HASH" not grep({$_ eq $active->{"col"};} @time)
Truth table33%1/3
A and not(B)
A= ref $active eq "HASH"B= not grep({$_ eq $active->{"col"};} @time)
ABresult
0X0
100
111
3099 348 $args->{time_columns} = \@time;
3100 }
3101  
3102 # Mojolicious's own 404 page has no navigation and no breadcrumb; an
3103 # HTML one is drawn from our not_found template instead. Its first
3104 # try is "not_found.<mode>", so that is the one replaced. JSON
3105 # replies and exceptions keep the defaults.
3106 3300 ▶ if (($args->{template} // '') =~ /\Anot_found\.\w+\z/
Branch: 1 branch
BranchTrueFalseTotal
if (($args->{"template"} // "") =~ /\Anot_found\.\w+\z/u and (($args->{"format"} // $c->stash("format")) // "html") eq "html") 147 3153 3300
Condition60%6/10
($args->{"template"} // "") =~ /\Anot_found\.\w+\z/u and (($args->{"format"} // $c->stash("format")) // "html") eq "html"
!ll&&!rl&&r
31530147
$args->{"template"} // ""
l!l
14001900
($args->{"format"} // $c->stash("format")) // "html"
l!l
1470
$args->{"format"} // $c->stash("format")
l!l&&r!l&&!r
14700
MC/DC33%1/3
($args->{"template"} // "") =~ /\Anot_found\.\w+\z/u and (($args->{"format"} // $c->stash("format")) // "html") eq "html"
$args->{"template"} $args->{"format"} $c->stash("format")
Truth table50%2/4
A and B // C
A= $args->{"template"}B= $args->{"format"}C= $c->stash("format")
ABCresult
0XX0
1000
11X1
1011
3107 && ($args->{format} // $c->stash('format') // 'html') eq 'html') {
3108 147 $args->{template} = $page_template->('not_found');
3109 147 $args->{handler} = 'tt';
3110 147 $c->stash(title => 'Page not found');
3111 }
3112  
3113 # The breadcrumb trail (layouts/breadcrumb.html.tt), worked out from the
3114 # request's own URL, so every page has one and a new page gets one
3115 # without code of its own.
3116 3300 ▶ if (!defined $c->stash('trail')) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $c->stash("trail")) 3296 4 3300
3117 3296 require Database::BI::Controller::Dashboard;
3118 3296 $c->stash(trail => Database::BI::Controller::Dashboard::_breadcrumb_trail($c));
3119 }
3120  
3121 # The nav's Preferences link names this page with back=, so the
3122 # preferences page's trail leads back to it (Dashboard::_crumb_parent).
3123 3300 ▶ if (!defined $c->stash('preferences_url')) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $c->stash("preferences_url")) 3296 4 3300
3124 3296 require Database::BI::Controller::Dashboard;
3125 3296 $c->stash(preferences_url => Database::BI::Controller::Dashboard::_preferences_url($c));
3126 }
3127  
3128 3300 ▶ return if defined $c->stash('tutorial_chapter');
Branch: 1 branch
BranchTrueFalseTotal
if defined $c->stash("tutorial_chapter") 2 3298 3300
3129  
3130 3298 my $chapter = Database::BI::Tutorial->chapter_for_action($c->stash('action'));
3131 3298 ▶ return unless $chapter;
Branch: 1 branch
BranchTrueFalseTotal
unless $chapter 1305 1993 3298
3132  
3133 $c->stash(
3134 tutorial_chapter => $chapter->{id},
3135 tutorial_chapter_title => $chapter->{title},
3136 1993 );
3137 143 });
3138  
3139 # Factory helper: opens any named table from the configured data directory.
3140 # The directory=> option overrides the default so open_file and upload_file
3141 # can open tables from arbitrary filesystem paths.
3142 #
3143 # Joins are handled by Database::Join in the controller pipeline;
3144 # open_table returns a single DataSource per table.
3145 #
3146 # Resolved with the rule the controller's _data_dir_for applies: a relative
3147 # value is relative to the application home, an absolute one is used as
3148 # given. Mojo::File->child appends an absolute path instead of replacing
3149 # the base, so home->child($absolute) named a directory that cannot exist,
3150 # and /view - which opens its table without a directory of its own - read
3151 # from it and served an empty page.
3152 143 ▶ my $configured = $self->config->{data_dir} // 'data';
Condition100%2/2
$self->config->{"data_dir"} // "data"
l!l
10637
MC/DC100%1/1
$self->config->{"data_dir"} // "data"
$self->config->{"data_dir"}
Truth table100%2/2
A
A= $self->config->{"data_dir"}
Aresult
11
00
3153 143 my $data_path = Mojo::File->new($configured);
3154 143 ▶ $data_path = $self->home->child($configured) unless $data_path->is_abs;
Branch: 1 branch
BranchTrueFalseTotal
unless $data_path->is_abs 137 6 143
3155 143 my $data_dir = $data_path->to_string;
3156  
3157 # In-process CHI cache: shared across all requests in the same worker process.
3158 # The Memory driver needs no external services and works out of the box.
3159 # Set global => 1 so the same namespace is reused across multiple open_table
3160 # calls within one process rather than creating separate isolated caches.
3161 143 ▶ my $cache_conf = $self->config->{cache} // {};
Condition50%1/2
$self->config->{"cache"} // {}
l!l
0143
MC/DC0%0/1
$self->config->{"cache"} // {}
$self->config->{"cache"}
Truth table50%1/2
A
A= $self->config->{"cache"}
Aresult
11
00
3162 143 ▶ my $cache_ttl_url = $cache_conf->{ttl_url} // $DEFAULT_CACHE_TTL_URL;
Condition66%2/3
$cache_conf->{"ttl_url"} // $DEFAULT_CACHE_TTL_URL
l!l&&r!l&&!r
013310
MC/DC50%1/2
$cache_conf->{"ttl_url"} // $DEFAULT_CACHE_TTL_URL
$cache_conf->{"ttl_url"} $DEFAULT_CACHE_TTL_URL
Truth table66%2/3
A // B
A= $cache_conf->{"ttl_url"}B= $DEFAULT_CACHE_TTL_URL
ABresult
1X1
011
000
3163 my $chi = CHI->new(
3164 143 ▶ driver => $cache_conf->{driver} // 'Memory',
Condition50%1/2
$cache_conf->{"driver"} // "Memory"
l!l
0143
MC/DC0%0/1
$cache_conf->{"driver"} // "Memory"
$cache_conf->{"driver"}
Truth table50%1/2
A
A= $cache_conf->{"driver"}
Aresult
11
00
3165 global => 1,
3166 namespace => 'Database::BI',
3167 _table_cache_root($self, $cache_conf),
3168 );
3169  
3170 2000 ▶ $self->helper(open_table => sub($c, $table, %opts) {
Subroutine __ANON__: called CC=13 SCAR=27.5
3171 # URL mode: fetch a remote HTML table directly via Database::Abstraction's
3172 # URL backend (LWP::UserAgent + HTML::TableExtract).
3173 2000 ▶ if (exists $opts{url}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opts{"url"}) 48 1952 2000
3174 return Database::BI::Model::DataSource->new(
3175 url => $opts{url},
3176 cache => $chi,
3177 cache_ttl_url => $cache_ttl_url,
3178 private_hosts => $c->app->config('url_private_hosts') // [],
3179 exists $opts{html_table_index}
3180 ? (html_table_index => $opts{html_table_index})
3181 48 ▶ : (),
Branch: 1 branch
BranchTrueFalseTotal
exists $opts{'html_table_index'} ? : 28 20 48
Condition50%1/2
$c->app->config("url_private_hosts") // []
l!l
048
MC/DC0%0/1
$c->app->config("url_private_hosts") // []
$c->app->config("url_private_hosts")
Truth table50%1/2
A
A= $c->app->config("url_private_hosts")
Aresult
11
00
3182 );
3183 }
3184 # Redis mode: connect to a Redis server via Database::Abstraction's
3185 # Redis backend (Redis::Fast or Redis).
3186 1952 ▶ if (exists $opts{redis}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opts{"redis"}) 0 1952 1952
3187 return Database::BI::Model::DataSource->new(
3188 table => $table,
3189 redis => $opts{redis},
3190 0 cache => $chi,
3191 cache_ttl_url => $cache_ttl_url,
3192 );
3193 }
3194 # MariaDB mode: connect to an entry of the mariadb_servers configuration.
3195 1952 ▶ if (exists $opts{mariadb}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opts{"mariadb"}) 0 1952 1952
3196 return Database::BI::Model::DataSource->new(
3197 table => $table,
3198 server => $opts{mariadb},
3199 mariadb => ($c->app->config('mariadb_servers') // {})->{ $opts{mariadb} },
3200 0 ▶ );
Condition0%0/2
$c->app->config("mariadb_servers") // {}
l!l
00
MC/DC0%0/1
$c->app->config("mariadb_servers") // {}
$c->app->config("mariadb_servers")
Truth table0%0/2
A
A= $c->app->config("mariadb_servers")
Aresult
11
00
3201 }
3202 1952 ▶ my $dir = exists $opts{directory} ? $opts{directory} : $data_dir;
Branch: 1 branch
BranchTrueFalseTotal
exists $opts{'directory'} ? : 1793 159 1952
3203 Database::BI::Model::DataSource->new(
3204 directory => $dir,
3205 table => $table,
3206 cache => $chi,
3207 cache_ttl_url => $cache_ttl_url,
3208 exists $opts{host} ? (host => $opts{host}) : (),
3209 exists $opts{file_ext} ? (file_ext => $opts{file_ext}) : (),
3210 exists $opts{internal_table} ? (internal_table => $opts{internal_table}) : (),
3211 1952 ▶ exists $opts{column_order} ? (column_order => $opts{column_order}) : (),
Branch: 5 branches
BranchTrueFalseTotal
exists $opts{'host'} ? : 9 1943 1952
exists $opts{'file_ext'} ? : 9 1943 1952
exists $opts{'internal_table'} ? : 1 1951 1952
exists $opts{'column_order'} ? : 2 1950 1952
$c->app->config('json_flatten') ? : 0 1952 1952
3212 json_flatten => $c->app->config('json_flatten') ? 1 : 0,
3213 );
3214 143 });
3215  
3216 143 my $r = $self->routes();
3217  
3218 # Reached without logging in: the login itself, and the share and embed
3219 # links, whose signed, expiring token is their own permission. Everything
3220 # else goes through require_login, which lets every request in when no
3221 # password_hash is set.
3222 143 $r->get('/login') ->to('Dashboard#login_form');
3223 143 $r->post('/login') ->to('Dashboard#login');
3224 143 $r->post('/logout') ->to('Dashboard#logout');
3225 143 $r->get('/share/:id')->to('Dashboard#share_view');
3226 143 $r->get('/embed/:id')->to('Dashboard#embed_view');
3227 143 $r = $r->under('/')->to('Dashboard#require_login');
3228  
3229 143 $r->get('/')->to('Dashboard#index');
3230 143 $r->get('/tutorial')->to('Dashboard#tutorial');
3231 143 $r->get('/preferences')->to('Dashboard#preferences');
3232 143 $r->get('/view/:table')->to('Dashboard#view');
3233 143 $r->get('/browse')->to('Dashboard#browse');
3234 143 $r->get('/open')->to('Dashboard#open_file');
3235 143 $r->get('/join')->to('Dashboard#join_tables');
3236 143 $r->get('/api/columns')->to('Dashboard#columns_api');
3237 143 $r->get('/api/range')->to('Dashboard#range_api');
3238 143 $r->get('/import')->to('Dashboard#import_url');
3239 143 $r->get('/combine')->to('Dashboard#combine_tables');
3240 143 $r->get('/export')->to('Dashboard#export_data');
3241 143 $r->post('/export')->to('Dashboard#export_write');
3242 143 $r->get('/api/dirs')->to('Dashboard#dirs_api');
3243 143 $r->get('/api/stat')->to('Dashboard#stat_api');
3244 143 $r->post('/upload')->to('Dashboard#upload_file');
3245 143 $r->post('/uploads/clear')->to('Dashboard#clear_uploads');
3246 143 $r->get('/graph')->to('Dashboard#graph_view');
3247 143 $r->get('/pie')->to('Dashboard#pie_view');
3248 143 $r->get('/heatmap')->to('Dashboard#heatmap_view');
3249 143 $r->get('/bar')->to('Dashboard#bar_view');
3250 143 $r->get('/folder')->to('Dashboard#folder_view');
3251 143 $r->get('/tables')->to('Dashboard#tables_view');
3252 143 $r->get('/pivot')->to('Dashboard#pivot_view');
3253 143 $r->get('/stats')->to('Dashboard#stats_view');
3254 143 $r->post('/calc/save') ->to('Dashboard#calc_save');
3255 143 $r->post('/calc/delete') ->to('Dashboard#calc_delete');
3256 143 $r->get('/calc/list') ->to('Dashboard#calc_list');
3257 143 $r->post('/groups/save') ->to('Dashboard#groups_save');
3258 143 $r->post('/groups/delete')->to('Dashboard#groups_delete');
3259 143 $r->get('/groups/list') ->to('Dashboard#groups_list');
3260 143 $r->post('/dates/save') ->to('Dashboard#dates_save');
3261 143 $r->post('/dates/delete') ->to('Dashboard#dates_delete');
3262 143 $r->get('/dates/list') ->to('Dashboard#dates_list');
3263 143 $r->post('/lookups/save') ->to('Dashboard#lookups_save');
3264 143 $r->post('/lookups/delete')->to('Dashboard#lookups_delete');
3265 143 $r->get('/lookups/list') ->to('Dashboard#lookups_list');
3266 143 $r->post('/extract/save') ->to('Dashboard#extract_save');
3267 143 $r->post('/extract/delete')->to('Dashboard#extract_delete');
3268 143 $r->get('/extract/list') ->to('Dashboard#extract_list');
3269 143 $r->post('/geo/save') ->to('Dashboard#geo_save');
3270 143 $r->post('/geo/delete') ->to('Dashboard#geo_delete');
3271 143 $r->post('/geo/lookup') ->to('Dashboard#geo_lookup');
3272 143 $r->post('/geo/boundary') ->to('Dashboard#geo_boundary');
3273 143 $r->get('/geo/list') ->to('Dashboard#geo_list');
3274 143 $r->get('/scatter') ->to('Dashboard#scatter_view');
3275 143 $r->get('/stacked') ->to('Dashboard#stacked_view');
3276 143 $r->get('/combo') ->to('Dashboard#combo_view');
3277 143 $r->get('/treemap') ->to('Dashboard#treemap_view');
3278 143 $r->get('/histogram') ->to('Dashboard#histogram_view');
3279 143 $r->get('/wordcloud') ->to('Dashboard#wordcloud_view');
3280 143 $r->get('/map') ->to('Dashboard#map_view');
3281 143 $r->get('/line') ->to('Dashboard#graph_view'); # alias for /graph
3282 143 $r->post('/api/ask') ->to('Dashboard#ask_api');
3283 143 $r->get('/insights') ->to('Dashboard#insights_view');
3284 143 $r->post('/api/summary') ->to('Dashboard#summary_api');
3285  
3286 # Saved analyses
3287 # /api/analyses/import must be registered BEFORE /api/analyses/:id so that the
3288 # literal segment "import" is matched before the :id placeholder captures it.
3289 143 $r->get('/a/:id') ->to('Dashboard#canvas_render');
3290 143 $r->get('/api/analyses') ->to('Dashboard#analyses_list');
3291 143 $r->post('/api/analyses') ->to('Dashboard#analyses_create');
3292 143 $r->post('/api/analyses/import') ->to('Dashboard#analyses_import');
3293 143 $r->get('/api/analyses/:id') ->to('Dashboard#analyses_get');
3294 143 $r->put('/api/analyses/:id') ->to('Dashboard#analyses_update');
3295 143 $r->patch('/api/analyses/:id') ->to('Dashboard#analyses_patch'); $r->delete('/api/analyses/:id') ->to('Dashboard#analyses_delete');
3296 143 $r->post('/api/analyses/:id/visuals')->to('Dashboard#analyses_add_visual');
3297 143 $r->patch('/api/analyses/:id/visuals/:visual')->to('Dashboard#analyses_update_visual');
3298 143 $r->delete('/api/analyses/:id/visuals/:visual')->to('Dashboard#analyses_delete_visual');
3299 143 $r->get('/api/analyses/:id/export') ->to('Dashboard#analyses_export');
3300  
3301 # extracts, catalog, sharing, embedding, per-visual downloads
3302 143 $r->get('/canvases') ->to('Dashboard#canvases_view');
3303 143 $r->get('/catalog') ->to('Dashboard#catalog_view');
3304 143 $r->get('/a/:id/visual/:n/:fmt') ->to('Dashboard#visual_download');
3305 143 $r->post('/api/analyses/:id/share') ->to('Dashboard#analyses_share');
3306  
3307 # Evict stale upload subdirectories on every startup so the cache cannot
3308 # grow unboundedly across server restarts. Only entries whose mtime is
3309 # older than $UPLOAD_MAX_AGE_S seconds are removed; recent uploads that
3310 # were made while the previous server process was running are preserved.
3311 143 _evict_old_uploads($self->_uploads_dir, $UPLOAD_MAX_AGE_S);
3312 }
3313  
3314 # _uploads_dir() -> Mojo::File
3315 #
3316 # Purpose: The one place that decides where POST /upload stages its files.
3317 # Entry: $self->config->{uploads_dir} may be unset (the default), a path
3318 # relative to the application home, or an absolute path.
3319 # Exit: A Mojo::File; the directory may not exist yet.
3320 #
3321 # upload_file, clear_uploads and the startup eviction all resolve the
3322 # directory through here, so a configured staging directory is written to and
3323 # purged as one. Resolving it per call rather than once in startup() is what
3324 # lets a caller - a test in particular - point one application instance at its
3325 # own directory without touching the shared <home>/.uploads that another
3326 # process may be clearing at the same moment.
3327 189 ▶sub _uploads_dir ($self) {
Subroutine _uploads_dir: called CC=5 SCAR=16.1
3328 189 my $dir = $self->config->{uploads_dir};
3329 189 ▶ return $self->home->child('.uploads')
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dir and not ref $dir and length $dir 117 72 189
Condition100%6/6
defined $dir and not ref $dir and length $dir
!ll&&!rl&&r
116172
defined $dir and not ref $dir
!ll&&!rl&&r
114273
MC/DC100%3/3
defined $dir and not ref $dir and length $dir
defined $dir not ref $dir length $dir
Truth table100%4/4
A and not(B) and C
A= defined $dirB= not ref $dirC= length $dir
ABCresult
0XX0
10X0
1100
1111
3330 unless defined $dir && !ref $dir && length $dir;
3331  
3332 72 my $path = Mojo::File->new($dir);
3333 72 ▶ return $path->is_abs ? $path : $self->home->child($dir);
Branch: 1 branch
BranchTrueFalseTotal
$path->is_abs ? : 70 2 72
3334 }
3335  
3336 # _evict_old_uploads( $uploads_dir, $max_age_s ) -> void
3337 #
3338 # Purpose: Remove upload subdirectory trees whose mtime is older than $max_age_s
3339 # seconds. Runs at startup and is also called by clear_uploads (via the
3340 # Dashboard controller) when the user explicitly requests a purge.
3341 # Entry: $uploads_dir is a Mojo::File. $max_age_s is a positive integer.
3342 # Exit: Silent on success. Individual remove_tree failures are non-fatal.
3343 147 ▶sub _evict_old_uploads {
Subroutine _evict_old_uploads: called CC=2 SCAR=7.0
3344 147 my ($uploads_dir, $max_age_s) = @_;
3345 147 ▶ return unless -d $uploads_dir;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $uploads_dir 81 66 147
3346  
3347 66 my $cutoff = time() - $max_age_s;
3348  
3349 15 ▶ $uploads_dir->list({ dir => 1 })->each(sub {
Subroutine __ANON__: called CC=5 SCAR=16.2
3350 15 my ($entry) = @_;
3351 15 ▶ my $mtime = (stat $entry)[9] // 0;
Condition50%1/2
(stat $entry)[9] // 0
l!l
150
MC/DC0%0/1
(stat $entry)[9] // 0
(stat $entry)[9]
Truth table50%1/2
A
A= (stat $entry)[9]
Aresult
11
00
3352 15 ▶ return if $mtime >= $cutoff; # still fresh -- keep it
Branch: 1 branch
BranchTrueFalseTotal
if $mtime >= $cutoff 11 4 15
3353 4 ▶ if (-d $entry) {
Branch: 2 branches
BranchTrueFalseTotal
if (-d $entry) { } 3 1 4
elsif (-f $entry) { } 1 0 1
3354 3 $entry->remove_tree;
3355 } elsif (-f $entry) {
3356 1 unlink $entry->to_string;
3357 }
3358 66 });
3359 }
3360  
3361 # _cross_origin_opener_policy( \%config ) -> $value | undef
3362 #
3363 # Purpose: The Cross-Origin-Opener-Policy header a page carries.
3364 # Entry: The config. cross_origin_opener_policy is one of %COOP_VALUES
3365 # ('' or 0 sends none); without it, $DEFAULT_COOP.
3366 # Exit: The value, or undef for none. One changed after startup to a value
3367 # not in the list is not sent.
3368 1404 ▶sub _cross_origin_opener_policy {
Subroutine _cross_origin_opener_policy: called CC=7 SCAR=19.5
3369 1404 my ($config) = @_;
3370 1404 ▶ my $value = ($config // {})->{cross_origin_opener_policy};
Condition50%1/2
$config // {}
l!l
14040
MC/DC0%0/1
$config // {}
$config
Truth table50%1/2
A
A= $config
Aresult
11
00
3371 1404 ▶ return $DEFAULT_COOP unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 1397 7 1404
3372 7 ▶ return if ref $value || !length($value) || $value eq '0';
Branch: 1 branch
BranchTrueFalseTotal
if ref $value or not length $value or $value eq 0 3 4 7
Condition100%6/6
ref $value or not length $value or $value eq 0
l!l&&r!l&&!r
214
ref $value or not length $value
l!l&&r!l&&!r
115
MC/DC100%3/3
ref $value or not length $value or $value eq 0
ref $value not length $value $value eq 0
Truth table100%4/4
A or not(B) or C
A= ref $valueB= not length $valueC= $value eq 0
ABCresult
1XX1
01X1
0011
0000
3373 4 ▶ return $COOP_VALUES{$value} ? $value : undef;
Branch: 1 branch
BranchTrueFalseTotal
$COOP_VALUES{$value} ? : 1 3 4
3374 }
3375  
3376 # _check_cross_origin_opener_policy( $value ) -> void
3377 #
3378 # Purpose: Refuse a cross_origin_opener_policy a browser would not read.
3379 # Entry: The config value.
3380 # Exit: Returns; croaks on anything but undef, '', 0 or a known value.
3381 161 ▶sub _check_cross_origin_opener_policy {
Subroutine _check_cross_origin_opener_policy: called CC=7 SCAR=19.5
3382 161 my ($value) = @_;
3383 161 ▶ return if !defined $value || (!ref $value && (!length($value) || $value eq '0' || $COOP_VALUES{$value}));
Branch: 1 branch
BranchTrueFalseTotal
if not defined $value or not ref $value and !length($value) || $value eq 0 || $COOP_VALUES{$value} 152 9 161
Condition100%12/12
not defined $value or not ref $value and !length($value) || $value eq 0 || $COOP_VALUES{$value}
l!l&&r!l&&!r
14669
not ref $value and !length($value) || $value eq 0 || $COOP_VALUES{$value}
!ll&&!rl&&r
276
not length $value or $value eq 0 or $COOP_VALUES{$value}
l!l&&r!l&&!r
247
not length $value or $value eq 0
l!l&&r!l&&!r
1111
MC/DC100%5/5
not defined $value or not ref $value and !length($value) || $value eq 0 || $COOP_VALUES{$value}
not defined $value not ref $value not length $value $value eq 0 $COOP_VALUES{$value}
Truth table100%6/6
not(A) or not(B) and not(C) or D or E
A= not defined $valueB= not ref $valueC= not length $valueD= $value eq 0E= $COOP_VALUES{$value}
ABCDEresult
1XXXX1
011XX1
0101X1
010011
00XXX0
010000
3384 9 ▶ croak sprintf("cross_origin_opener_policy: '%s' is not one of %s, or 0 for none",
Branch: 1 branch
BranchTrueFalseTotal
ref $value ? : 2 7 9
3385 ref $value ? ref $value : $value, join(', ', sort keys %COOP_VALUES));
3386 }
3387  
3388 # _permissions_policy( \%config ) -> $value | undef
3389 #
3390 # Purpose: The Permissions-Policy header every reply carries.
3391 # Entry: The config. permissions_policy is the value to send, as written
3392 # ('' or 0 sends none); without it, $DEFAULT_PERMISSIONS_POLICY.
3393 # Exit: The value, or undef for none. One changed after startup to text
3394 # that is not printable ASCII is not sent (_check_permissions_policy
3395 # refuses it at startup), so it cannot carry a line break.
3396 3315 ▶sub _permissions_policy {
Subroutine _permissions_policy: called CC=7 SCAR=19.5
3397 3315 my ($config) = @_;
3398 3315 ▶ my $value = ($config // {})->{permissions_policy};
Condition100%2/2
$config // {}
l!l
33141
MC/DC100%1/1
$config // {}
$config
Truth table100%2/2
A
A= $config
Aresult
11
00
3399 3315 ▶ return $DEFAULT_PERMISSIONS_POLICY unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 3303 12 3315
3400 12 ▶ return if ref $value || !length($value) || $value eq '0';
Branch: 1 branch
BranchTrueFalseTotal
if ref $value or not length $value or $value eq 0 4 8 12
Condition100%6/6
ref $value or not length $value or $value eq 0
l!l&&r!l&&!r
318
ref $value or not length $value
l!l&&r!l&&!r
219
MC/DC100%3/3
ref $value or not length $value or $value eq 0
ref $value not length $value $value eq 0
Truth table100%4/4
A or not(B) or C
A= ref $valueB= not length $valueC= $value eq 0
ABCresult
1XX1
01X1
0011
0000
3401 8 ▶ return $value =~ /\A[\x20-\x7e]+\z/ ? $value : undef;
Branch: 1 branch
BranchTrueFalseTotal
$value =~ /\A[\x20-\x7e]+\z/u ? : 1 7 8
3402 }
3403  
3404 # _check_permissions_policy( $value ) -> void
3405 #
3406 # Purpose: Refuse a permissions_policy that cannot be a header value.
3407 # Entry: The config value.
3408 # Exit: Returns; croaks on a reference or on text that is not printable
3409 # ASCII. The features themselves are the browser's to judge.
3410 160 ▶sub _check_permissions_policy {
Subroutine _check_permissions_policy: called CC=4 SCAR=13.9
3411 160 my ($value) = @_;
3412 160 ▶ return if !defined $value || (!ref $value && $value =~ /\A(?:[\x20-\x7e]*)\z/);
Branch: 1 branch
BranchTrueFalseTotal
if not defined $value or not ref $value and $value =~ /\A(?:[\x20-\x7e]*)\z/u 150 10 160
Condition100%6/6
not defined $value or not ref $value and $value =~ /\A(?:[\x20-\x7e]*)\z/u
l!l&&r!l&&!r
146410
not ref $value and $value =~ /\A(?:[\x20-\x7e]*)\z/u
!ll&&!rl&&r
374
MC/DC100%3/3
not defined $value or not ref $value and $value =~ /\A(?:[\x20-\x7e]*)\z/u
not defined $value not ref $value $value =~ /\A(?:[\x20-\x7e]*)\z/u
Truth table100%4/4
not(A) or not(B) and C
A= not defined $valueB= not ref $valueC= $value =~ /\A(?:[\x20-\x7e]*)\z/u
ABCresult
1XX1
0111
00X0
0100
3413 10 croak 'permissions_policy must be a header value, such as "camera=(), geolocation=()", or 0 for none';
3414 }
3415  
3416 # _strict_transport_security( $c ) -> $value | undef
3417 #
3418 # Purpose: The Strict-Transport-Security header for this reply, if any.
3419 # Entry: The controller. Config strict_transport_security is the value to
3420 # send ('' or 0 sends none); without it, $DEFAULT_HSTS.
3421 # Exit: The value, or undef when none is to be sent.
3422 #
3423 # Only a request that came over https gets it: a browser ignores the header
3424 # over http, and a reply that came through a proxy is https only when
3425 # Mojolicious is told to trust the proxy (MOJO_REVERSE_PROXY=1, hypnotoad's
3426 # proxy => 1) and the proxy says X-Forwarded-Proto: https. Never for
3427 # localhost or an IP address: the header binds the host, not the port, so
3428 # from https://localhost:8443 it would send every other server on that
3429 # machine, morbo included, to https; and RFC 6797 has browsers ignore it for
3430 # an IP address. A value the configuration changed to after startup is sent
3431 # only if it is still well formed.
3432 3322 ▶sub _strict_transport_security {
Subroutine _strict_transport_security: called CC=14 SCAR=26.4
3433 3322 my ($c) = @_;
3434 3322 ▶ return unless $c->req->is_secure;
Branch: 1 branch
BranchTrueFalseTotal
unless $c->req->is_secure 3302 20 3322
3435  
3436 20 ▶ my $host = lc($c->req->url->to_abs->host // '');
Condition50%1/2
$c->req->url->to_abs->host // ""
l!l
200
MC/DC0%0/1
$c->req->url->to_abs->host // ""
$c->req->url->to_abs->host
Truth table50%1/2
A
A= $c->req->url->to_abs->host
Aresult
11
00
3437 20 ▶ return if $host eq '' || $host eq 'localhost' || $host =~ /\.localhost\z/
Branch: 1 branch
BranchTrueFalseTotal
if $host eq "" or $host eq "localhost" or $host =~ /\.localhost\z/u or $host =~ /\A\d{1,3}(?:\.\d{1,3}){3}\z/u or $host =~ /:/u or $host =~ /\A\[/u 10 10 20
Condition93%14/15
$host eq "" or $host eq "localhost" or $host =~ /\.localhost\z/u or $host =~ /\A\d{1,3}(?:\.\d{1,3}){3}\z/u or $host =~ /:/u or $host =~ /\A\[/u
l!l&&r!l&&!r
10010
$host eq "" or $host eq "localhost" or $host =~ /\.localhost\z/u or $host =~ /\A\d{1,3}(?:\.\d{1,3}){3}\z/u or $host =~ /:/u
l!l&&r!l&&!r
7310
$host eq "" or $host eq "localhost" or $host =~ /\.localhost\z/u or $host =~ /\A\d{1,3}(?:\.\d{1,3}){3}\z/u
l!l&&r!l&&!r
5213
$host eq "" or $host eq "localhost" or $host =~ /\.localhost\z/u
l!l&&r!l&&!r
3215
$host eq "" or $host eq "localhost"
l!l&&r!l&&!r
1217
MC/DC83%5/6
$host eq "" or $host eq "localhost" or $host =~ /\.localhost\z/u or $host =~ /\A\d{1,3}(?:\.\d{1,3}){3}\z/u or $host =~ /:/u or $host =~ /\A\[/u
$host eq "" $host eq "localhost" $host =~ /\.localhost\z/u $host =~ /\A\d{1,3}(?:\.\d{1,3}){3}\z/u $host =~ /:/u $host =~ /\A\[/u
Truth table85%6/7
A or B or C or D or E or F
A= $host eq ""B= $host eq "localhost"C= $host =~ /\.localhost\z/uD= $host =~ /\A\d{1,3}(?:\.\d{1,3}){3}\z/uE= $host =~ /:/uF= $host =~ /\A\[/u
ABCDEFresult
1XXXXX1
01XXXX1
001XXX1
0001XX1
00001X1
0000011
0000000
3438 || $host =~ /\A\d{1,3}(?:\.\d{1,3}){3}\z/ || $host =~ /:/ || $host =~ /\A\[/;
3439  
3440 10 my $value = $c->app->config('strict_transport_security');
3441 10 ▶ return $DEFAULT_HSTS unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 3 7 10
3442 7 ▶ return if ref $value || !length($value) || $value eq '0';
Branch: 1 branch
BranchTrueFalseTotal
if ref $value or not length $value or $value eq 0 3 4 7
Condition100%6/6
ref $value or not length $value or $value eq 0
l!l&&r!l&&!r
214
ref $value or not length $value
l!l&&r!l&&!r
115
MC/DC100%3/3
ref $value or not length $value or $value eq 0
ref $value not length $value $value eq 0
Truth table100%4/4
A or not(B) or C
A= ref $valueB= not length $valueC= $value eq 0
ABCresult
1XX1
01X1
0011
0000
3443 4 ▶ return $value =~ $HSTS_RE ? $value : undef;
Branch: 1 branch
BranchTrueFalseTotal
$value =~ /$HSTS_RE/u ? : 1 3 4
3444 }
3445  
3446 # _check_strict_transport_security( $value ) -> void
3447 #
3448 # Purpose: Refuse a strict_transport_security that a browser would not read.
3449 # Entry: The config value: undef, '' or 0 (none), or a header value.
3450 # Exit: Returns; croaks on anything else.
3451 168 ▶sub _check_strict_transport_security {
Subroutine _check_strict_transport_security: called CC=8 SCAR=20.8
3452 168 my ($value) = @_;
3453 168 ▶ return if !defined $value || (!ref $value && (!length($value) || $value eq '0'));
Branch: 1 branch
BranchTrueFalseTotal
if not defined $value or not ref $value and !length($value) || $value eq 0 148 20 168
Condition100%9/9
not defined $value or not ref $value and !length($value) || $value eq 0
l!l&&r!l&&!r
146220
not ref $value and !length($value) || $value eq 0
!ll&&!rl&&r
1192
not length $value or $value eq 0
l!l&&r!l&&!r
1119
MC/DC100%4/4
not defined $value or not ref $value and !length($value) || $value eq 0
not defined $value not ref $value not length $value $value eq 0
Truth table100%5/5
not(A) or not(B) and not(C) or D
A= not defined $valueB= not ref $valueC= not length $valueD= $value eq 0
ABCDresult
1XXX1
011X1
01011
00XX0
01000
3454 20 ▶ return if !ref $value && $value =~ $HSTS_RE;
Branch: 1 branch
BranchTrueFalseTotal
if not ref $value and $value =~ /$HSTS_RE/u 6 14 20
Condition100%3/3
not ref $value and $value =~ /$HSTS_RE/u
!ll&&!rl&&r
1136
MC/DC100%2/2
not ref $value and $value =~ /$HSTS_RE/u
not ref $value $value =~ /$HSTS_RE/u
Truth table100%3/3
not(A) and B
A= not ref $valueB= $value =~ /$HSTS_RE/u
ABresult
0X0
100
111
3455 14 ▶ croak sprintf("strict_transport_security: '%s' is not a header value such as 'max-age=31536000'"
Branch: 1 branch
BranchTrueFalseTotal
ref $value ? : 1 13 14
3456 . ' (optionally with includeSubDomains and preload), or 0 for none', ref $value ? ref $value : $value);
3457 }
3458  
3459 # _require_export_dirs_with_password( $hash, $export_dirs ) -> void
3460 #
3461 # Purpose: A server with a login is one other people use, so their exports
3462 # must be kept to folders of their own. Anywhere else, an export can
3463 # replace a .json or .csv another program obeys (a project's
3464 # package.json names commands npm runs) as the account running the
3465 # server.
3466 # Entry: Config password_hash and export_dirs (already checked).
3467 # Exit: Returns; croaks when there is a password and no export_dirs.
3468 157 ▶sub _require_export_dirs_with_password {
Subroutine _require_export_dirs_with_password: called CC=6 SCAR=17.9
3469 157 my ($hash, $dirs) = @_;
3470 157 ▶ return unless defined $hash && !ref $hash && length $hash;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $hash and not ref $hash and length $hash 148 9 157
Condition100%6/6
defined $hash and not ref $hash and length $hash
!ll&&!rl&&r
14719
defined $hash and not ref $hash
!ll&&!rl&&r
145210
MC/DC100%3/3
defined $hash and not ref $hash and length $hash
defined $hash not ref $hash length $hash
Truth table100%4/4
A and not(B) and C
A= defined $hashB= not ref $hashC= length $hash
ABCresult
0XX0
10X0
1100
1111
3471 9 ▶ return if ref($dirs) eq 'ARRAY' && @{$dirs};
Branch: 1 branch
BranchTrueFalseTotal
if ref $dirs eq "ARRAY" and @{$dirs;} 3 6 9
Condition100%3/3
ref $dirs eq "ARRAY" and @{$dirs;}
!ll&&!rl&&r
513
MC/DC100%2/2
ref $dirs eq "ARRAY" and @{$dirs;}
ref $dirs eq "ARRAY" @{$dirs;}
Truth table100%3/3
A and B
A= ref $dirs eq "ARRAY"B= @{$dirs;}
ABresult
0X0
100
111
3472 6 croak "export_dirs: with password_hash set, other people can save exports, so keep them to folders of their own: "
3473 . "add export_dirs => ['/srv/reports/exports'] to database_bi.conf (see \"Which folders it may use\" in perldoc Database::BI)";
3474 }
3475  
3476 # _check_login( $hash, $expiration ) -> void
3477 #
3478 # Purpose: Refuse a login configuration that would not do what it says.
3479 # Entry: Config password_hash (undef or '' for no login, else a hash made by
3480 # script/database-bi password) and login_expiration (undef, or
3481 # seconds, a whole number from 60).
3482 # Exit: Returns; croaks otherwise. A plain password in password_hash is
3483 # refused rather than hashed here, so it is never left in the file.
3484 155 ▶sub _check_login {
Subroutine _check_login: called CC=10 SCAR=23.3
3485 155 my ($hash, $expiration) = @_;
3486 155 ▶ if (defined $hash && (ref $hash || length $hash)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $hash and ref $hash || length $hash) 1 154 155
Condition50%3/6
defined $hash and ref $hash || length $hash
!ll&&!rl&&r
15401
ref $hash or length $hash
l!l&&r!l&&!r
010
MC/DC33%1/3
defined $hash and ref $hash || length $hash
defined $hash ref $hash length $hash
Truth table50%2/4
A and B or C
A= defined $hashB= ref $hashC= length $hash
ABCresult
0XX0
1000
11X1
1011
3487 1 require Database::BI::Password;
3488 1 ▶ croak 'password_hash: not a hash made by "script/database-bi password" (put the line it prints in database_bi.conf, not the password itself)'
Branch: 1 branch
BranchTrueFalseTotal
unless Database::BI::Password::is_password_hash($hash) 0 1 1
3489 unless Database::BI::Password::is_password_hash($hash);
3490 }
3491 155 ▶ croak sprintf("login_expiration: '%s' is not a number of seconds from 60", ref($expiration) || $expiration)
Branch: 1 branch
BranchTrueFalseTotal
if defined $expiration and ref $expiration || !($expiration =~ /\A[0-9]+\z/u) || $expiration < 60 7 148 155
Condition100%12/12
defined $expiration and ref $expiration || !($expiration =~ /\A[0-9]+\z/u) || $expiration < 60
!ll&&!rl&&r
14627
ref $expiration or not $expiration =~ /\A[0-9]+\z/u or $expiration < 60
l!l&&r!l&&!r
522
ref $expiration or not $expiration =~ /\A[0-9]+\z/u
l!l&&r!l&&!r
144
ref $expiration || $expiration
l!l&&r!l&&!r
142
MC/DC100%4/4
defined $expiration and ref $expiration || !($expiration =~ /\A[0-9]+\z/u) || $expiration < 60
defined $expiration ref $expiration not $expiration =~ /\A[0-9]+\z/u $expiration < 60
MC/DC100%2/2
ref $expiration || $expiration
ref $expiration $expiration
Truth table100%5/5
A and B or not(C) or D
A= defined $expirationB= ref $expirationC= not $expiration =~ /\A[0-9]+\z/uD= $expiration < 60
ABCDresult
0XXX0
10000
11XX1
101X1
10011
Truth table100%3/3
A || B
A= ref $expirationB= $expiration
ABresult
1X1
011
000
3492 if defined $expiration && (ref $expiration || $expiration !~ /\A[0-9]+\z/ || $expiration < 60);
3493 148 return;
3494 }
3495  
3496 # _require_password_if_open( $app, $listen, $hypnotoad ) -> void
3497 #
3498 # Purpose: Refuse to start where other machines could reach the server with no
3499 # password: everything it can read and write would then be theirs.
3500 # Entry: The application, MOJO_LISTEN as startup left it, and the hypnotoad
3501 # settings (used instead under hypnotoad).
3502 # Exit: Returns when every location is loopback or a password_hash is set;
3503 # croaks otherwise. The defaults (127.0.0.1, no password) start.
3504 #
3505 # A bare "morbo script/database-bi" listens on every interface (morbo opens
3506 # the port before it loads the application, so config listen never reaches
3507 # it), and now stops here; the message says to give it -l.
3508 145 ▶sub _require_password_if_open {
Subroutine _require_password_if_open: called CC=13 SCAR=28.7
3509 145 my ($app, $listen, $hypnotoad) = @_;
3510 145 my $hash = $app->config('password_hash');
3511 145 ▶ return if defined $hash && length $hash;
Branch: 1 branch
BranchTrueFalseTotal
if defined $hash and length $hash 1 144 145
Condition66%2/3
defined $hash and length $hash
!ll&&!rl&&r
14401
MC/DC50%1/2
defined $hash and length $hash
defined $hash length $hash
Truth table66%2/3
A and B
A= defined $hashB= length $hash
ABresult
0X0
100
111
3512  
3513 # Under hypnotoad (which sets HYPNOTOAD_APP) its own listen applies, and
3514 # MOJO_LISTEN does not.
3515 144 ▶ my @places = split /,/, $listen // '';
Condition50%1/2
$listen // ""
l!l
1440
MC/DC0%0/1
$listen // ""
$listen
Truth table50%1/2
A
A= $listen
Aresult
11
00
3516 0 @places = @{ $hypnotoad->{listen} }
3517 144 ▶ if $ENV{HYPNOTOAD_APP} && ref($hypnotoad) eq 'HASH' && ref($hypnotoad->{listen}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{"HYPNOTOAD_APP"} and ref $hypnotoad eq "HASH" and ref $hypnotoad->{"listen"} eq "ARRAY" 0 144 144
Condition33%2/6
$ENV{"HYPNOTOAD_APP"} and ref $hypnotoad eq "HASH" and ref $hypnotoad->{"listen"} eq "ARRAY"
!ll&&!rl&&r
14400
$ENV{"HYPNOTOAD_APP"} and ref $hypnotoad eq "HASH"
!ll&&!rl&&r
14400
MC/DC0%0/3
$ENV{"HYPNOTOAD_APP"} and ref $hypnotoad eq "HASH" and ref $hypnotoad->{"listen"} eq "ARRAY"
$ENV{"HYPNOTOAD_APP"} ref $hypnotoad eq "HASH" ref $hypnotoad->{"listen"} eq "ARRAY"
Truth table25%1/4
A and B and C
A= $ENV{"HYPNOTOAD_APP"}B= ref $hypnotoad eq "HASH"C= ref $hypnotoad->{"listen"} eq "ARRAY"
ABCresult
0XX0
10X0
1100
1111
3518 144 for my $place (@places) {
3519 144 ▶ my $host = lc(Mojo::URL->new($place)->host // '');
Condition50%1/2
"Mojo::URL"->new($place)->host // ""
l!l
1440
MC/DC0%0/1
"Mojo::URL"->new($place)->host // ""
"Mojo::URL"->new($place)->host
Truth table50%1/2
A
A= "Mojo::URL"->new($place)->host
Aresult
11
00
3520 144 ▶ next if $host eq 'localhost' || $host =~ /\A127\./ || $host eq '[::1]' || $host eq '::1';
Branch: 1 branch
BranchTrueFalseTotal
if $host eq "localhost" or $host =~ /\A127\./u or $host eq "[::1]" or $host eq "::1" 142 2 144
Condition66%6/9
$host eq "localhost" or $host =~ /\A127\./u or $host eq "[::1]" or $host eq "::1"
l!l&&r!l&&!r
14202
$host eq "localhost" or $host =~ /\A127\./u or $host eq "[::1]"
l!l&&r!l&&!r
14202
$host eq "localhost" or $host =~ /\A127\./u
l!l&&r!l&&!r
01422
MC/DC25%1/4
$host eq "localhost" or $host =~ /\A127\./u or $host eq "[::1]" or $host eq "::1"
$host eq "localhost" $host =~ /\A127\./u $host eq "[::1]" $host eq "::1"
Truth table40%2/5
A or B or C or D
A= $host eq "localhost"B= $host =~ /\A127\./uC= $host eq "[::1]"D= $host eq "::1"
ABCDresult
1XXX1
01XX1
001X1
00011
00000
3521 2 (my $shown = $place) =~ s/\?.*//;
3522 2 croak "listen: $shown can be reached from other machines, and there is no password. "
3523 . 'Set password_hash (make it with "script/database-bi password"), '
3524 . 'or listen on this machine only: listen => \'http://127.0.0.1:3000\' '
3525 . '(for hypnotoad, hypnotoad => { listen => [\'http://127.0.0.1:8080\'] }; for morbo, -l http://127.0.0.1:3000)';
3526 }
3527 142 return;
3528 }
3529  
3530 # _check_url_private_hosts( $value ) -> void
3531 #
3532 # Purpose: Refuse a url_private_hosts that is not a list of host names.
3533 # Entry: Config url_private_hosts: undef, or names ('reports.corp.example',
3534 # or '*.corp.example' for its subdomains) that a url: source or
3535 # /import may fetch although they resolve to a private address.
3536 # Exit: Returns; croaks otherwise. '*' alone is refused: it would turn the
3537 # check off for every name, which is what egress rules are for.
3538 145 ▶sub _check_url_private_hosts {
Subroutine _check_url_private_hosts: called CC=9 SCAR=41.5
3539 145 my ($value) = @_;
3540 145 ▶ return unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 145 0 145
3541 0 ▶ croak "url_private_hosts: give a list of host names, such as ['reports.corp.example']"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value eq "ARRAY" 0 0 0
3542 unless ref($value) eq 'ARRAY';
3543 0 for my $name (@{$value}) {
3544 0 ▶ croak sprintf("url_private_hosts: '%s' is not a host name such as 'reports.corp.example' or '*.corp.example'",
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and not ref $name and $name =~ /\A(?:\*\.)?[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)+\z/u 0 0 0
Condition0%0/11
defined $name and not ref $name and $name =~ /\A(?:\*\.)?[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)+\z/u
!ll&&!rl&&r
000
defined $name and not ref $name
!ll&&!rl&&r
000
(ref $name || $name) // "undef"
l!l
00
ref $name or $name
l!l&&r!l&&!r
000
MC/DC0%0/3
defined $name and not ref $name and $name =~ /\A(?:\*\.)?[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)+\z/u
defined $name not ref $name $name =~ /\A(?:\*\.)?[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)+\z/u
MC/DC0%0/2
(ref $name || $name) // "undef"
ref $name $name
Truth table0%0/4
A and not(B) and C
A= defined $nameB= not ref $nameC= $name =~ /\A(?:\*\.)?[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)+\z/u
ABCresult
0XX0
10X0
1100
1111
Truth table0%0/3
A or B
A= ref $nameB= $name
ABresult
1X1
011
000
3545 ref($name) || $name // 'undef')
3546 unless defined $name && !ref $name
3547 && $name =~ /\A(?:\*\.)?[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)+\z/;
3548 }
3549 0 return;
3550 }
3551  
3552 # _check_map_bounds_ranks( $value ) -> void
3553 #
3554 # Purpose: Refuse a map_bounds_ranks that would not choose the county outlines.
3555 # Entry: Config map_bounds_ranks: undef, or { country code => place rank },
3556 # such as { lk => 10 }: the rank of Nominatim's that is a county in
3557 # that country, over Boundary's own list.
3558 # Exit: Returns; croaks on anything but a hash of two-letter codes to 8, 10
3559 # or 12 (Boundary->new says which entry), since a mistyped one would
3560 # otherwise draw no outlines, or the wrong ones, without a word.
3561 145 ▶sub _check_map_bounds_ranks {
Subroutine _check_map_bounds_ranks: called CC=5 SCAR=29.7
3562 145 my ($value) = @_;
3563 145 ▶ return unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 145 0 145
3564 0 ▶ croak "map_bounds_ranks: give a hash of country codes to place ranks, such as { lk => 10 }"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value eq "HASH" 0 0 0
3565 unless ref($value) eq 'HASH';
3566 0 require Database::BI::Model::Boundary;
3567 0 my $ok = eval { Database::BI::Model::Boundary->check_ranks($value); 1 };
3568 0 ▶ return if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 0 0 0
3569 0 ▶ (my $error = $@ // 'unknown error') =~ s/ at \S+ line \d+\.?\n?\z//;
Condition0%0/2
$@ // "unknown error"
l!l
00
MC/DC0%0/1
$@ // "unknown error"
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
3570 0 croak "map_bounds_ranks: $error";
3571 }
3572  
3573 # _check_share_secret( $value ) -> void
3574 #
3575 # Purpose: Refuse a share_secret that would not keep share links private.
3576 # Entry: Config share_secret: undef or '' (a key derived from secrets), or
3577 # the key share and embed tokens are signed with.
3578 # Exit: Returns; croaks on a reference, fewer than 16 characters, or the
3579 # fixed string versions before 0.021.0 used when none was set, which
3580 # anyone can read in the source.
3581 154 ▶sub _check_share_secret {
Subroutine _check_share_secret: called CC=7 SCAR=19.5
3582 154 my ($value) = @_;
3583 154 ▶ return unless defined $value && (ref $value || length $value);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value and ref $value || length $value 147 7 154
Condition100%6/6
defined $value and ref $value || length $value
!ll&&!rl&&r
14617
ref $value or length $value
l!l&&r!l&&!r
161
MC/DC100%3/3
defined $value and ref $value || length $value
defined $value ref $value length $value
Truth table100%4/4
A and B or C
A= defined $valueB= ref $valueC= length $value
ABCresult
0XX0
1000
11X1
1011
3584 7 ▶ croak 'share_secret: give a string of at least 16 characters, or leave it out' if ref $value;
Branch: 1 branch
BranchTrueFalseTotal
if ref $value 1 6 7
3585 6 ▶ croak 'share_secret: that is the default from the source, which anyone can read; choose another'
Branch: 1 branch
BranchTrueFalseTotal
if $value eq "BI_DEFAULT_INSECURE_SECRET" 1 5 6
3586 if $value eq 'BI_DEFAULT_INSECURE_SECRET';
3587 5 ▶ croak 'share_secret: give at least 16 characters, so a share link cannot be forged by guessing it'
Branch: 1 branch
BranchTrueFalseTotal
if length $value < 16 2 3 5
3588 if length($value) < 16;
3589 3 return;
3590 }
3591  
3592 # _check_file_roots( $value, $home ) -> void
3593 #
3594 # Purpose: Refuse a file_roots that would not fence what it says.
3595 # Entry: Config file_roots: undef or [] (the whole filesystem), or a list of
3596 # folders, each absolute or relative to the application home.
3597 # Exit: Returns; croaks on anything but a list of folders that exist, since
3598 # a mistyped root would otherwise leave readers with nothing, or a
3599 # list that is not one would leave them everything.
3600 145 ▶sub _check_file_roots {
Subroutine _check_file_roots: called CC=11 SCAR=30.4
3601 145 my ($value, $home) = @_;
3602 145 ▶ return unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 144 1 145
3603 1 ▶ croak "file_roots: give a list of folders, such as ['/srv/data']" unless ref($value) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value eq "ARRAY" 0 1 1
3604 1 for my $root (@{$value}) {
3605 1 ▶ croak sprintf("file_roots: '%s' is not a folder name", ref($root) || $root // 'undef')
Branch: 1 branch
BranchTrueFalseTotal
unless defined $root and not ref $root and length $root 0 1 1
Condition18%2/11
defined $root and not ref $root and length $root
!ll&&!rl&&r
001
defined $root and not ref $root
!ll&&!rl&&r
001
(ref $root || $root) // "undef"
l!l
00
ref $root or $root
l!l&&r!l&&!r
000
MC/DC0%0/3
defined $root and not ref $root and length $root
defined $root not ref $root length $root
MC/DC0%0/2
(ref $root || $root) // "undef"
ref $root $root
Truth table25%1/4
A and not(B) and C
A= defined $rootB= not ref $rootC= length $root
ABCresult
0XX0
10X0
1100
1111
Truth table0%0/3
A or B
A= ref $rootB= $root
ABresult
1X1
011
000
3606 unless defined $root && !ref $root && length $root;
3607 1 ▶ my $dir = File::Spec->file_name_is_absolute($root) ? $root : $home->child($root)->to_string;
Branch: 1 branch
BranchTrueFalseTotal
'File::Spec'->file_name_is_absolute($root) ? : 1 0 1
3608 1 ▶ croak "file_roots: '$root' is not a folder that exists" unless -d $dir;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $dir 0 1 1
3609 }
3610 1 return;
3611 }
3612  
3613 # _check_export_dirs( $app, $value ) -> void
3614 #
3615 # Purpose: Refuse an export_dirs that would not confine exports as it says.
3616 # Entry: Config export_dirs: undef or [] (anywhere file_roots allows), or a
3617 # list of folders, relative ones under the application home.
3618 # Exit: Returns; croaks on what is not such a list, a folder that does not
3619 # exist, or one outside file_roots, where nothing could be saved.
3620 145 ▶sub _check_export_dirs {
Subroutine _check_export_dirs: called CC=17 SCAR=39.3
3621 145 my ($app, $value) = @_;
3622 145 ▶ return unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 144 1 145
3623 1 ▶ croak "export_dirs: give a list of folders, such as ['/srv/exports']" unless ref($value) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value eq "ARRAY" 0 1 1
3624 1 for my $dir (@{$value}) {
3625 1 ▶ croak sprintf("export_dirs: '%s' is not a folder name", ref($dir) || $dir // 'undef')
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dir and not ref $dir and length $dir 0 1 1
Condition18%2/11
defined $dir and not ref $dir and length $dir
!ll&&!rl&&r
001
defined $dir and not ref $dir
!ll&&!rl&&r
001
(ref $dir || $dir) // "undef"
l!l
00
ref $dir or $dir
l!l&&r!l&&!r
000
MC/DC0%0/3
defined $dir and not ref $dir and length $dir
defined $dir not ref $dir length $dir
MC/DC0%0/2
(ref $dir || $dir) // "undef"
ref $dir $dir
Truth table25%1/4
A and not(B) and C
A= defined $dirB= not ref $dirC= length $dir
ABCresult
0XX0
10X0
1100
1111
Truth table0%0/3
A or B
A= ref $dirB= $dir
ABresult
1X1
011
000
3626 unless defined $dir && !ref $dir && length $dir;
3627 1 ▶ my $path = File::Spec->file_name_is_absolute($dir) ? $dir : $app->home->child($dir)->to_string;
Branch: 1 branch
BranchTrueFalseTotal
'File::Spec'->file_name_is_absolute($dir) ? : 1 0 1
3628 1 ▶ croak "export_dirs: '$dir' is not a folder that exists" unless -d $path;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $path 0 1 1
3629 1 require Database::BI::Controller::Dashboard;
3630 1 my $roots = $app->config('file_roots');
3631 0 ▶ if (ref($roots) eq 'ARRAY' && @{$roots}) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $roots eq "ARRAY" and @{$roots;}) 0 1 1
Condition33%1/3
ref $roots eq "ARRAY" and @{$roots;}
!ll&&!rl&&r
100
MC/DC0%0/2
ref $roots eq "ARRAY" and @{$roots;}
ref $roots eq "ARRAY" @{$roots;}
Truth table33%1/3
A and B
A= ref $roots eq "ARRAY"B= @{$roots;}
ABresult
0X0
100
111
3632 0 my @real = Database::BI::Controller::Dashboard::_real_folders($app->build_controller, $roots,
3633 Database::BI::Controller::Dashboard::_data_dir_for($app), $app->_uploads_dir);
3634 0 ▶ croak "export_dirs: '$dir' is outside file_roots, so nothing could be saved there"
Branch: 1 branch
BranchTrueFalseTotal
unless Database::BI::Controller::Dashboard::_inside_any($path, @real) 0 0 0
3635 unless Database::BI::Controller::Dashboard::_inside_any($path, @real);
3636 }
3637 croak "export_dirs: '$dir' is a dot-folder, where exports are never saved"
3638 1 ▶ if grep { /\A\./ && $_ ne '.' && $_ ne '..' } File::Spec->splitdir(Mojo::File->new($path)->realpath->to_string);
Branch: 1 branch
BranchTrueFalseTotal
if grep {/\A\./u and $_ ne "." and $_ ne "..";} "File::Spec"->splitdir("Mojo::File"->new($path)->realpath->to_string) 0 1 1
Condition33%2/6
/\A\./u && $_ ne '.' && $_ ne '..'
!ll&&!rl&&r
300
/\A\./u and $_ ne "."
!ll&&!rl&&r
300
MC/DC0%0/3
/\A\./u && $_ ne '.' && $_ ne '..'
/\A\./u $_ ne "." $_ ne '..'
Truth table25%1/4
A and B && C
A= /\A\./uB= $_ ne "."C= $_ ne '..'
ABCresult
0XX0
10X0
1100
1111
3639 }
3640 1 return;
3641 }
3642  
3643 # _check_allowed_hosts( $value ) -> void
3644 #
3645 # Purpose: Refuse an allowed_hosts the request check could not use.
3646 # Entry: Config allowed_hosts: undef, or a list of host names, each a name
3647 # such as 'bi.example.com', '*.example.com' for its subdomains, or
3648 # '*' for every name.
3649 # Exit: Returns; croaks on anything else, since a list that does not say
3650 # what was meant either locks everyone out or lets the wrong site in.
3651 145 ▶sub _check_allowed_hosts {
Subroutine _check_allowed_hosts: called CC=9 SCAR=41.5
3652 145 my ($value) = @_;
3653 145 ▶ return unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 145 0 145
3654 0 ▶ croak "allowed_hosts: give a list of host names, such as ['bi.example.com']"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value eq "ARRAY" 0 0 0
3655 unless ref($value) eq 'ARRAY';
3656 0 for my $name (@{$value}) {
3657 0 ▶ croak sprintf("allowed_hosts: '%s' is not a host name such as 'bi.example.com', '*.example.com' or '*'",
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and not ref $name and $name =~ /\A(?:\*|(?:\*\.)?[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)*)\z/u 0 0 0
Condition0%0/11
defined $name and not ref $name and $name =~ /\A(?:\*|(?:\*\.)?[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)*)\z/u
!ll&&!rl&&r
000
defined $name and not ref $name
!ll&&!rl&&r
000
(ref $name || $name) // "undef"
l!l
00
ref $name or $name
l!l&&r!l&&!r
000
MC/DC0%0/3
defined $name and not ref $name and $name =~ /\A(?:\*|(?:\*\.)?[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)*)\z/u
defined $name not ref $name $name =~ /\A(?:\*|(?:\*\.)?[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)*)\z/u
MC/DC0%0/2
(ref $name || $name) // "undef"
ref $name $name
Truth table0%0/4
A and not(B) and C
A= defined $nameB= not ref $nameC= $name =~ /\A(?:\*|(?:\*\.)?[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)*)\z/u
ABCresult
0XX0
10X0
1100
1111
Truth table0%0/3
A or B
A= ref $nameB= $name
ABresult
1X1
011
000
3658 ref($name) || $name // 'undef')
3659 unless defined $name && !ref $name
3660 && $name =~ /\A(?:\*|(?:\*\.)?[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)*)\z/;
3661 }
3662 0 return;
3663 }
3664  
3665 # _listen_locations( $value ) -> @locations
3666 #
3667 # Purpose: Where a server started without -l or MOJO_LISTEN listens.
3668 # Entry: Config listen: undef, a location such as 'http://*:3000', several
3669 # separated by commas, or an arrayref of them.
3670 # Exit: The locations, $DEFAULT_LISTEN when none is given; croaks on
3671 # anything that is not a location, since a server that listens
3672 # somewhere other than intended is a security setting gone wrong.
3673 145 ▶sub _listen_locations {
Subroutine _listen_locations: called CC=11 SCAR=32.0
3674 145 my ($value) = @_;
3675 145 ▶ return ($DEFAULT_LISTEN) unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 143 2 145
3676  
3677 2 ▶ my @locations = ref($value) eq 'ARRAY' ? @{$value} : ref($value) ? ($value) : split(/,/, $value);
Branch: 2 branches
BranchTrueFalseTotal
ref $value eq 'ARRAY' ? : 2 0 2
ref $value ? : 0 0 0
3678 2 ▶ croak "listen: give one or more locations, such as 'http://127.0.0.1:3000' or 'http://*:3000'"
Branch: 1 branch
BranchTrueFalseTotal
unless @locations 0 2 2
3679 unless @locations;
3680 2 for my $location (@locations) {
3681 2 ▶ croak sprintf("listen: '%s' is not a location such as 'http://127.0.0.1:3000' or 'http://*:3000'",
Branch: 1 branch
BranchTrueFalseTotal
unless defined $location and not ref $location and $location =~ m[\Ahttps?://[^\s,]+\z]u 0 2 2
Condition18%2/11
defined $location and not ref $location and $location =~ m[\Ahttps?://[^\s,]+\z]u
!ll&&!rl&&r
002
defined $location and not ref $location
!ll&&!rl&&r
002
(ref $location || $location) // "undef"
l!l
00
ref $location or $location
l!l&&r!l&&!r
000
MC/DC0%0/3
defined $location and not ref $location and $location =~ m[\Ahttps?://[^\s,]+\z]u
defined $location not ref $location $location =~ m[\Ahttps?://[^\s,]+\z]u
MC/DC0%0/2
(ref $location || $location) // "undef"
ref $location $location
Truth table25%1/4
A and not(B) and C
A= defined $locationB= not ref $locationC= $location =~ m[\Ahttps?://[^\s,]+\z]u
ABCresult
0XX0
10X0
1100
1111
Truth table0%0/3
A or B
A= ref $locationB= $location
ABresult
1X1
011
000
3682 ref($location) || $location // 'undef')
3683 unless defined $location && !ref $location && $location =~ m{\Ahttps?://[^\s,]+\z};
3684 }
3685 2 return @locations;
3686 }
3687  
3688 # _default_hypnotoad_listen( $config ) -> void
3689 #
3690 # Purpose: Make hypnotoad listen on this machine only unless told otherwise.
3691 # Entry: The application's config hashref.
3692 # Exit: hypnotoad => { listen } is $DEFAULT_HYPNOTOAD_LISTEN when it was
3693 # unset; a hypnotoad entry that is not a hash is left for hypnotoad.
3694 #
3695 # Hypnotoad reads hypnotoad => { listen } after loading the application, and
3696 # ignores MOJO_LISTEN; without one it would listen on every interface.
3697 145 ▶sub _default_hypnotoad_listen {
Subroutine _default_hypnotoad_listen: called CC=4 SCAR=14.6
3698 145 my ($config) = @_;
3699 145 ▶ my $hypnotoad = $config->{hypnotoad} //= {};
Condition50%1/2
$config->{"hypnotoad"} //= {}
l!l
0145
MC/DC0%0/1
$config->{"hypnotoad"} //= {}
$config->{"hypnotoad"}
Truth table50%1/2
A
A= $config->{"hypnotoad"}
Aresult
11
00
3700 145 ▶ return unless ref($hypnotoad) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $hypnotoad eq "HASH" 0 145 145
3701 145 ▶ $hypnotoad->{listen} //= [$DEFAULT_HYPNOTOAD_LISTEN];
Condition50%1/2
$hypnotoad->{"listen"} //= [$DEFAULT_HYPNOTOAD_LISTEN]
l!l
0145
MC/DC0%0/1
$hypnotoad->{"listen"} //= [$DEFAULT_HYPNOTOAD_LISTEN]
$hypnotoad->{"listen"}
Truth table50%1/2
A
A= $hypnotoad->{"listen"}
Aresult
11
00
3702 145 return;
3703 }
3704  
3705 # _new_nonce() -> $nonce
3706 #
3707 # Purpose: A fresh Content-Security-Policy nonce.
3708 # Exit: 22 base64url characters, 132 random bits.
3709 #
3710 # generate_secret is base64url of 128 bytes from Crypt::URandom (a weaker
3711 # generator only when that is missing); the page writes the nonce on every
3712 # <script>, so a prefix keeps it short while still unguessable.
3713 3296 ▶sub _new_nonce {
Subroutine _new_nonce: called CC=1 SCAR=0.0
3714 3296 return substr(Mojo::Util::generate_secret(), 0, 22);
3715 }
3716  
3717 # _content_security_policy( \%config, $nonce, \@framers ) -> $policy | undef
3718 #
3719 # Purpose: The Content-Security-Policy header every HTML reply carries.
3720 # Entry: The application's config, the request's nonce (see csp_nonce), and
3721 # the other origins that may frame this reply (only /embed/ has any).
3722 # content_security_policy, when set to a string, is the whole policy,
3723 # sent as written but for {nonce}, which becomes the nonce; set to ''
3724 # or 0 it turns the header off. Otherwise the policy is built from
3725 # d3_url, the five leaflet_*_url keys, tile_url and tile_sources.
3726 # Exit: The header's value, or undef for none.
3727 #
3728 # script-src has no 'unsafe-inline': an inline script runs only if it carries
3729 # the nonce, so one that came in with a cell's text does not. style-src keeps
3730 # it, for the style attributes the templates write and the styles Leaflet and
3731 # D3 set, which is a much smaller risk. The hosts in script-src are what let a
3732 # <script src> run without a nonce of its own, as the canvas page's card
3733 # scripts load Leaflet.
3734 #
3735 # Leaflet's marker images are found beside its stylesheet, so the stylesheet's
3736 # host is allowed images too. unpkg.com stays in script-src even when the
3737 # Leaflet keys point elsewhere: HTML::OSM loads leaflet.heat from there, and
3738 # no key moves it. The pins themselves are data: URIs (_marker_icon in the controller), and a
3739 # chart export draws its copy through a data: or blob: image.
3740 1396 ▶sub _content_security_policy {
Subroutine _content_security_policy: called CC=12 SCAR=31.6
3741 1396 my ($config, $nonce, $framers) = @_;
3742 1396 ▶ $config //= {};
Condition50%1/2
$config //= {}
l!l
13960
MC/DC0%0/1
$config //= {}
$config
Truth table50%1/2
A
A= $config
Aresult
11
00
3743 1396 ▶ $nonce = undef unless defined $nonce && $nonce =~ $NONCE_RE;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $nonce and $nonce =~ /$NONCE_RE/u 0 1396 1396
Condition33%1/3
defined $nonce and $nonce =~ /$NONCE_RE/u
!ll&&!rl&&r
001396
MC/DC0%0/2
defined $nonce and $nonce =~ /$NONCE_RE/u
defined $nonce $nonce =~ /$NONCE_RE/u
Truth table33%1/3
A and B
A= defined $nonceB= $nonce =~ /$NONCE_RE/u
ABresult
0X0
100
111
3744  
3745 1396 my $set = $config->{content_security_policy};
3746 1396 ▶ if (defined $set && !ref $set) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $set and not ref $set) 0 1396 1396
Condition33%1/3
defined $set and not ref $set
!ll&&!rl&&r
139600
MC/DC0%0/2
defined $set and not ref $set
defined $set not ref $set
Truth table33%1/3
A and not(B)
A= defined $setB= not ref $set
ABresult
0X0
100
111
3747 0 ▶ return undef unless length($set) && $set ne '0';
Branch: 1 branch
BranchTrueFalseTotal
unless length $set and $set ne 0 0 0 0
Condition0%0/3
length $set and $set ne 0
!ll&&!rl&&r
000
MC/DC0%0/2
length $set and $set ne 0
length $set $set ne 0
Truth table0%0/3
A and B
A= length $setB= $set ne 0
ABresult
0X0
100
111
3748 0 ▶ $set =~ s/\{nonce\}/$nonce \/\/ ''/ge;
Condition0%0/2
$nonce // ""
l!l
00
MC/DC0%0/1
$nonce // ""
$nonce
Truth table0%0/2
A
A= $nonce
Aresult
11
00
3749 0 return $set;
3750 }
3751  
3752 9772 ▶ my $from = sub {
Subroutine __ANON__: called CC=4 SCAR=14.0
3753 9772 my ($key, $default) = @_;
3754 9772 my $url = $config->{$key};
3755 9772 ▶ $url = $default unless defined $url && !ref $url && length $url;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $url and not ref $url and length $url 8521 1251 9772
Condition66%4/6
defined $url and not ref $url and length $url
!ll&&!rl&&r
852101251
defined $url and not ref $url
!ll&&!rl&&r
852101251
MC/DC33%1/3
defined $url and not ref $url and length $url
defined $url not ref $url length $url
Truth table50%2/4
A and not(B) and C
A= defined $urlB= not ref $urlC= length $url
ABCresult
0XX0
10X0
1100
1111
3756 9772 return _csp_source($url);
3757 1396 };
3758  
3759 my @script = ($from->('d3_url', $DEFAULT_D3_URL),
3760 1396 map { $from->($_, $DEFAULT_LEAFLET_URL) } qw(leaflet_js_url leaflet_cluster_js_url));
3761 1396 push @script, _csp_source($DEFAULT_LEAFLET_URL);
3762 1396 my @style = map { $from->($_, $DEFAULT_LEAFLET_URL) }
3763 qw(leaflet_css_url leaflet_cluster_css_url leaflet_cluster_default_css_url);
3764 1396 my $sources = $config->{tile_sources};
3765 my @tiles = ($from->('tile_url', $DEFAULT_TILE_URL),
3766 ref $sources eq 'HASH'
3767 0 ▶ ? map { _csp_source(ref $_ eq 'HASH' ? $_->{url} : undef) } @{$sources}{sort keys %{$sources}}
Branch: 2 branches
BranchTrueFalseTotal
ref $sources eq 'HASH' ? : 0 1396 1396
ref $_ eq 'HASH' ? : 0 0 0
3768 : ());
3769  
3770 4188 ▶ my $list = sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
3771 4188 my %seen;
3772 4188 ▶ return join ' ', grep { defined && !$seen{$_}++ } @_;
Condition66%2/3
defined $_ && !$seen{$_}++
!ll&&!rl&&r
0837616752
MC/DC50%1/2
defined $_ && !$seen{$_}++
defined $_ !$seen{$_}++
Truth table66%2/3
A && not(B)
A= defined $_B= !$seen{$_}++
ABresult
0X0
100
111
3773 1396 };
3774  
3775 1396 ▶ return join '; ',
Branch: 1 branch
BranchTrueFalseTotal
defined $nonce ? : 1396 0 1396
3776 "default-src 'self'",
3777 'script-src ' . $list->("'self'", (defined $nonce ? "'nonce-$nonce'" : ()), @script),
3778 'style-src ' . $list->("'self'", "'unsafe-inline'", @style),
3779 'img-src ' . $list->("'self'", 'data:', 'blob:', @tiles, @style),
3780 "font-src 'self' data:",
3781 "connect-src 'self'",
3782 "object-src 'none'",
3783 "base-uri 'self'",
3784 "form-action 'self'",
3785 _frame_ancestors_directive($framers);
3786 }
3787  
3788 # _frame_ancestors_directive( \@framers ) -> $directive
3789 #
3790 # Purpose: frame-ancestors for a reply: this site, and the origins given.
3791 1396 ▶sub _frame_ancestors_directive {
Subroutine _frame_ancestors_directive: called CC=2 SCAR=7.1
3792 1396 my ($framers) = @_;
3793 1396 ▶ return join ' ', 'frame-ancestors', "'self'", @{ $framers // [] };
Condition50%1/2
$framers // []
l!l
13960
MC/DC0%0/1
$framers // []
$framers
Truth table50%1/2
A
A= $framers
Aresult
11
00
3794 }
3795  
3796 # _embed_frame_ancestors( \%config ) -> @origins
3797 #
3798 # Purpose: The other sites that may frame /embed/, from embed_frame_ancestors.
3799 # Entry: The config. The key is a list of origins, or one as a string.
3800 # Exit: Each as a CSP source ("https://intranet.example.com"), lower case,
3801 # without a trailing slash and without repeats. An entry that is not
3802 # an origin is left out (startup refuses one; see
3803 # _check_embed_frame_ancestors), so a list changed after startup
3804 # cannot put anything else into the header.
3805 57 ▶sub _embed_frame_ancestors {
Subroutine _embed_frame_ancestors: called CC=6 SCAR=24.8
3806 57 my ($config) = @_;
3807 57 ▶ my $value = ($config // {})->{embed_frame_ancestors};
Condition50%1/2
$config // {}
l!l
570
MC/DC0%0/1
$config // {}
$config
Truth table50%1/2
A
A= $config
Aresult
11
00
3808 0 ▶ my @list = ref $value eq 'ARRAY' ? @{$value} : defined $value && !ref $value ? ($value) : ();
Branch: 2 branches
BranchTrueFalseTotal
ref $value eq 'ARRAY' ? : 0 57 57
defined $value && !ref($value) ? : 0 57 57
Condition33%1/3
defined $value and not ref $value
!ll&&!rl&&r
5700
MC/DC0%0/2
defined $value and not ref $value
defined $value not ref $value
Truth table33%1/3
A and not(B)
A= defined $valueB= not ref $value
ABresult
0X0
100
111
3809 57 my %seen;
3810 0 ▶ return grep { defined && !$seen{$_}++ } map { _frame_origin($_) } @list;
Condition0%0/3
defined $_ && !$seen{$_}++
!ll&&!rl&&r
000
MC/DC0%0/2
defined $_ && !$seen{$_}++
defined $_ !$seen{$_}++
Truth table0%0/3
A && not(B)
A= defined $_B= !$seen{$_}++
ABresult
0X0
100
111
3811 }
3812  
3813 # _check_embed_frame_ancestors( $value ) -> void
3814 #
3815 # Purpose: Refuse an embed_frame_ancestors that does not name origins.
3816 # Entry: The config value: undef, an origin, or a list of them.
3817 # Exit: Returns; croaks naming the first entry that is not an origin.
3818 145 ▶sub _check_embed_frame_ancestors {
Subroutine _check_embed_frame_ancestors: called CC=8 SCAR=38.8
3819 145 my ($value) = @_;
3820 145 ▶ return unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 145 0 145
3821 0 ▶ croak 'embed_frame_ancestors must be a list of origins, such as [ \'https://intranet.example.com\' ]'
Branch: 1 branch
BranchTrueFalseTotal
if ref $value and ref $value ne "ARRAY" 0 0 0
Condition0%0/3
ref $value and ref $value ne "ARRAY"
!ll&&!rl&&r
000
MC/DC0%0/2
ref $value and ref $value ne "ARRAY"
ref $value ref $value ne "ARRAY"
Truth table0%0/3
A and B
A= ref $valueB= ref $value ne "ARRAY"
ABresult
0X0
100
111
3822 if ref $value && ref $value ne 'ARRAY';
3823 0 ▶ for my $entry (ref $value ? @{$value} : $value) {
Branch: 1 branch
BranchTrueFalseTotal
ref $value ? : 0 0 0
3824 0 ▶ next if defined _frame_origin($entry);
Branch: 1 branch
BranchTrueFalseTotal
if defined _frame_origin($entry) 0 0 0
3825 0 ▶ croak sprintf("embed_frame_ancestors: '%s' is not an origin such as https://intranet.example.com"
Condition0%0/2
$entry // "undef"
l!l
00
MC/DC0%0/1
$entry // "undef"
$entry
Truth table0%0/2
A
A= $entry
Aresult
11
00
3826 . ' (a scheme, a host and an optional port, with no path)', $entry // 'undef');
3827 }
3828 0 return;
3829 }
3830  
3831 # _frame_origin( $entry ) -> $source | undef
3832 #
3833 # Purpose: One embed_frame_ancestors entry as a CSP source, if it is an origin.
3834 # Entry: A string.
3835 # Exit: "scheme://host[:port]", lower case, or undef.
3836 #
3837 # Only http and https origins: a scheme on its own (https:), *, 'none' or
3838 # 'self' would let far more than one site in, or say something else entirely,
3839 # and a path would be ignored by the browser. A wildcard is allowed as the
3840 # first label only (https://*.example.com), which is all CSP allows.
3841 0 ▶sub _frame_origin {
Subroutine _frame_origin: not called CC=8 SCAR=42.8
3842 0 my ($entry) = @_;
3843 0 ▶ return unless defined $entry && !ref $entry;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $entry and not ref $entry 0 0 0
Condition0%0/3
defined $entry and not ref $entry
!ll&&!rl&&r
000
MC/DC0%0/2
defined $entry and not ref $entry
defined $entry not ref $entry
Truth table0%0/3
A and not(B)
A= defined $entryB= not ref $entry
ABresult
0X0
100
111
3844 0 ▶ my ($scheme, $host, $port) = $entry =~ m{
Branch: 1 branch
BranchTrueFalseTotal
() = $entry =~ m[ \A\s*(https?):// ((?:\*\.)?[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)*) (?::(\d{1,5}))? /?\s*\z ]iux or return 0 0 0
3845 \A\s*(https?)://
3846 ((?:\*\.)?[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)*)
3847 (?::(\d{1,5}))?
3848 /?\s*\z
3849 }xi or return;
3850 0 ▶ return if defined $port && ($port == 0 || $port > 65_535);
Branch: 1 branch
BranchTrueFalseTotal
if defined $port and $port == 0 || $port > 65535 0 0 0
Condition0%0/6
defined $port and $port == 0 || $port > 65535
!ll&&!rl&&r
000
$port == 0 or $port > 65535
l!l&&r!l&&!r
000
MC/DC0%0/3
defined $port and $port == 0 || $port > 65535
defined $port $port == 0 $port > 65535
Truth table0%0/4
A and B or C
A= defined $portB= $port == 0C= $port > 65535
ABCresult
0XX0
1000
11X1
1011
3851 0 ▶ return lc("$scheme://$host") . (defined $port ? ":$port" : '');
Branch: 1 branch
BranchTrueFalseTotal
defined $port ? : 0 0 0
3852 }
3853  
3854 # _csp_source( $url ) -> $source | undef
3855 #
3856 # Purpose: The CSP source expression that allows $url.
3857 # Entry: A URL from the config: absolute (http, https or scheme-relative), or
3858 # a path, which is this site.
3859 # Exit: "https://host[:port]", "'self'", or undef when it names nothing a
3860 # policy can allow.
3861 #
3862 # Only the origin is kept: a source with a path would allow that one file, and
3863 # tile URLs carry {z}/{x}/{y}. A placeholder in the first label of the host
3864 # ({s}.tile.openstreetmap.org) becomes CSP's wildcard; one anywhere else cannot
3865 # be written as a host, so the whole scheme is allowed rather than the tiles
3866 # broken.
3867 11168 ▶sub _csp_source {
Subroutine _csp_source: called CC=22 SCAR=39.7
3868 11168 my ($url) = @_;
3869 11168 ▶ return unless defined $url && !ref $url && length $url;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $url and not ref $url and length $url 0 11168 11168
Condition33%2/6
defined $url and not ref $url and length $url
!ll&&!rl&&r
0011168
defined $url and not ref $url
!ll&&!rl&&r
0011168
MC/DC0%0/3
defined $url and not ref $url and length $url
defined $url not ref $url length $url
Truth table25%1/4
A and not(B) and C
A= defined $urlB= not ref $urlC= length $url
ABCresult
0XX0
10X0
1100
1111
3870  
3871 11168 ▶ if ($url !~ m{\A(?:[A-Za-z][A-Za-z0-9+.-]*:)?//}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($url =~ m[\A(?:[A-Za-z][A-Za-z0-9+.-]*:)?//]u) 0 11168 11168
3872 # A path on this site; any other scheme (data:, javascript:) is none.
3873 0 ▶ return $url =~ m{\A[A-Za-z][A-Za-z0-9+.-]*:} ? undef : "'self'";
Branch: 1 branch
BranchTrueFalseTotal
$url =~ /\A[A-Za-z][A-Za-z0-9+.-]*:/u ? : 0 0 0
3874 }
3875 11168 my ($scheme, $authority) = $url =~ m{\A(?:([A-Za-z][A-Za-z0-9+.-]*):)?//([^/?#]*)};
3876 11168 ▶ $scheme = lc($scheme // '');
Condition50%1/2
$scheme // ""
l!l
111680
MC/DC0%0/1
$scheme // ""
$scheme
Truth table50%1/2
A
A= $scheme
Aresult
11
00
3877 11168 ▶ return if length $scheme && $scheme !~ /\Ahttps?\z/;
Branch: 1 branch
BranchTrueFalseTotal
if length $scheme and not $scheme =~ /\Ahttps?\z/u 0 11168 11168
Condition33%1/3
length $scheme and not $scheme =~ /\Ahttps?\z/u
!ll&&!rl&&r
0111680
MC/DC0%0/2
length $scheme and not $scheme =~ /\Ahttps?\z/u
length $scheme not $scheme =~ /\Ahttps?\z/u
Truth table33%1/3
A and not(B)
A= length $schemeB= not $scheme =~ /\Ahttps?\z/u
ABresult
0X0
100
111
3878 11168 ▶ my $prefix = length $scheme ? "$scheme://" : '';
Branch: 1 branch
BranchTrueFalseTotal
length $scheme ? : 11168 0 11168
3879 11168 ▶ my $whole = length $scheme ? "$scheme:" : undef;
Branch: 1 branch
BranchTrueFalseTotal
length $scheme ? : 11168 0 11168
3880  
3881 11168 $authority =~ s/\A.*@//;
3882 11168 ▶ my ($host, $port) = $authority =~ /\A([^:]+)(?::(.*))?\z/
Branch: 1 branch
BranchTrueFalseTotal
() = $authority =~ /\A([^:]+)(?::(.*))?\z/u or return $whole 11168 0 11168
3883 or return $whole;
3884 11168 my @labels = split /\./, $host, -1;
3885 11168 ▶ $labels[0] = '*' if @labels > 1 && $labels[0] =~ /\{/;
Branch: 1 branch
BranchTrueFalseTotal
if @labels > 1 and $labels[0] =~ /\{/u 1396 9772 11168
Condition66%2/3
@labels > 1 and $labels[0] =~ /\{/u
!ll&&!rl&&r
097721396
MC/DC50%1/2
@labels > 1 and $labels[0] =~ /\{/u
@labels > 1 $labels[0] =~ /\{/u
Truth table66%2/3
A and B
A= @labels > 1B= $labels[0] =~ /\{/u
ABresult
0X0
100
111
3886 11168 for my $i (0 .. $#labels) {
3887 26524 ▶ next if $i == 0 && $labels[0] eq '*';
Branch: 1 branch
BranchTrueFalseTotal
if $i == 0 and $labels[0] eq "*" 1396 25128 26524
Condition100%3/3
$i == 0 and $labels[0] eq "*"
!ll&&!rl&&r
1535697721396
MC/DC100%2/2
$i == 0 and $labels[0] eq "*"
$i == 0 $labels[0] eq "*"
Truth table100%3/3
A and B
A= $i == 0B= $labels[0] eq "*"
ABresult
0X0
100
111
3888 25128 ▶ return $whole unless $labels[$i] =~ /\A[A-Za-z0-9-]+\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $labels[$i] =~ /\A[A-Za-z0-9-]+\z/u 0 25128 25128
3889 }
3890 11168 ▶ if (defined $port) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $port) 0 11168 11168
3891 0 ▶ return $whole unless $port =~ /\A(?:\d{1,5}|\{[^}]*\})\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $port =~ /\A(?:\d{1,5}|\{[^}]*\})\z/u 0 0 0
3892 0 ▶ $port = $port =~ /\{/ ? '*' : $port;
Branch: 1 branch
BranchTrueFalseTotal
$port =~ /\{/u ? : 0 0 0
3893 }
3894 11168 ▶ return $prefix . lc(join '.', @labels) . (defined $port ? ":$port" : '');
Branch: 1 branch
BranchTrueFalseTotal
defined $port ? : 0 11168 11168
3895 }
3896  
3897 =head1 SEE ALSO
3898  
3899 =over 4
3900  
3901 =item * L<Test Dashboard|https://nigelhorne.github.io/Database-BI/coverage/>
3902  
3903 =back
3904  
3905 =head1 REPOSITORY
3906  
3907 L<https://github.com/nigelhorne/Database-BI>
3908  
3909 =head1 SUPPORT
3910  
3911 This module is provided as-is without any warranty.
3912  
3913 =head1 AUTHOR
3914  
3915 Nigel Horne C<< <njh@nigelhorne.com> >>
3916  
3917 =head1 LICENCE AND COPYRIGHT
3918  
3919 Copyright 2026 Nigel Horne.
3920  
3921 Usage is subject to the GPL2 licence terms.
3922 If you use it,
3923 please let me know.
3924  
3925 =cut
3926  
3927 12 1;
« blib/lib/Database/BI/Model/DataSource.pm ↑ Summary blib/lib/Database/BI/CacheDir.pm »