Compare commits

..
36 Commits
Author SHA1 Message Date
swaitsandClaude Opus 5.5 3a2bcefd38 Redesign the page as an instrument panel: hairline panels, amber hero band, counter strip, two-column grid
Dark charcoal with one amber accent, a derived light theme, the problems list (click to open) inside the hero, raw counters collapsed by default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 09:14:58 -07:00
swaitsandClaude Fable 5.2 06abc4de80 Speed panel: say the time is for one crate's compile, not a whole build
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 18:47:40 -07:00
swaitsandClaude Fable 5.2 e3b56cb213 Never start sccache unless asked; compact reasons panel
A server started from the dashboard has the dashboard's environment, not
the builds'. It came up with the 10 GB default beside a 250 GB cache and
sccache trimmed the cache. Starting is now opt-in
(SCCACHE_DASH_START_SCCACHE=1) and the README says why.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 18:32:20 -07:00
swaitsandClaude Fable 5.2 c2b07734c6 Merge compact reasons panel: one line per reason, click to open
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 18:26:16 -07:00
swaitsandClaude Sonnet 5.5 30643390a7 Reasons: one line each, click to open; stack the small panels beside tall reasons
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-28 18:23:28 -07:00
swaitsandClaude Fable 5.2 0759cbaa25 just shots: screenshots of the whole page at the 3, 2 and 1 column widths
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 18:08:13 -07:00
swaitsandClaude Fable 5.2 29e5103648 Merge scroll fix: a row scrolled above the window ends at its own bottom
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 18:02:52 -07:00
swaitsandClaude Sonnet 5.5 9630b96c1b Fix the page growing while scrolled: close panel rows at their own bottom
end_row folded the panels' bottoms from 0.0, so a row whose bottom was above
the top of the window (negative screen y while scrolled) was closed at y=0.
Everything after it was placed from there, the scroll content grew by the
scroll offset, and the scroll bar kept shrinking at the bottom. The lowest
bottom is now a plain function in fmt with a native test.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-28 18:02:00 -07:00
swaitsandClaude Fable 5.2 f08f4655e4 Shorten the low-hit-rate warning; the fix lives in the reasons panel
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 17:51:30 -07:00
swaitsandClaude Fable 5.2 a8c69567b4 Merge hit-rate advice: what each not-cacheable reason means and what to change
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 17:46:17 -07:00
swaitsandClaude Sonnet 5.5 0f4df265a5 Say what each not-cacheable reason means and what to change; explain a low Rust hit rate
Each reason now carries a plain name, meaning, action and a fixable flag (checked
against sccache 0.18.0), shown with its count in the reasons panel, fixable first.
The low-hit-rate problem names the fixable loss and the Rust hash-key inputs.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-28 17:45:38 -07:00
swaitsandClaude Fable 5.2 4a1dfadfb0 Add a favicon: a gauge in the page's colours
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 17:45:20 -07:00
swaitsandClaude Fable 5.2 3ede855fbb Fix the All languages box: ticking it shows every language again
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 17:27:13 -07:00
swaitsandClaude Fable 5.2 3e76fad51f README: say plainly what it is; it does start sccache
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 15:21:19 -07:00
swaitsandClaude Fable 5.2 0cb8206d43 README: screenshots of the dashboard
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 15:17:07 -07:00
swaits 7e864ad749 Fix round: readable selected segments, panels that fit, smaller fonts
- A selected segment is the accent with white text, in both themes.
- At three columns the row of "Where compiles went", "By language" and
  "Problems" is one modest height; the reasons table is its own panel,
  "Why compiles were not cacheable", stacked under "Speed" beside
  "Over time" and as tall together as it is. In the two-column and
  one-column layouts it follows "Where compiles went".
- Raw counters use every column; each value follows its key by 16 px,
  and a key ends in "..." only where the two do not fit.
- No blank row between a table's head and its first row.
- The five embedded fonts are subset to Latin text and the symbols the
  page uses with pyftsubset (hinting dropped); the wasm goes from
  5.49 MB to 4.11 MB.
2026-11-28 13:40:27 -07:00
swaits 03ffdf887a Merge page redesign: panel grid, instrument-panel theme, Inter and JetBrains Mono 2026-11-28 13:32:53 -07:00
swaits a7d836d45a Redesign the page: a grid of panels with an instrument-panel look
Every colour, size, spacing and font now lives in crates/ui/src/theme.rs.
At 1100 px and wider the page is three columns of panels, at 700 px two,
below that one: a toolbar with the range as one segmented control, a
headline panel, six stat cards in one row, three panels side by side,
then Over time beside Speed, then Raw counters as key/value lines.

The type is Inter and JetBrains Mono (SIL Open Font License, licence
files beside the fonts). Tables size their columns to what they hold,
charts keep their time labels inside the plot and tint unrecorded time,
and the hit-rate bars leave the language table where there is no room.

Behaviour is unchanged: ranges, refresh, theme switch, Copy summary,
Export JSON, Zero stats with its question, the language filter and the
remembered settings work as before.
2026-11-28 13:31:51 -07:00
swaits 72fcf8f976 Merge page polish: full-range charts, even cards, aligned tables 2026-11-28 12:49:48 -07:00
swaits 73c8138072 Page polish from the live service
- Both charts always span exactly the selected range, edge to edge. Time
  nothing was recorded in is shaded and labelled once, and each chart's
  key is drawn under the chart instead of over the data.
- The time saved says "not enough data yet" or "nothing saved yet"
  when nothing can be counted, and a saving under a second reads
  "under 1 s", never in milliseconds.
- The six cards are exact boxes of one size, so their tops line up.
- Tables have headed columns at fixed shares of the width, text left and
  numbers right; each row is one rectangle with a place for every cell.
- The cache usage bar has an outlined track.
- When the server can't be reached, the notice is drawn over the page, so
  what is on screen keeps its place and height.
2026-11-28 12:49:21 -07:00
swaits d7351a5d5e Merge fix: history survives a restart; first histogram is immediate 2026-11-28 12:34:57 -07:00
swaitsandClaude Sonnet 5.5 c56aaefa72 History: resume the saved tracker at start; first build observations draw at once
The polling task never loaded the tracker the last run saved, so every
restart began again from a baseline and dropped what had not yet reached a
row. The empty bootstrap drawn at the first poll also started the one-minute
wait for the first real observations.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-28 12:34:30 -07:00
swaitsandClaude Fable 5.2 bcc178330b Lock file with the page crate; ignore local agent notes
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 12:24:58 -07:00
swaits f277737e12 Merge page: egui dashboard for the browser 2026-11-28 12:14:19 -07:00
swaits 46b8dcf274 Hit-rate chart: a mark every quarter, so the axis reads 0% to 100% 2026-11-28 12:13:45 -07:00
swaits dc876b5a5c Dashboard page: fit the page, five shares, build-time histograms
- Built is the miss count, as sccache counts timeouts, cache errors and
  forced recaches inside it. The bar under the headline has five shares
  that add up to every compiler call and always to 100%; what happened
  inside the built share is one line under the bar.
- The time saved shows its 90% range in small print under the figure.
- Speed gains "How long builds take, by language": one fixed-height
  histogram per language on a shared log scale of build time, with the
  mean, median and p90 marked.
- The api crate's Range helpers replace the page's own copies.
- Drawing is built only for the browser, so the tests (and the rest of
  the crate) build anywhere without eframe's native backends.
- Tables are drawn row by row; egui's Grid lost its rows when a cell
  held more than a plain widget. Fold-away bodies are held to the width
  of the page, and the charts fit their data every frame.
- mise.toml takes trunk 0.22.2 as a release binary; building it from
  source took over half an hour.
2026-11-28 12:10:01 -07:00
swaits e282b40a18 Merge server round 3: steady cost by count, bootstrap once a minute 2026-11-28 12:09:21 -07:00
swaits 693dca6cdf Prove the steady cost by count, redraw the bootstrap once a minute, tidy
A test fills a history with a row a minute for thirty days (43,199 rows,
4,319 build observations) in one transaction, runs two polls and asserts
the second hands out fewer than 3,000 rows; it measures 1,567 (the first
reads every observation once). History::fill saves a run of readings as
the polls would have.

While a build keeps adding observations, they are stored at once but the
bootstrap and the histogram are redrawn at most once a minute.

A saving is never negative or a negative zero.

History::rows and History::build_observations are gone, with the tests
that only used them. History::first_row stays: without it the chart of
the reset range, on a database that never saw a zeroing, would start at
the live reading instead of at the first row.

The timing line is logged for the first two polls.
2026-11-28 12:07:56 -07:00
swaits 7ab1543315 Merge server round 2: SQL bucketing, histogram and interval, starts sccache 2026-11-28 11:57:33 -07:00
swaits 16ba94517b Bucket in SQLite, draw the build-time bootstrap once, start sccache's server
Speed: the chart's counts come from GROUP BY over the bucket number, so
about 120 rows per table per range reach Rust instead of every saved row;
a range total is one indexed SUM. History counts the rows it hands out.

Build times: crates/stats gains Resampled, which draws the bootstrap once
for a set of languages and applies it to any number of hit sets; the
server keeps it and redraws only when an observation was added. The
views fill build_times, time saved and the 90% interval from the stats
crate, and the time-saved arithmetic of the server is gone.

Starting sccache: when nothing listens where the client looks
(SCCACHE_SERVER_UDS, or 127.0.0.1 at SCCACHE_SERVER_PORT), sccache
--start-server is run once and the counters read again; a failure is
reported as NotRunning and not retried for a minute.

Uses the api's Range::ALL, parse and label.
2026-11-28 11:57:10 -07:00
swaits 90a6302149 Merge server: polling, SQLite history, views, HTTP, service install 2026-11-28 11:46:54 -07:00
swaits 7f58931b7b Keep the history in SQLite, one view per range made after each poll
Each row of the readings table is the difference since the row before it,
at most one a minute and only when something changed, so a range total is
one indexed query. Per-language counts, not-cacheable reasons and build
observations have their own tables; what the last poll and the last row
saw is remembered in the state table, so differences survive a restart.

The five views are computed once per poll and kept; /api/view answers
from them and never touches the database, which only the polling task
holds. /api/zero wakes that task instead of reading the counters itself.

Build observations: after a poll in which every build that finished was
of one language, one row with the difference in compilations and compile
time, for the build-time histogram. Time saved uses their per-language
average. Views fill the api's build_times and interval_90 as empty/None.
2026-11-28 11:44:50 -07:00
swaits c589b7c868 Merge branch 'main' into t3/dashboard-ui-page 2026-11-28 11:41:03 -07:00
swaits b80749ebb5 Dashboard page for sccache-dash (crates/ui)
An eframe/egui page compiled to WebAssembly with trunk. It draws the one
View the server sends: controls on top, three big figures, six cards, and
the collapsible sections Problems, Where compiles went, Over time, Speed,
Extras and Raw counters. The range, refresh interval and theme are
remembered between visits with eframe storage.

mise.toml names trunk 0.22.2 as the build tool.
2026-11-28 11:30:54 -07:00
swaits a83ae5e0d9 Merge branch 'main' into t3/sccache-dash-server 2026-11-28 11:27:18 -07:00
swaits 3cbc02e631 Server half of sccache-dash
Polls sccache's counters every 10 s, keeps a JSON-lines history, and serves
the page and its API on 127.0.0.1: one difference-with-reset mechanism behind
every range, per-language time saved, problems, a copyable summary, and
extra tables for multi-level and distributed caches.

The page is embedded from crates/ui/dist when it exists, with a placeholder
until then. POST /api/zero refuses foreign Host and Origin headers.
Tests run against a stand-in sccache script; sample fixtures for the
multi-level and distributed shapes are made up.
2026-11-28 11:23:39 -07:00
52 changed files with 12292 additions and 76 deletions

No files matched your search

+1
View File
@@ -1,3 +1,4 @@
target/ target/
dist/ dist/
.sisi/ .sisi/
AGENTS.md
Generated
+2635
View File
File diff suppressed because it is too large. Load diff
+176
View File
@@ -0,0 +1,176 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 sccache-dash contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+91
View File
@@ -0,0 +1,91 @@
# sccache-dash
Is [sccache](https://github.com/mozilla/sccache) actually saving you time? sccache-dash answers
that with a dashboard in your browser.
It is one small Linux program. It runs in the background, reads sccache's counters every 10
seconds, keeps 30 days of history, and shows the result at <http://127.0.0.1:8226>. Only the
machine it runs on can open that page.
The page shows, for the last hour, 24 hours, 7 days or 30 days:
- how many compiles came from the cache, overall and per language
- roughly how much time that saved, with a 90% range
- what looks wrong: cache errors, timeouts, a language that rarely hits, a cache close to full
- where the other compiles went, and why some could not be cached
- how long a cache hit takes compared with a build, and how build times are spread
## What it looks like
![The dashboard on a wide screen, dark](docs/screenshots/desktop-dark.png)
<table>
<tr>
<td width="72%"><img src="docs/screenshots/desktop-light.png" alt="The dashboard on a wide screen, light"></td>
<td><img src="docs/screenshots/phone-dark.png" alt="The dashboard at phone width, dark"></td>
</tr>
</table>
## Install
```
just build # builds the page (trunk) and then the server
sccache-dash # serves http://127.0.0.1:8226 and opens it
sccache-dash install # the same, as a systemd user service that starts at login
sccache-dash uninstall
```
`sccache-dash [--port N] [--no-open]` serves. `install` writes
`~/.config/systemd/user/sccache-dash.service` with the absolute path of the binary and the `PATH`
of the shell that ran it, so that `sccache` is found; the service never opens a browser.
`SCCACHE_DASH_SCCACHE` names the sccache command when it is not simply `sccache` on `PATH`.
Until the page has been built (`crates/ui/dist`), the server serves a placeholder saying so; its
API answers either way.
## Routes
| Route | What it does |
| --- | --- |
| `GET /api/view?range=1h\|24h\|7d\|30d\|reset` | one `View`: totals, the period before, timing, time saved, languages, buckets, problems, a summary |
| `GET /api/export` | sccache's current stats exactly as `sccache --show-stats --stats-format json` prints them, as a download |
| `POST /api/zero` | runs `sccache --zero-stats`; the saved history is kept |
| `GET /` | the page |
`/api/zero` is refused unless the request's `Host` is localhost and, when it has an `Origin`,
that origin is this server, so a web page elsewhere cannot zero the stats.
## Where history lives
`$XDG_DATA_HOME/sccache-dash/history.db` (`~/.local/share/...` by default): one SQLite file. Its
`readings` table holds one row a minute at most, and only when sccache's counters changed; each
row is the difference since the row before it, so a range total is one indexed query. Per-language
counts and not-cacheable reasons sit in their own tables, and `build_obs` holds what the polls saw
of how long a build of each language takes. A stretch without rows is a gap. Rows older than 30
days are deleted at startup and once a day. Deleting the file loses the history and nothing else.
The five views (one per range) are made after every poll and kept in memory, so a request never
waits for the database.
A counter that goes down means sccache reset its counters (`--zero-stats`, or its server
restarted): the range counts start again from zero there and the chart marks the spot. The first
reading ever is a baseline and counts for nothing.
## Notes on sccache
sccache-dash never starts or stops sccache's server by itself. When none is running it shows
"not running"; sccache starts its own server on your next build, with your build's settings.
To have sccache-dash start the server when none is running, set `SCCACHE_DASH_START_SCCACHE=1`
in its environment. Be careful with this: a server started that way gets sccache-dash's
environment, not your build's. If your cache size or folder is set only in your build's
environment, the server comes up with sccache's defaults, and sccache deletes cache entries
until the cache fits the 10 GB default.
While sccache-dash runs, sccache's server stays up: being asked for its stats every 10 seconds
keeps it from shutting itself down after 10 idle minutes.
## Licence
MIT or Apache-2.0, at your choice (`LICENSE-MIT`, `LICENSE-APACHE`).
+19 -2
View File
@@ -78,8 +78,9 @@ pub struct View {
pub build_times: Vec<BuildTimes>, pub build_times: Vec<BuildTimes>,
/// Sorted by hits + misses, largest first. /// Sorted by hits + misses, largest first.
pub languages: Vec<Language>, pub languages: Vec<Language>,
/// Why compiles were not cacheable, largest first, e.g. ("crate-type", 562). /// Why compiles were not cacheable: reasons you can fix first, then expected ones,
pub not_cached: Vec<(String, u64)>, /// each largest first.
pub not_cached: Vec<NotCached>,
/// Oldest first, evenly spaced, at most 120. /// Oldest first, evenly spaced, at most 120.
pub buckets: Vec<Bucket>, pub buckets: Vec<Bucket>,
/// Most serious first. Empty means no problems. /// Most serious first. Empty means no problems.
@@ -92,6 +93,22 @@ pub struct View {
pub summary_markdown: String, pub summary_markdown: String,
} }
/// One reason sccache gave for not caching a compile, with what to do about it.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct NotCached {
/// Exactly as sccache words it, e.g. "crate-type".
pub reason: String,
pub count: u64,
/// A plain name, e.g. "Incremental compilation is on".
pub name: String,
/// One sentence on what the reason means.
pub meaning: String,
/// What to change, or why nothing needs changing.
pub action: String,
/// True when a setting you control would make these compiles cacheable.
pub fixable: bool,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum Status { pub enum Status {
/// Compiles arrived in the last five minutes. /// Compiles arrived in the last five minutes.
+20
View File
@@ -0,0 +1,20 @@
[package]
name = "sccache-dash"
description = "Records sccache's counters and serves a dashboard for them on localhost"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
sccache-dash-api = { path = "../api" }
sccache-dash-stats = { path = "../stats" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tiny_http = "0.12"
rusqlite = { version = "0.37", features = ["bundled"] }
wait-timeout = "0.2"
dirs = "6"
include_dir = "0.7"
[dev-dependencies]
tempfile = "3"
+37
View File
@@ -0,0 +1,37 @@
//! Puts the page into the binary. The page is what `trunk build --release` writes to
//! `crates/ui/dist`; until it has been built, a placeholder page stands in for it.
use std::path::Path;
const PLACEHOLDER: &str = "<!doctype html>
<meta charset=\"utf-8\">
<title>sccache-dash</title>
<body style=\"font: 16px sans-serif; margin: 3em auto; max-width: 34em;\">
<h1>The sccache dashboard page is not built</h1>
<p>The server is running and its <a href=\"/api/view?range=24h\">API</a> answers, but the page
that draws it is missing. Run <code>just build</code> in the repository (it runs
<code>trunk build --release</code> in <code>crates/ui</code>) and start sccache-dash again.
";
fn main() {
let crates = Path::new(&std::env::var("CARGO_MANIFEST_DIR").unwrap())
.parent()
.expect("crates/server has a parent")
.to_path_buf();
let dist = crates.join("ui").join("dist");
// Checked on every build, so the page is picked up as soon as `trunk build` has made it.
println!(
"cargo:rerun-if-changed={}",
dist.join("index.html").display()
);
let site = if dist.join("index.html").is_file() {
dist
} else {
let out = Path::new(&std::env::var("OUT_DIR").unwrap()).join("site");
std::fs::create_dir_all(&out).unwrap();
std::fs::write(out.join("index.html"), PLACEHOLDER).unwrap();
out
};
println!("cargo:rustc-env=DASH_SITE={}", site.display());
}
+289
View File
@@ -0,0 +1,289 @@
//! What each "not cacheable" reason means and what to do about it.
//!
//! Every statement here was checked against the sccache 0.18.0 source (the file and line
//! of the code that produces each reason is beside its entry) and, where a command is
//! named, by running it. A reason that is not listed is shown as sccache words it, with
//! "sccache does not say more": we do not guess.
use sccache_dash_api::NotCached;
/// What we know about one reason.
pub struct Advice {
pub name: String,
pub meaning: String,
pub action: String,
pub fixable: bool,
}
fn entry(name: &str, meaning: &str, action: &str, fixable: bool) -> Advice {
Advice {
name: name.to_owned(),
meaning: meaning.to_owned(),
action: action.to_owned(),
fixable,
}
}
/// The advice for `reason`, exactly as sccache's "Non-cacheable reasons" prints it.
pub fn advise(reason: &str) -> Advice {
let expected = |name: &str, meaning: &str, why: &str| {
entry(name, meaning, &format!("Nothing to do, this is expected. {why}"), false)
};
match reason {
// rust.rs:1208 `("incremental", _) => cannot_cache!("incremental")`
"incremental" => entry(
"Incremental compilation is on",
"rustc was told to compile incrementally (-C incremental=...), and sccache 0.18.0 never caches those compiles; its own note says rustc in incremental mode is likely to be faster than fetching from the cache.",
"To cache them, turn incremental off: set CARGO_INCREMENTAL=0 in the environment, or incremental = false under [profile.dev] in Cargo.toml, or incremental = false under [build] in ~/.cargo/config.toml. The trade-off: incremental makes rebuilds of your own crates faster, while the cache helps clean builds and dependency builds.",
true,
),
// rust.rs:1187 and rust.rs:1298: only lib, rlib and staticlib are cached.
"crate-type" => expected(
"Programs and libraries that get linked",
"sccache only caches the crate types lib, rlib and staticlib. Anything else (bin, which includes build scripts and test programs, plus proc-macro, dylib and cdylib), or a call with no crate type, is not cached because rustc runs the system linker and sccache cannot know all of the linker's inputs.",
"Cargo builds each of these in every project, and they cannot be cached.",
),
// rust.rs:1026 `flag!("-", TooHardFlag)`, gcc.rs:190
"-" => expected(
"Source read from standard input",
"The compiler was given a bare - (read the source from standard input), which sccache does not cache.",
"Cargo makes one such call per run to ask rustc about the target it builds for.",
),
// rust.rs:1062 `take_arg!("-o", ..., TooHardPath)`; rust.rs doc: "We don't support `-o file`"
"-o" => entry(
"rustc called with -o",
"rustc was given -o <file>, which sccache 0.18.0 does not cache; it needs --out-dir (cargo passes that for normal builds).",
"Nothing to change in sccache. The tool that called rustc directly would have to use --out-dir instead.",
false,
),
// rust.rs:1280 req!(input) (macro at 1269-1276). Seen in the log as CannotCache(missing input): ["-vV"].
"missing input" => expected(
"rustc call with no source file",
"A rustc call had no source file on its command line, so there was nothing to cache.",
"Cargo starts every run with `rustc -vV` to read the compiler's version, and that is counted here.",
),
// rust.rs:1282 req!(output_dir)
"missing output_dir" => expected(
"rustc call without --out-dir",
"A rustc call had no --out-dir, which sccache requires.",
"It comes from the tool that called rustc; cargo's normal builds pass --out-dir.",
),
// rust.rs:1283 req!(emit)
"missing emit" => expected(
"rustc call without --emit",
"A rustc call had no --emit, which sccache requires.",
"It comes from the tool that called rustc; cargo's normal builds pass --emit.",
),
// rust.rs:1284 req!(crate_name)
"missing crate_name" => expected(
"rustc call without --crate-name",
"A rustc call had no --crate-name, which sccache requires.",
"It comes from the tool that called rustc; cargo's normal builds pass --crate-name.",
),
// rust.rs:1173
"more than one --emit" => expected(
"rustc call with --emit given twice",
"rustc was given --emit more than once, which sccache does not handle.",
"It comes from the tool that called rustc.",
),
// rust.rs:1303 ALLOWED_EMIT = link, metadata, dep-info
"unsupported --emit" => expected(
"rustc asked for extra output",
"rustc was asked to emit something other than link, metadata and dep-info (for example asm or llvm-ir), which sccache does not cache.",
"Those outputs were asked for on purpose.",
),
// rust.rs:1198
"extra-filename" => expected(
"-C extra-filename without a value",
"rustc was given -C extra-filename with no value, which sccache cannot use.",
"It comes from the tool that called rustc.",
),
// rust.rs:1232 ArgTarget::Unsure, rust.rs:955-980
"target unsure" => entry(
"Ambiguous --target",
"The --target value is a plain name, but a file with that name plus .json exists, so sccache cannot tell whether a built-in target or your target file is meant.",
"Pass the target file by its path ending in .json (--target path/to/target.json); sccache then hashes the file's contents.",
true,
),
// rust.rs:1048 `take_arg!("--sysroot", ..., TooHardPath)`
"--sysroot" => entry(
"rustc given --sysroot",
"rustc was given --sysroot, which sccache 0.18.0 does not cache.",
"If it comes from RUSTFLAGS or build.rustflags and you do not need a custom sysroot, remove it.",
true,
),
// rust.rs:1248, gcc.rs:666, msvc.rs:791
"multiple input files" => entry(
"Several source files in one compiler call",
"One compiler call named more than one source file, and sccache caches only one source file per call.",
"If your build passes several files to one compiler call, change it to compile one file per call.",
true,
),
// gcc.rs:362 and diab.rs:206
"@" => expected(
"Option value starting with @",
"An option's value began with @: an @file that sccache could not read or expand, or one attached straight to an option. sccache gives up on both.",
"It comes from how the build passes its flags.",
),
// gcc.rs:466
"-x" => entry(
"Unknown language after -x",
"The call said -x <language> with a language sccache does not know.",
"Use a language sccache knows (c, c++, objective-c, objective-c++, assembler, assembler-with-cpp, cu, cuda, hip, or a header kind) or drop -x.",
true,
),
// gcc.rs:472
"multiple different -arch, and SCCACHE_CACHE_MULTIARCH not set" => entry(
"Several -arch values in one call",
"The call had more than one different -arch, and sccache only caches that when SCCACHE_CACHE_MULTIARCH is set.",
"Set SCCACHE_CACHE_MULTIARCH=1 in the environment sccache's server starts with.",
true,
),
// gcc.rs:674, msvc.rs:802
"no input file" => expected(
"C/C++ call with no source file",
"The compiler call had no source file, so there was nothing to cache.",
"It comes from the tool that called the compiler.",
),
// gcc.rs:688, msvc.rs:799
"unknown source language" => entry(
"Source file type not recognised",
"sccache could not tell the language from the file's extension and the call had no -x.",
"Give the file a standard extension, or add -x c or -x c++ to the call.",
true,
),
// gcc.rs:414
"unknown module output format" => expected(
"Unknown clang module output option",
"A clang module-output option had a value sccache does not understand.",
"Only clang modules builds do this.",
),
// gcc.rs:593-604
"Can't handle complex arguments through clang"
| "Can't handle Raw arguments with -Xclang"
| "Can't handle UnknownFlag arguments with -Xclang" => expected(
"Complicated -Xclang options",
"The call passes options through -Xclang that sccache cannot follow.",
"Remove the -Xclang options if you do not need them.",
),
// msvc.rs:610, msvc.rs:911, msvc.rs:831
"output to nul" | "shared pdb" | "invalid input file" => expected(
"Visual C++ call sccache cannot cache",
"The Visual C++ call writes its output to nul, uses a program database file shared by every compile in the folder (-Zi or -ZI without -Fd), or has an input path with no file name; sccache caches none of these.",
"These come from the call's own options.",
),
// gcc.rs:201-214 TooHardFlag: preprocess-only and dependency-only calls
"-E" | "-M" | "-MM" | "-P" => expected(
"Preprocess-only or dependency-only call",
"The call only preprocesses the source or only writes dependency rules (-E, -M, -MM, -P), so it produces no object file; sccache lists these options as too hard to cache.",
"Your build tool runs these calls on purpose.",
),
// gcc.rs:352, rust.rs:1147, msvc.rs:590
"argument parse" => entry(
"A compiler option sccache could not read",
"sccache could not parse one of the compiler's arguments.",
"sccache does not say more in its counters; run the server with SCCACHE_LOG=debug to see the call.",
false,
),
// gcc.rs:375, clang.rs:192-295, msvc.rs:593: the reason is the option's own name.
other if other.starts_with('-') && other.len() > 1 => entry(
&format!("Option {other} is never cached"),
&format!(
"The compiler call contains {other}, which sccache's option table lists as too hard to cache, so every call with it runs uncached."
),
"If you do not need the option, remove it from the build's flags.",
true,
),
other => entry(
other,
"sccache does not say more.",
"",
false,
),
}
}
/// Dress counted reasons with their advice: fixable ones first, then expected ones, each
/// largest first.
pub fn describe(reasons: &[(String, u64)]) -> Vec<NotCached> {
let mut out: Vec<NotCached> = reasons
.iter()
.map(|(reason, count)| {
let a = advise(reason);
NotCached {
reason: reason.clone(),
count: *count,
name: a.name,
meaning: a.meaning,
action: a.action,
fixable: a.fixable,
}
})
.collect();
out.sort_by(|a, b| {
b.fixable
.cmp(&a.fixable)
.then_with(|| b.count.cmp(&a.count))
.then_with(|| a.reason.cmp(&b.reason))
});
out
}
/// How many compiles were lost to reasons that can be fixed, and the biggest of them.
pub fn fixable_loss(reasons: &[NotCached]) -> Option<(u64, &NotCached)> {
let top = reasons.iter().filter(|r| r.fixable).max_by_key(|r| r.count)?;
Some((reasons.iter().filter(|r| r.fixable).map(|r| r.count).sum(), top))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn incremental_says_how_to_turn_it_off_and_what_it_costs() {
let a = advise("incremental");
assert!(a.fixable);
assert!(a.action.contains("CARGO_INCREMENTAL=0"));
assert!(a.action.contains("[profile.dev]"));
assert!(a.action.contains("[build]"));
assert!(a.action.contains("trade-off"));
}
#[test]
fn crate_type_is_expected_and_names_what_is_cached() {
let a = advise("crate-type");
assert!(!a.fixable);
assert!(a.action.starts_with("Nothing to do"));
assert!(a.meaning.contains("lib, rlib and staticlib"));
}
#[test]
fn an_unknown_reason_is_shown_as_it_came() {
let a = advise("something new in 0.19");
assert_eq!(a.name, "something new in 0.19");
assert_eq!(a.meaning, "sccache does not say more.");
assert!(!a.fixable);
}
#[test]
fn an_option_name_is_a_fixable_reason_but_the_known_dashes_are_not() {
assert!(advise("-fplugin").fixable);
assert!(!advise("-").fixable);
assert!(!advise("-o").fixable);
}
#[test]
fn fixable_reasons_come_first_then_the_biggest() {
let out = describe(&[
("crate-type".to_owned(), 1548),
("-".to_owned(), 156),
("incremental".to_owned(), 1642),
("multiple input files".to_owned(), 63),
]);
let order: Vec<&str> = out.iter().map(|r| r.reason.as_str()).collect();
assert_eq!(order, ["incremental", "multiple input files", "crate-type", "-"]);
let (lost, top) = fixable_loss(&out).unwrap();
assert_eq!((lost, top.reason.as_str()), (1705, "incremental"));
assert!(fixable_loss(&out[2..]).is_none());
}
}
+401
View File
@@ -0,0 +1,401 @@
//! What the service knows right now, and how it is kept up to date. One task polls sccache, and
//! it alone holds the history and makes the views; requests only read what it made.
use std::ffi::{OsStr, OsString};
use std::io::{ErrorKind, Read};
use std::net::{SocketAddr, TcpStream};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use sccache_dash_api::{Range, View};
use serde_json::Value;
use wait_timeout::ChildExt;
use crate::history::{History, Tracker};
use crate::stats::Snapshot;
use crate::view::{self, Builds};
/// How often sccache is asked for its counters.
pub const POLL: Duration = Duration::from_secs(10);
/// A sccache command that takes longer than this counts as failed.
const COMMAND_TIMEOUT: Duration = Duration::from_secs(20);
const PRUNE_EVERY: Duration = Duration::from_secs(86_400);
/// When starting sccache's server fails, it is not tried again sooner than this.
pub const START_EVERY: i64 = 60;
/// The port sccache's server listens on when `SCCACHE_SERVER_PORT` does not say.
const SCCACHE_PORT: u16 = 4226;
pub struct Config {
/// The sccache command the service runs.
pub sccache: OsString,
/// The SQLite file the history is saved in.
pub history: PathBuf,
/// Whether to start sccache's server when none is listening. Off unless asked for: a
/// server started from here has this program's environment, not the builds', so it can
/// come up with another cache size or folder, and sccache trims the cache to the size
/// it is started with.
pub start_sccache: bool,
}
impl Config {
/// `SCCACHE_DASH_SCCACHE` names the sccache command (`sccache` when unset);
/// `SCCACHE_DASH_START_SCCACHE=1` lets it start sccache's server; the history
/// lives in `$XDG_DATA_HOME/sccache-dash/history.db`.
pub fn from_env() -> Result<Config, String> {
let sccache = std::env::var_os("SCCACHE_DASH_SCCACHE").unwrap_or_else(|| "sccache".into());
let dir = dirs::data_dir()
.ok_or("cannot find the data directory ($XDG_DATA_HOME, or ~/.local/share)")?;
Ok(Config {
sccache,
history: dir.join("sccache-dash").join("history.db"),
start_sccache: std::env::var_os("SCCACHE_DASH_START_SCCACHE").is_some_and(|v| v == "1"),
})
}
}
pub fn unix_now() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_secs() as i64)
}
/// The last reading sccache answered.
pub struct Live {
pub at: i64,
pub snapshot: Snapshot,
/// sccache's output, exactly as it printed it.
pub raw_text: String,
}
#[derive(Default)]
pub struct State {
pub live: Option<Live>,
/// sccache's output of the last good reading, as JSON.
pub raw: Option<Value>,
pub client_version: Option<String>,
/// Why sccache counts as not running.
pub error: Option<String>,
/// What the previous poll and the last saved row saw.
pub tracker: Tracker,
/// One view per range of [`Range::ALL`], made after every poll.
pub views: Vec<View>,
/// How long making those views took at the last poll, and how many rows the database
/// handed out for it: a count of the work, which does not depend on how busy the machine is.
pub views_took: Duration,
pub views_rows: usize,
/// Whether a failure to save has already been reported.
pub warned: bool,
/// How many polls have had their timing reported: the first two.
pub reported: u8,
}
/// Whether an sccache server is listening.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Probe {
Running,
NotRunning,
/// It could not be told; nothing is started then.
Unknown,
}
pub type Prober = Arc<dyn Fn() -> Probe + Send + Sync>;
pub struct App {
pub cfg: Config,
state: Mutex<State>,
/// Wakes the polling task, as `/api/zero` needs: only that task holds the database.
wake: (Sender<()>, Mutex<Option<Receiver<()>>>),
probe: Prober,
}
impl App {
pub fn new(cfg: Config) -> App {
App::with_probe(cfg, Arc::new(server_listening))
}
/// With a stand-in for the check on sccache's server, as tests need.
pub fn with_probe(cfg: Config, probe: Prober) -> App {
let (send, receive) = channel();
App {
cfg,
state: Mutex::new(State::default()),
wake: (send, Mutex::new(Some(receive))),
probe,
}
}
pub fn lock(&self) -> MutexGuard<'_, State> {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
/// The view made for `range` at the last poll. A request never touches the database.
pub fn view(&self, range: Range) -> View {
let state = self.lock();
let index = Range::ALL.iter().position(|r| *r == range).unwrap_or(1);
match state.views.get(index) {
Some(view) => view.clone(),
None => View {
range: Some(range),
..View::default()
},
}
}
/// Runs `sccache --zero-stats`; the saved history stays as it is.
pub fn zero(&self) -> Result<(), String> {
run(&self.cfg.sccache, &["--zero-stats"])?;
// The counters are read again right away by the polling task, which owns the database.
let _ = self.wake.0.send(());
Ok(())
}
/// Polls sccache every [`POLL`] (sooner when woken) and prunes the history once a day,
/// until the process ends. This task alone holds the database.
pub fn keep_updated(self: Arc<Self>) {
thread::spawn(move || {
let mut task = match Task::open(&self.cfg.history, unix_now()) {
Ok(task) => task,
Err(e) => {
eprintln!("sccache-dash: {e}");
std::process::exit(1);
}
};
let wake = self
.wake
.1
.lock()
.unwrap_or_else(PoisonError::into_inner)
.take();
let mut pruned = Instant::now();
loop {
task.poll(&self, unix_now());
if pruned.elapsed() >= PRUNE_EVERY {
pruned = Instant::now();
if let Err(e) = task.history.prune(unix_now()) {
eprintln!(
"sccache-dash: cannot prune {}: {e}",
self.cfg.history.display()
);
}
}
match &wake {
Some(receiver) => {
let _ = receiver.recv_timeout(POLL);
}
None => thread::sleep(POLL),
}
}
});
}
}
/// The polling task's own things: the history, whose connection is not shared, and what it has
/// learned of build times.
pub struct Task {
pub history: History,
builds: Builds,
/// When sccache's server was last tried to start, and why it is still not running.
started_at: Option<i64>,
start_error: Option<String>,
/// Whether the totals the last run remembered have been put back into the shared state.
resumed: bool,
}
impl Task {
/// Opens the history file, deleting what is too old.
pub fn open(path: &Path, now: i64) -> Result<Task, String> {
let history = History::open(path)?;
history
.prune(now)
.map_err(|e| format!("cannot prune {}: {e}", path.display()))?;
Ok(Task::with(history))
}
/// An empty history that is never written to disk, for tests.
pub fn memory() -> Task {
Task::with(History::memory().expect("an in-memory database"))
}
fn with(history: History) -> Task {
Task {
history,
builds: Builds::new(),
started_at: None,
start_error: None,
resumed: false,
}
}
/// Asks sccache for its counters and version, starting its server if none is listening,
/// records what changed, and makes the views.
pub fn poll(&mut self, app: &App, now: i64) {
let version = run(&app.cfg.sccache, &["--version"]).ok().and_then(|text| {
text.split_whitespace()
.find(|w| w.starts_with(|c: char| c.is_ascii_digit()))
.map(str::to_owned)
});
let mut read = read_stats(&app.cfg.sccache);
// Without a server, `--show-stats` answers with empty counters rather than starting one.
let probe = (app.probe)();
match (probe, read.is_ok()) {
(Probe::NotRunning, true) => match self.start_server(app, now) {
Ok(()) => read = read_stats(&app.cfg.sccache),
Err(e) => self.start_error = Some(e),
},
(Probe::Running | Probe::Unknown, _) => self.start_error = None,
(Probe::NotRunning, false) => {}
}
let mut state = app.lock();
if !self.resumed {
// Carry on where the last run stopped: its running totals are the base that the work
// not yet in a row is counted from, so a restart neither drops it nor counts it twice.
self.resumed = true;
state.tracker = self.history.tracker();
}
state.client_version = version;
match read {
Ok((text, snapshot)) => {
state.error = self.start_error.clone();
state.raw = serde_json::from_str(&text).ok();
state.live = Some(Live {
at: now,
snapshot,
raw_text: text,
});
}
Err(e) => {
state.error = Some(e);
state.live = None;
state.raw = None;
}
}
if let Some(counters) = state.live.as_ref().map(|l| l.snapshot.counters.clone()) {
match self.history.record(&mut state.tracker, &counters, now) {
Ok(()) => {}
Err(e) if !state.warned => {
state.warned = true;
eprintln!(
"sccache-dash: cannot save history to {}: {e}",
app.cfg.history.display()
);
}
Err(_) => {}
}
}
let started = Instant::now();
self.history.take_fetched();
self.builds.refresh(&self.history, now);
state.views = view::all(&self.history, &self.builds, &state, now);
state.views_took = started.elapsed();
state.views_rows = self.history.take_fetched();
// Reported for the first two polls: the first reads the build observations and draws the
// bootstrap, the second shows what every later poll costs.
if state.reported < 2 {
state.reported += 1;
eprintln!(
"sccache-dash: {} rows of history in {}; the five views take {:.2} ms and {} rows per poll",
self.history.row_count().unwrap_or(0),
app.cfg.history.display(),
state.views_took.as_secs_f64() * 1e3,
state.views_rows
);
}
}
/// Starts sccache's server when none is listening and that was asked for, at most once a minute. `Err` says why
/// there is none, including when an earlier attempt is still being waited out.
fn start_server(&mut self, app: &App, now: i64) -> Result<(), String> {
if !app.cfg.start_sccache {
return Err("no sccache server is running; your next build starts it".to_owned());
}
if let Some(when) = self.started_at {
if now - when < START_EVERY {
return Err(self
.start_error
.clone()
.unwrap_or_else(|| "no sccache server is running".to_owned()));
}
}
self.started_at = Some(now);
run(&app.cfg.sccache, &["--start-server"])
.map(|_| ())
.map_err(|e| {
format!("no sccache server is running and `sccache --start-server` failed: {e}")
})
}
}
fn read_stats(sccache: &OsStr) -> Result<(String, Snapshot), String> {
run(sccache, &["--show-stats", "--stats-format", "json"])
.and_then(|text| crate::stats::parse(&text).map(|snapshot| (text, snapshot)))
}
/// Whether an sccache server is listening, found the way its client finds it (`get_addr` in
/// sccache 0.18): `SCCACHE_SERVER_UDS` names its socket, otherwise it is on 127.0.0.1 at the
/// port `SCCACHE_SERVER_PORT` gives, 4226 by default. Only a connection is made and closed
/// again: no request is sent, so nothing is started, read or reset.
pub fn server_listening() -> Probe {
if let Some(path) = std::env::var_os("SCCACHE_SERVER_UDS").filter(|p| !p.is_empty()) {
return match std::os::unix::net::UnixStream::connect(path) {
Ok(_) => Probe::Running,
Err(e) if matches!(e.kind(), ErrorKind::NotFound | ErrorKind::ConnectionRefused) => {
Probe::NotRunning
}
Err(_) => Probe::Unknown,
};
}
let port = std::env::var("SCCACHE_SERVER_PORT")
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(SCCACHE_PORT);
match TcpStream::connect_timeout(
&SocketAddr::from(([127, 0, 0, 1], port)),
Duration::from_millis(500),
) {
Ok(_) => Probe::Running,
Err(e) if e.kind() == ErrorKind::ConnectionRefused => Probe::NotRunning,
Err(_) => Probe::Unknown,
}
}
/// Runs sccache and returns what it printed; `Err` says why when it is missing, fails or hangs.
fn run(sccache: &OsStr, args: &[&str]) -> Result<String, String> {
let mut child = Command::new(sccache)
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.map_err(|e| match e.kind() {
ErrorKind::NotFound => format!(
"`{} {}`: command not found",
sccache.to_string_lossy(),
args.join(" ")
),
_ => format!("`{} {}`: {e}", sccache.to_string_lossy(), args.join(" ")),
})?;
let named = format!("`{} {}`", sccache.to_string_lossy(), args.join(" "));
match child.wait_timeout(COMMAND_TIMEOUT) {
Ok(Some(status)) if status.success() => {}
Ok(Some(status)) => return Err(format!("{named} exited with {status}")),
Ok(None) => {
let _ = child.kill();
let _ = child.wait();
return Err(format!(
"{named} did not answer within {} seconds",
COMMAND_TIMEOUT.as_secs()
));
}
Err(e) => return Err(format!("{named}: {e}")),
}
let mut text = String::new();
if let Some(mut out) = child.stdout.take() {
out.read_to_string(&mut text)
.map_err(|e| format!("{named}: {e}"))?;
}
Ok(text)
}
+430
View File
@@ -0,0 +1,430 @@
//! The saved history in one SQLite file. Each row holds what changed since the row before it,
//! so that a range total is one indexed `SELECT SUM(...)` and the chart one `GROUP BY`. Rows come
//! at most one a minute and only when sccache's counters changed; a stretch without rows is a gap.
use std::cell::Cell;
use std::path::Path;
use std::time::Duration;
use rusqlite::{params, params_from_iter, Connection, OptionalExtension};
use sccache_dash_api::Totals;
use sccache_dash_stats::Observation;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use crate::stats::{Counters, COMPILE};
/// Rows older than this are deleted.
pub const KEEP_DAYS: i64 = 30;
/// Never more than one saved row per minute.
pub const MIN_ROW_SECS: i64 = 60;
const NANOS: f64 = 1e9;
/// The counters of a reading, each visited once: every query goes through this list.
macro_rules! each {
($m:ident!($($a:tt)*)) => {
$m!(requests, executed, hits, misses, not_cacheable, unsupported_compiler, not_compile,
timeouts, read_errors, write_errors, other_errors, compile_fails, forced_recaches,
cache_writes; $($a)*)
};
}
macro_rules! names {
($($c:ident),* ;) => { concat!($(",", stringify!($c)),*) };
}
macro_rules! defs {
($($c:ident),* ;) => { concat!($(",", stringify!($c), " INTEGER NOT NULL DEFAULT 0"),*) };
}
macro_rules! sums {
($($c:ident),* ;) => { concat!($(", SUM(", stringify!($c), ") AS ", stringify!($c)),*) };
}
macro_rules! totals_of {
($($c:ident),* ; $row:expr) => { Totals { $( $c: $row.get::<_, i64>(stringify!($c))?.max(0) as u64, )* } };
}
macro_rules! push {
($($c:ident),* ; $t:expr, $v:expr) => { $( $v.push(Box::new($t.$c as i64) as Box<dyn rusqlite::ToSql>); )* };
}
const NAMES: &str = each!(names!());
const DEFS: &str = each!(defs!());
const SUMS: &str = each!(sums!());
const OTHER_TABLES: &str = "
CREATE TABLE IF NOT EXISTS reading_languages (t INTEGER NOT NULL, language TEXT NOT NULL, hits INTEGER NOT NULL, misses INTEGER NOT NULL, errors INTEGER NOT NULL, PRIMARY KEY (t, language)) WITHOUT ROWID;
CREATE TABLE IF NOT EXISTS not_cached (t INTEGER NOT NULL, reason TEXT NOT NULL, count INTEGER NOT NULL, PRIMARY KEY (t, reason)) WITHOUT ROWID;
CREATE TABLE IF NOT EXISTS build_obs (t INTEGER NOT NULL, language TEXT NOT NULL, compiles INTEGER NOT NULL, seconds REAL NOT NULL, PRIMARY KEY (t, language)) WITHOUT ROWID;
CREATE INDEX IF NOT EXISTS build_obs_language ON build_obs (language);
CREATE TABLE IF NOT EXISTS state (key TEXT PRIMARY KEY, value TEXT NOT NULL) WITHOUT ROWID;";
/// What is remembered between polls, so that differences survive a restart of sccache-dash.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Tracker {
/// The running totals at the previous poll.
pub last_poll: Option<Counters>,
/// The running totals when the last row was saved.
pub row_base: Option<Counters>,
/// When the last row was saved.
pub row_at: i64,
}
/// What the live reading adds since the last saved row.
#[derive(Clone, Debug, PartialEq)]
pub struct Row {
pub t: i64,
/// sccache's counters went back to zero before this row.
pub reset: bool,
pub delta: Counters,
}
/// One bucket of the chart as SQLite adds it up; `b` is the bucket's number.
#[derive(Clone, Debug, PartialEq)]
pub struct BucketRow {
pub b: i64,
pub reset: bool,
/// When the first and the last row in the bucket are dated.
pub first: i64,
pub last: i64,
pub hits: u64,
pub misses: u64,
pub other: u64,
pub errors: u64,
}
/// One language's hits and misses in one bucket of the chart.
#[derive(Clone, Debug, PartialEq)]
pub struct BucketLangs {
pub b: i64,
pub language: String,
pub hits: u64,
pub misses: u64,
}
pub struct History {
conn: Connection,
/// How many rows queries have handed out since the last look: a count of the work done.
fetched: Cell<usize>,
}
impl History {
/// Opens (or creates) the file in WAL mode. The connection belongs to the task that polls.
pub fn open(path: &Path) -> Result<History, String> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
}
Self::init(Connection::open(path).map_err(|e| format!("{}: {e}", path.display()))?)
.map_err(|e| e.to_string())
}
/// An empty history that is never written to disk, for tests.
pub fn memory() -> rusqlite::Result<History> {
Self::init(Connection::open_in_memory()?)
}
fn init(conn: Connection) -> rusqlite::Result<History> {
let _: String = conn.query_row("PRAGMA journal_mode = WAL", [], |row| row.get(0))?;
conn.busy_timeout(Duration::from_secs(5))?;
conn.execute_batch(&format!(
"CREATE TABLE IF NOT EXISTS readings (t INTEGER PRIMARY KEY, reset INTEGER NOT NULL DEFAULT 0{DEFS}, \
compilations INTEGER NOT NULL DEFAULT 0, hit_read REAL NOT NULL DEFAULT 0, \
cache_write REAL NOT NULL DEFAULT 0, compile REAL NOT NULL DEFAULT 0);\n{OTHER_TABLES}"
))?;
Ok(History {
conn,
fetched: Cell::new(0),
})
}
/// How many rows queries handed out since the last look.
pub fn take_fetched(&self) -> usize {
self.fetched.replace(0)
}
fn count(&self, rows: usize) {
self.fetched.set(self.fetched.get() + rows);
}
/// Deletes the rows older than [`KEEP_DAYS`], and says how many went.
pub fn prune(&self, now: i64) -> rusqlite::Result<usize> {
let cutoff = now - KEEP_DAYS * 86_400;
let mut gone = 0;
for table in ["readings", "reading_languages", "not_cached", "build_obs"] {
gone += self
.conn
.execute(&format!("DELETE FROM {table} WHERE t < ?1"), [cutoff])?;
}
Ok(gone)
}
fn state<T: DeserializeOwned>(&self, key: &str) -> Option<T> {
let text: Option<String> = self
.conn
.query_row("SELECT value FROM state WHERE key = ?1", [key], |row| {
row.get(0)
})
.optional()
.ok()?;
text.and_then(|text| serde_json::from_str(&text).ok())
}
fn set_state<T: Serialize>(&self, key: &str, value: &T) -> rusqlite::Result<()> {
let value = serde_json::to_string(value)
.map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?;
self.conn.execute(
"INSERT INTO state (key, value) VALUES (?1, ?2) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
params![key, value],
)?;
Ok(())
}
/// Saves a run of readings exactly as the polls would have, in one transaction.
pub fn fill(&self, readings: &[(i64, Counters)]) -> rusqlite::Result<()> {
self.conn.execute_batch("BEGIN")?;
let mut tracker = self.tracker();
let result = readings
.iter()
.try_for_each(|(t, c)| self.record(&mut tracker, c, *t));
self.conn.execute_batch("COMMIT")?;
result
}
/// What the previous run of sccache-dash remembered, so that it carries on where it stopped.
pub fn tracker(&self) -> Tracker {
self.state("tracker").unwrap_or_default()
}
/// Records what a poll saw at `now`: a build-time observation when one language's builds
/// finished since the previous poll, a row when one is due and something changed, and the
/// totals for next time.
pub fn record(&self, tracker: &mut Tracker, c: &Counters, now: i64) -> rusqlite::Result<()> {
if let Some(previous) = &tracker.last_poll {
let (since, _) = c.since(previous);
if let Some((language, _)) = since.one_missed_language() {
self.conn.execute(
"INSERT OR REPLACE INTO build_obs (t, language, compiles, seconds) VALUES (?1, ?2, ?3, ?4)",
params![now, language, since.compilations as i64, since.ns[COMPILE] as f64 / NANOS],
)?;
}
}
// The first reading ever is a baseline. After it: a row a minute at most, and only when something changed.
match &tracker.row_base {
None => {
tracker.row_base = Some(c.clone());
tracker.row_at = now;
}
Some(base) => {
let (diff, reset) = c.since(base);
if (diff != Counters::default() || reset) && now - tracker.row_at >= MIN_ROW_SECS {
self.save(now, &diff, reset)?;
tracker.row_base = Some(c.clone());
tracker.row_at = now;
}
}
}
tracker.last_poll = Some(c.clone());
self.set_state("tracker", tracker)
}
/// Writes what changed since the row before.
fn save(&self, t: i64, diff: &Counters, reset: bool) -> rusqlite::Result<()> {
let mut values: Vec<Box<dyn rusqlite::ToSql>> = vec![Box::new(t), Box::new(reset)];
each!(push!(diff.totals, values));
values.push(Box::new(diff.compilations as i64));
for n in diff.ns {
values.push(Box::new(n as f64 / NANOS));
}
let marks = vec!["?"; NAMES.matches(',').count()].join(", ");
let sql = format!(
"INSERT INTO readings (t, reset{NAMES}, compilations, hit_read, cache_write, compile) VALUES (?, ?, {marks}, ?, ?, ?, ?)"
);
self.conn
.execute(&sql, params_from_iter(values.iter().map(|v| v.as_ref())))?;
let mut langs = self
.conn
.prepare("INSERT INTO reading_languages (t, language, hits, misses, errors) VALUES (?1, ?2, ?3, ?4, ?5)")?;
for (name, v) in &diff.langs {
langs.execute(params![t, name, v[0] as i64, v[1] as i64, v[2] as i64])?;
}
let mut reasons = self
.conn
.prepare("INSERT INTO not_cached (t, reason, count) VALUES (?1, ?2, ?3)")?;
for (reason, count) in &diff.not_cached {
reasons.execute(params![t, reason, *count as i64])?;
}
Ok(())
}
/// The counters summed over the rows from `from` (inclusive) to `to` (exclusive): one indexed
/// query. `None` when there is no row in that time. Languages and reasons are not part of it.
pub fn sums(&self, from: i64, to: i64) -> rusqlite::Result<Option<Counters>> {
let sql = format!(
"SELECT COUNT(*){SUMS}, SUM(compilations) AS compilations, SUM(hit_read) AS hit_read, \
SUM(cache_write) AS cache_write, SUM(compile) AS compile FROM readings WHERE t >= ?1 AND t < ?2"
);
self.count(1);
self.conn.query_row(&sql, params![from, to], |row| {
let rows: i64 = row.get(0)?;
let nanos = |name: &str| -> rusqlite::Result<u64> {
Ok((row.get::<_, f64>(name)? * NANOS).round().max(0.0) as u64)
};
Ok(if rows > 0 {
Some(Counters {
totals: each!(totals_of!(row)),
compilations: row.get::<_, i64>("compilations")?.max(0) as u64,
ns: [nanos("hit_read")?, nanos("cache_write")?, nanos("compile")?],
..Counters::default()
})
} else {
None
})
})
}
/// The chart's counts, one row per bucket: bucket `b` holds the rows dated from
/// `from + b * len` on, for `t` below `to`.
pub fn bucket_rows(&self, from: i64, len: i64, to: i64) -> rusqlite::Result<Vec<BucketRow>> {
let sql = "SELECT (t - ?1) / ?2 AS b, MAX(reset) != 0 AS reset, MIN(t) AS first, MAX(t) AS last, \
SUM(hits) AS hits, SUM(misses) AS misses, \
SUM(not_cacheable) + SUM(unsupported_compiler) + SUM(not_compile) AS other, \
SUM(read_errors) + SUM(write_errors) + SUM(other_errors) AS errors \
FROM readings WHERE t >= ?1 AND t < ?3 GROUP BY b";
let mut stmt = self.conn.prepare(sql)?;
let rows = stmt.query_map(params![from, len, to], |row| {
Ok(BucketRow {
b: row.get("b")?,
reset: row.get::<_, i64>("reset")? != 0,
first: row.get("first")?,
last: row.get("last")?,
hits: row.get::<_, i64>("hits")?.max(0) as u64,
misses: row.get::<_, i64>("misses")?.max(0) as u64,
other: row.get::<_, i64>("other")?.max(0) as u64,
errors: row.get::<_, i64>("errors")?.max(0) as u64,
})
})?;
let rows = rows.collect::<rusqlite::Result<Vec<_>>>()?;
self.count(rows.len());
Ok(rows)
}
/// Each language's hits and misses per bucket of the chart.
pub fn bucket_languages(
&self,
from: i64,
len: i64,
to: i64,
) -> rusqlite::Result<Vec<BucketLangs>> {
let mut stmt = self.conn.prepare(
"SELECT (t - ?1) / ?2 AS b, language, SUM(hits) AS hits, SUM(misses) AS misses \
FROM reading_languages WHERE t >= ?1 AND t < ?3 GROUP BY b, language",
)?;
let rows = stmt.query_map(params![from, len, to], |row| {
Ok(BucketLangs {
b: row.get("b")?,
language: row.get(1)?,
hits: row.get::<_, i64>(2)?.max(0) as u64,
misses: row.get::<_, i64>(3)?.max(0) as u64,
})
})?;
let rows = rows.collect::<rusqlite::Result<Vec<_>>>()?;
self.count(rows.len());
Ok(rows)
}
/// (language, [hits, misses, errors]) summed over the rows from `from` to `to`.
pub fn languages(&self, from: i64, to: i64) -> rusqlite::Result<Vec<(String, [u64; 3])>> {
let mut stmt = self.conn.prepare(
"SELECT language, SUM(hits), SUM(misses), SUM(errors) FROM reading_languages WHERE t >= ?1 AND t < ?2 GROUP BY language ORDER BY language",
)?;
let out = stmt.query_map(params![from, to], |row| {
Ok((
row.get(0)?,
[
row.get::<_, i64>(1)?.max(0) as u64,
row.get::<_, i64>(2)?.max(0) as u64,
row.get::<_, i64>(3)?.max(0) as u64,
],
))
})?;
let out = out.collect::<rusqlite::Result<Vec<_>>>()?;
self.count(out.len());
Ok(out)
}
/// (reason, count) summed over the rows from `from` to `to`.
pub fn reasons(&self, from: i64, to: i64) -> rusqlite::Result<Vec<(String, u64)>> {
let mut stmt = self.conn.prepare(
"SELECT reason, SUM(count) FROM not_cached WHERE t >= ?1 AND t < ?2 GROUP BY reason ORDER BY reason",
)?;
let out = stmt.query_map(params![from, to], |row| {
Ok((row.get(0)?, row.get::<_, i64>(1)?.max(0) as u64))
})?;
let out = out.collect::<rusqlite::Result<Vec<_>>>()?;
self.count(out.len());
Ok(out)
}
/// When the counters were last seen to be zeroed; `None` when they never were.
pub fn last_reset(&self) -> rusqlite::Result<Option<i64>> {
self.count(1);
self.conn
.query_row("SELECT MAX(t) FROM readings WHERE reset != 0", [], |row| {
row.get(0)
})
}
/// The oldest row there is: where the `reset` chart starts when no zeroing was ever seen.
pub fn first_row(&self) -> rusqlite::Result<Option<i64>> {
self.count(1);
self.conn
.query_row("SELECT MIN(t) FROM readings", [], |row| row.get(0))
}
/// How many rows there are, all told.
pub fn row_count(&self) -> rusqlite::Result<usize> {
Ok(self
.conn
.query_row("SELECT COUNT(*) FROM readings", [], |row| {
row.get::<_, i64>(0)
})? as usize)
}
/// `requests` summed over the rows from `from` on.
pub fn requests_since(&self, from: i64) -> rusqlite::Result<u64> {
self.count(1);
let sum: i64 = self.conn.query_row(
"SELECT COALESCE(SUM(requests), 0) FROM readings WHERE t >= ?1",
[from],
|row| row.get(0),
)?;
Ok(sum.max(0) as u64)
}
/// How many build observations there are and when the newest one is dated: one row, to tell
/// whether they changed.
pub fn build_obs_stamp(&self) -> rusqlite::Result<(i64, i64)> {
self.count(1);
self.conn.query_row(
"SELECT COUNT(*), COALESCE(MAX(t), 0) FROM build_obs",
[],
|row| Ok((row.get(0)?, row.get(1)?)),
)
}
/// The build observations dated after `after`: (language, what was seen).
pub fn build_obs_after(&self, after: i64) -> rusqlite::Result<Vec<(String, Observation)>> {
let mut stmt = self
.conn
.prepare("SELECT language, compiles, seconds FROM build_obs WHERE t > ?1 ORDER BY t")?;
let out = stmt.query_map([after], |row| {
Ok((
row.get(0)?,
Observation {
compiles: row.get::<_, i64>(1)?.max(0) as u64,
seconds: row.get(2)?,
},
))
})?;
let out = out.collect::<rusqlite::Result<Vec<_>>>()?;
self.count(out.len());
Ok(out)
}
}
+235
View File
@@ -0,0 +1,235 @@
//! The HTTP side: three routes and the page's files, on 127.0.0.1 only.
use std::io::Cursor;
use std::net::SocketAddr;
use std::sync::Arc;
use std::thread;
use include_dir::{include_dir, Dir};
use sccache_dash_api::Range;
use serde_json::Value;
use tiny_http::{Header, Request, Response, Server};
use crate::app::App;
use crate::pretty;
/// The page as `trunk build` wrote it to crates/ui/dist, or a placeholder saying it is not built
/// (the build script names the folder in `DASH_SITE`).
static SITE: Dir<'_> = include_dir!("$DASH_SITE");
type Reply = Response<Cursor<Vec<u8>>>;
/// Serves until the process ends.
pub fn serve(app: Arc<App>, port: u16) -> Result<(), String> {
answer(listen(port)?, app);
Ok(())
}
/// Binds 127.0.0.1 and nothing else; port 0 picks a free one.
pub fn listen(port: u16) -> Result<Server, String> {
Server::http(SocketAddr::from(([127, 0, 0, 1], port)))
.map_err(|e| format!("cannot listen on 127.0.0.1:{port}: {e}"))
}
/// The port a listening server answers on.
pub fn port_of(server: &Server) -> u16 {
server.server_addr().to_ip().map_or(0, |a| a.port())
}
/// Answers requests until the process ends.
pub fn answer(server: Server, app: Arc<App>) {
let port = port_of(&server);
for mut request in server.incoming_requests() {
let app = Arc::clone(&app);
thread::spawn(move || {
let response = handle(&app, port, &mut request);
let _ = request.respond(response);
});
}
}
fn handle(app: &App, port: u16, req: &mut Request) -> Reply {
let url = req.url();
let (path, query) = url.split_once('?').unwrap_or((url, ""));
match (req.method().as_str(), path) {
("GET", "/api/view") => match range_of(query) {
Some(range) => reply(
200,
"application/json",
serde_json::to_vec(&app.view(range)).unwrap_or_default(),
)
.with_header(header("Cache-Control", "no-store")),
None => text(400, "unknown range: use 1h, 24h, 7d, 30d or reset"),
},
("GET" | "HEAD", "/api/export") => export(app),
("POST", "/api/zero") => zero(app, port, req),
(_, "/api/zero") => text(405, "use POST"),
("GET" | "HEAD", _) => site_file(path),
_ => text(404, "not found"),
}
}
/// `range=24h` in the query string.
fn range_of(query: &str) -> Option<Range> {
let value = query.split('&').find_map(|p| p.strip_prefix("range="))?;
serde_json::from_value(Value::String(value.to_owned())).ok()
}
/// sccache's output exactly as it printed it, as a download.
fn export(app: &App) -> Reply {
let state = app.lock();
match &state.live {
Some(live) => reply(200, "application/json", live.raw_text.clone().into_bytes())
.with_header(header(
"Content-Disposition",
&format!(
"attachment; filename=\"sccache-stats-{}.json\"",
pretty::stamp(live.at)
),
)),
None => text(
502,
&format!(
"sccache did not answer: {}",
state.error.as_deref().unwrap_or("no reading yet")
),
),
}
}
/// Runs `sccache --zero-stats`. Only this machine's own dashboard may ask for that.
fn zero(app: &App, port: u16, req: &Request) -> Reply {
if !from_own_page(req, port) {
return text(
403,
"refused: only the dashboard's own page, on this machine, may zero the stats",
);
}
match app.zero() {
Ok(()) => text(
200,
"sccache's counters were zeroed; the saved history is kept",
),
Err(e) => text(502, &format!("could not zero the stats: {e}")),
}
}
/// Whether a request comes from the dashboard itself: its `Host` is localhost, and when a web
/// page sent it (it carries an `Origin`) that page is this server. A page anywhere else must
/// not be able to zero the stats, and neither may a host name that merely resolves here.
fn from_own_page(req: &Request, port: u16) -> bool {
let header = |name: &'static str| {
req.headers()
.iter()
.find(|h| h.field.equiv(name))
.map(|h| h.value.as_str())
};
// `name` or `name:port`, with a port made of digits and nothing else.
let host_is_local = |host: &str| {
let mut parts = host.splitn(2, ':');
let name = parts.next().unwrap_or_default();
let port = parts.next().unwrap_or("");
(name.eq_ignore_ascii_case("127.0.0.1") || name.eq_ignore_ascii_case("localhost"))
&& port.bytes().all(|b| b.is_ascii_digit())
};
let own_origins = [
format!("http://127.0.0.1:{port}"),
format!("http://localhost:{port}"),
];
header("Host").is_some_and(host_is_local)
&& header("Origin").is_none_or(|origin| own_origins.iter().any(|own| own == origin))
}
/// A file of the page; `/` is its index.
fn site_file(path: &str) -> Reply {
let name = path.trim_start_matches('/');
let name = if name.is_empty() { "index.html" } else { name };
match SITE.get_file(name) {
Some(file) => reply(200, content_type(name), file.contents().to_vec()),
None => text(404, "not found"),
}
}
/// Content types by file extension, as the page's own files need them.
fn content_type(path: &str) -> &'static str {
match path.rsplit_once('.').map(|(_, ext)| ext) {
Some("html") => "text/html; charset=utf-8",
Some("js" | "mjs") => "text/javascript; charset=utf-8",
Some("wasm") => "application/wasm",
Some("css") => "text/css; charset=utf-8",
Some("json" | "map") => "application/json",
Some("svg") => "image/svg+xml",
Some("png") => "image/png",
Some("jpg" | "jpeg") => "image/jpeg",
Some("gif") => "image/gif",
Some("webp") => "image/webp",
Some("ico") => "image/x-icon",
Some("woff") => "font/woff",
Some("woff2") => "font/woff2",
Some("ttf") => "font/ttf",
Some("otf") => "font/otf",
Some("txt" | "md") => "text/plain; charset=utf-8",
_ => "application/octet-stream",
}
}
fn header(name: &'static str, value: &str) -> Header {
Header::from_bytes(name.as_bytes(), value.as_bytes()).expect("a header made of plain ASCII")
}
fn reply(code: u16, content_type: &str, body: Vec<u8>) -> Reply {
Response::from_data(body)
.with_status_code(code)
.with_header(header("Content-Type", content_type))
}
fn text(code: u16, body: &str) -> Reply {
reply(code, "text/plain; charset=utf-8", body.as_bytes().to_vec())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_page_or_its_placeholder_is_in_the_binary() {
assert!(
SITE.get_file("index.html").is_some(),
"`/` must answer with a page"
);
assert!(
SITE.get_file("../Cargo.toml").is_none(),
"nothing outside the page is served"
);
assert!(SITE.get_file("no-such-file").is_none());
}
#[test]
fn content_types_are_what_browsers_need() {
assert_eq!(content_type("index.html"), "text/html; charset=utf-8");
assert_eq!(
content_type("app-a1b2c3.js"),
"text/javascript; charset=utf-8"
);
assert_eq!(content_type("app-a1b2c3.wasm"), "application/wasm");
assert_eq!(content_type("app.css"), "text/css; charset=utf-8");
assert_eq!(content_type("icons/sccache.svg"), "image/svg+xml");
assert_eq!(content_type("data"), "application/octet-stream");
}
#[test]
fn the_range_comes_from_the_query_string() {
for (query, expected) in [
("range=1h", Some(Range::Hour)),
("range=24h", Some(Range::Day)),
("range=7d", Some(Range::Week)),
("range=30d", Some(Range::Month)),
("range=reset", Some(Range::SinceReset)),
("other=1&range=24h", Some(Range::Day)),
("", None),
("range=all", None),
] {
assert_eq!(range_of(query), expected, "{query:?}");
}
}
}
+11
View File
@@ -0,0 +1,11 @@
//! The server half of sccache-dash: it asks sccache for its counters, keeps their history and
//! serves the page that draws them.
pub mod advice;
pub mod app;
pub mod history;
pub mod http;
pub mod pretty;
pub mod stats;
pub mod systemd;
pub mod view;
+163
View File
@@ -0,0 +1,163 @@
//! `sccache-dash`: serves the dashboard, or installs itself as a user service.
use std::process::{Command as Process, Stdio};
use std::sync::Arc;
use sccache_dash::app::{App, Config};
use sccache_dash::{http, systemd};
const USAGE: &str = "\
sccache-dash [--port N] [--no-open] serve the dashboard on http://127.0.0.1:8226 and open it
sccache-dash install start it at login, as a systemd user service
sccache-dash uninstall remove that service again";
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
if let Err(e) = run(&args) {
eprintln!("sccache-dash: {e}");
std::process::exit(1);
}
}
fn run(args: &[String]) -> Result<(), String> {
match parse(args)? {
Command::Help => println!("{USAGE}"),
Command::Install => systemd::install()?,
Command::Uninstall => systemd::uninstall()?,
Command::Serve { port, open } => serve(port, open)?,
}
Ok(())
}
/// What the command line asks for.
#[derive(Debug)]
enum Command {
Serve { port: u16, open: bool },
Install,
Uninstall,
Help,
}
fn parse(args: &[String]) -> Result<Command, String> {
let mut serve = Command::Serve {
port: sccache_dash_api::DEFAULT_PORT,
open: true,
};
let mut i = 0;
while let Some(arg) = args.get(i) {
i += 1;
match arg.as_str() {
"--no-open" => {
if let Command::Serve { open, .. } = &mut serve {
*open = false;
}
}
"--help" | "-h" => return Ok(Command::Help),
"install" => return Ok(Command::Install),
"uninstall" => return Ok(Command::Uninstall),
a if a == "--port" || a.starts_with("--port=") => {
let value = match a.strip_prefix("--port=") {
Some(value) => value.to_owned(),
None => {
i += 1;
args.get(i - 1)
.ok_or("--port needs a number, as in --port 8226")?
.clone()
}
};
let port = value
.parse()
.map_err(|_| format!("`{value}` is not a port number"))?;
if let Command::Serve { port: p, .. } = &mut serve {
*p = port;
}
}
a => return Err(format!("unknown argument `{a}`\n\n{USAGE}")),
}
}
Ok(serve)
}
fn serve(port: u16, open: bool) -> Result<(), String> {
let app = Arc::new(App::new(Config::from_env()?));
let server = http::listen(port)?;
let port = http::port_of(&server);
let url = format!("http://127.0.0.1:{port}");
println!(
"sccache-dash: serving {url}, history in {}",
app.cfg.history.display()
);
app.clone().keep_updated();
if open {
// Left to finish on its own: a browser that will not open is not worth stopping for.
let browser = Process::new("xdg-open")
.arg(&url)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn();
if let Ok(mut browser) = browser {
std::thread::spawn(move || {
let _ = browser.wait();
});
}
}
http::answer(server, app);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn parse_args(args: &[&str]) -> Result<Command, String> {
parse(&args.iter().map(|a| a.to_string()).collect::<Vec<_>>())
}
#[test]
fn the_command_line() {
assert!(matches!(
parse_args(&[]),
Ok(Command::Serve {
port: 8226,
open: true
})
));
assert!(matches!(
parse_args(&["--port", "18226"]),
Ok(Command::Serve {
port: 18226,
open: true
})
));
assert!(matches!(
parse_args(&["--port=9000", "--no-open"]),
Ok(Command::Serve {
port: 9000,
open: false
})
));
assert!(matches!(
parse_args(&["--no-open", "--port", "1"]),
Ok(Command::Serve {
port: 1,
open: false
})
));
assert!(matches!(parse_args(&["install"]), Ok(Command::Install)));
assert!(matches!(parse_args(&["uninstall"]), Ok(Command::Uninstall)));
assert!(matches!(parse_args(&["--help"]), Ok(Command::Help)));
assert!(parse_args(&["18226"])
.unwrap_err()
.starts_with("unknown argument `18226`"));
assert!(parse_args(&["--port"])
.unwrap_err()
.contains("--port needs a number"));
assert!(parse_args(&["--port", "x"])
.unwrap_err()
.contains("`x` is not a port number"));
assert!(parse_args(&["--port", "70000"])
.unwrap_err()
.contains("is not a port number"));
}
}
+135
View File
@@ -0,0 +1,135 @@
//! How numbers, times and sizes are written for people.
/// `2815` as "2,815".
pub fn thousands(n: u64) -> String {
let digits = n.to_string();
let mut out = String::with_capacity(digits.len() + digits.len() / 3);
for (i, c) in digits.chars().enumerate() {
if i > 0 && (digits.len() - i).is_multiple_of(3) {
out.push(',');
}
out.push(c);
}
out
}
/// A share as a percentage with one decimal, dropping a needless ".0": `0.076` as "7.6", `1.0` as "100".
pub fn pct(share: f64) -> String {
let s = format!("{:.1}", share * 100.0);
s.strip_suffix(".0").unwrap_or(&s).to_owned()
}
/// Seconds rounded down to minutes, the way the summary says them: "3h 05m", "48m", "<1m".
pub fn hours_and_minutes(secs: f64) -> String {
let mins = (secs / 60.0).floor() as u64;
match mins {
0 => "<1m".to_owned(),
1..=59 => format!("{mins}m"),
_ => format!("{}h {:02}m", mins / 60, mins % 60),
}
}
/// A short length of time: "210 ms", "0.9 s", "7.8 s", "20 min".
pub fn short(secs: f64) -> String {
if secs < 1.0 {
format!("{:.0} ms", secs * 1000.0)
} else if secs < 600.0 {
let s = format!("{secs:.1}");
format!("{} s", s.strip_suffix(".0").unwrap_or(&s))
} else {
format!("{:.0} min", secs / 60.0)
}
}
/// Two sizes as one phrase: sccache's 10G limit reads "10.0 of 10.0 GB", and sizes in different
/// units read "900.0 MB of 10.0 GB".
pub fn bytes_of(size: u64, max: u64) -> String {
let (a, au) = amount(size);
let (b, bu) = amount(max);
if au == bu {
format!("{a} of {b} {au}")
} else {
format!("{a} {au} of {b} {bu}")
}
}
fn amount(b: u64) -> (String, &'static str) {
const K: f64 = 1024.0;
let b = b as f64;
if b >= K * K * K * K {
(format!("{:.1}", b / (K * K * K * K)), "TB")
} else if b >= K * K * K {
(format!("{:.1}", b / (K * K * K)), "GB")
} else if b >= K * K {
(format!("{:.1}", b / (K * K)), "MB")
} else {
(format!("{b:.0}"), "KB")
}
}
/// Unix seconds as a file-name-friendly UTC time: `0` as "19700101-000000".
pub fn stamp(secs: i64) -> String {
let (days, rem) = (secs.div_euclid(86_400), secs.rem_euclid(86_400));
// Days since 1970-01-01 to a date, by Howard Hinnant's algorithm.
let z = days + 719_468;
let (era, doe) = (z.div_euclid(146_097), z.rem_euclid(146_097));
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = yoe + era * 400 + i64::from(m <= 2);
format!(
"{y:04}{m:02}{d:02}-{:02}{:02}{:02}",
rem / 3600,
rem % 3600 / 60,
rem % 60
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn numbers_as_written() {
assert_eq!(thousands(0), "0");
assert_eq!(thousands(2815), "2,815");
assert_eq!(thousands(1_234_567), "1,234,567");
assert_eq!(pct(0.076), "7.6");
assert_eq!(pct(0.5018), "50.2");
assert_eq!(pct(1.0), "100");
}
#[test]
fn times_as_written() {
assert_eq!(hours_and_minutes(11100.0), "3h 05m");
assert_eq!(hours_and_minutes(48.4 * 60.0), "48m");
assert_eq!(hours_and_minutes(20.0), "<1m");
assert_eq!(short(0.21), "210 ms");
assert_eq!(short(0.9), "900 ms");
assert_eq!(short(10.0), "10 s");
assert_eq!(short(60.0), "60 s");
assert_eq!(short(1200.0), "20 min");
}
#[test]
fn sizes_and_dates_as_written() {
assert_eq!(
bytes_of(10 * 1024 * 1024 * 1024, 10 * 1024 * 1024 * 1024),
"10.0 of 10.0 GB"
);
assert_eq!(bytes_of(1024 * 1024, 1024 * 1024), "1.0 of 1.0 MB");
assert_eq!(bytes_of(10_726_353_131, 10_737_418_240), "10.0 of 10.0 GB");
assert_eq!(
bytes_of(9 * 1024 * 1024 * 1024, 10 * 1024 * 1024 * 1024),
"9.0 of 10.0 GB"
);
assert_eq!(
bytes_of(900 * 1024 * 1024, 10 * 1024 * 1024 * 1024),
"900.0 MB of 10.0 GB"
);
assert_eq!(stamp(0), "19700101-000000");
assert_eq!(stamp(1_764_000_000), "20251124-160000"); // what `date -u -d @1764000000` says
}
}
+576
View File
@@ -0,0 +1,576 @@
//! sccache's counters: reading them out of its JSON and telling two readings apart.
use std::collections::BTreeMap;
use sccache_dash_api::{Extra, Totals};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::pretty;
/// Positions in [`Counters::ns`].
pub const HIT_READ: usize = 0;
pub const CACHE_WRITE: usize = 1;
pub const COMPILE: usize = 2;
/// sccache's counters at one moment. Each only grows, until sccache resets them.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Counters {
#[serde(default)]
pub totals: Totals,
/// Compiler runs: misses, plus compiles that could not be cached or failed.
#[serde(default)]
pub compilations: u64,
/// Nanoseconds spent reading hits, writing cache entries and running compilers.
#[serde(default)]
pub ns: [u64; 3],
/// (language, [hits, misses, errors]) by name, for languages that have counted something.
#[serde(default)]
pub langs: Vec<(String, [u64; 3])>,
/// (reason, count) by name, for reasons that have counted something.
#[serde(default)]
pub not_cached: Vec<(String, u64)>,
}
impl Counters {
/// What happened between `older` and `self`, and whether sccache reset its counters in between.
///
/// A counter that went down can only mean sccache zeroed its counters (a new server, or
/// `--zero-stats`), and it zeroes all of them at once: every difference is then the new value.
pub fn since(&self, older: &Counters) -> (Counters, bool) {
let mut reset = false;
let mut sub = |a: u64, b: u64| {
if b < a {
reset = true;
}
b.saturating_sub(a)
};
let (a, b) = (&older.totals, &self.totals);
let totals = Totals {
requests: sub(a.requests, b.requests),
executed: sub(a.executed, b.executed),
hits: sub(a.hits, b.hits),
misses: sub(a.misses, b.misses),
not_cacheable: sub(a.not_cacheable, b.not_cacheable),
unsupported_compiler: sub(a.unsupported_compiler, b.unsupported_compiler),
not_compile: sub(a.not_compile, b.not_compile),
timeouts: sub(a.timeouts, b.timeouts),
read_errors: sub(a.read_errors, b.read_errors),
write_errors: sub(a.write_errors, b.write_errors),
other_errors: sub(a.other_errors, b.other_errors),
compile_fails: sub(a.compile_fails, b.compile_fails),
forced_recaches: sub(a.forced_recaches, b.forced_recaches),
cache_writes: sub(a.cache_writes, b.cache_writes),
};
let compilations = sub(older.compilations, self.compilations);
let mut ns = [0; 3];
for (d, (a, b)) in ns.iter_mut().zip(older.ns.iter().zip(self.ns.iter())) {
*d = sub(*a, *b);
}
let langs = self
.langs
.iter()
.filter_map(|(name, v)| {
let o = older
.langs
.iter()
.find(|(k, _)| k == name)
.map_or([0; 3], |(_, o)| *o);
let mut d = [0; 3];
for (d, (a, b)) in d.iter_mut().zip(o.iter().zip(v.iter())) {
*d = sub(*a, *b);
}
(d != [0; 3]).then(|| (name.clone(), d))
})
.collect();
let not_cached = self
.not_cached
.iter()
.filter_map(|(name, v)| {
let o = older
.not_cached
.iter()
.find(|(k, _)| k == name)
.map_or(0, |(_, o)| *o);
let d = sub(o, *v);
(d > 0).then(|| (name.clone(), d))
})
.collect();
let diff = Counters {
totals,
compilations,
ns,
langs,
not_cached,
};
(if reset { self.clone() } else { diff }, reset)
}
/// The language of the misses when they were all of one language: (name, misses).
pub fn one_missed_language(&self) -> Option<(&str, u64)> {
let mut with_misses = self.langs.iter().filter(|(_, v)| v[1] > 0);
let (name, v) = with_misses.next()?;
with_misses.next().is_none().then(|| (name.as_str(), v[1]))
}
/// Adds another set of counters into this one.
pub fn add(&mut self, other: &Counters) {
macro_rules! sum {
($($f:ident),* $(,)?) => { $( self.totals.$f += other.totals.$f; )* };
}
sum!(
requests,
executed,
hits,
misses,
not_cacheable,
unsupported_compiler,
not_compile,
timeouts,
read_errors,
write_errors,
other_errors,
compile_fails,
forced_recaches,
cache_writes,
);
self.compilations += other.compilations;
for (n, x) in self.ns.iter_mut().zip(other.ns.iter()) {
*n += x;
}
for (name, v) in &other.langs {
match self.langs.iter_mut().find(|(k, _)| k == name) {
Some((_, have)) => {
for (h, x) in have.iter_mut().zip(v.iter()) {
*h += x;
}
}
None => self.langs.push((name.clone(), *v)),
}
}
for (name, v) in &other.not_cached {
match self.not_cached.iter_mut().find(|(k, _)| k == name) {
Some((_, have)) => *have += v,
None => self.not_cached.push((name.clone(), *v)),
}
}
}
}
/// One level of a multi-level cache, as sccache 0.18 reports it in `stats.multi_level`.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Level {
pub name: String,
pub location: String,
pub hits: u64,
pub misses: u64,
pub writes: u64,
pub write_failures: u64,
pub backfills_from: u64,
pub backfills_to: u64,
pub hit_ns: u64,
pub write_ns: u64,
}
/// What one run of `sccache --show-stats --stats-format json` said.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Snapshot {
pub counters: Counters,
pub version: Option<String>,
pub cache_location: Option<String>,
pub cache_size: Option<u64>,
pub max_cache_size: Option<u64>,
pub multi_level: Vec<Level>,
/// (server, compiles) by server, sorted by server.
pub dist_compiles: Vec<(String, u64)>,
pub dist_errors: u64,
}
/// Reads sccache's JSON. Unknown fields are ignored and missing ones read as zero, so a new
/// sccache cannot break this; only output that is not JSON with a `stats` object is an error.
pub fn parse(text: &str) -> Result<Snapshot, String> {
let root: Value =
serde_json::from_str(text).map_err(|e| format!("sccache's output is not JSON ({e})"))?;
let stats = root
.get("stats")
.ok_or("sccache's output has no \"stats\" object")?;
let (hits, misses, errors) = (
counts(stats, "cache_hits"),
counts(stats, "cache_misses"),
counts(stats, "cache_errors"),
);
let mut by_lang: BTreeMap<&str, [u64; 3]> = BTreeMap::new();
for (map, i) in [(&hits, 0), (&misses, 1), (&errors, 2)] {
for (name, n) in map {
by_lang.entry(name.as_str()).or_default()[i] = *n;
}
}
let n = |field: &str| num(stats.get(field));
let totals = Totals {
requests: n("compile_requests"),
executed: n("requests_executed"),
hits: hits.values().sum(),
misses: misses.values().sum(),
not_cacheable: n("requests_not_cacheable"),
unsupported_compiler: n("requests_unsupported_compiler"),
not_compile: n("requests_not_compile"),
timeouts: n("cache_timeouts"),
read_errors: n("cache_read_errors"),
write_errors: n("cache_write_errors"),
other_errors: errors.values().sum(),
compile_fails: n("compile_fails"),
forced_recaches: n("forced_recaches"),
cache_writes: n("cache_writes"),
};
let counters = Counters {
totals,
compilations: n("compilations"),
ns: [
nanos(stats.get("cache_read_hit_duration")),
nanos(stats.get("cache_write_duration")),
nanos(stats.get("compiler_write_duration")),
],
langs: by_lang
.into_iter()
.map(|(name, v)| (name.to_owned(), v))
.collect(),
not_cached: pairs(stats.get("not_cached")).into_iter().collect(),
};
let text = |field: &str| root.get(field).and_then(Value::as_str).map(str::to_owned);
let multi_level = stats
.get("multi_level")
.and_then(Value::as_array)
.map(|levels| {
levels
.iter()
.filter_map(|l| {
let s = |f: &str| Some(l.get(f)?.as_str()?.to_owned());
Some(Level {
name: s("name")?,
location: s("location")?,
hits: num(l.get("hits")),
misses: num(l.get("misses")),
writes: num(l.get("writes")),
write_failures: num(l.get("write_failures")),
backfills_from: num(l.get("backfills_from")),
backfills_to: num(l.get("backfills_to")),
hit_ns: nanos(l.get("hit_duration")),
write_ns: nanos(l.get("write_duration")),
})
})
.collect()
})
.unwrap_or_default();
Ok(Snapshot {
counters,
version: text("version"),
cache_location: text("cache_location"),
cache_size: root.get("cache_size").and_then(Value::as_u64),
max_cache_size: root.get("max_cache_size").and_then(Value::as_u64),
multi_level,
dist_compiles: pairs(stats.get("dist_compiles"))
.into_iter()
.filter(|(_, n)| *n > 0)
.collect(),
dist_errors: n("dist_errors"),
})
}
/// A number as sccache writes it; anything else reads as zero.
fn num(v: Option<&Value>) -> u64 {
v.and_then(Value::as_u64).unwrap_or(0)
}
/// `{"secs": 1, "nanos": 2}` as nanoseconds.
fn nanos(v: Option<&Value>) -> u64 {
let o = v.and_then(Value::as_object);
let get = |k: &str| {
o.and_then(|o| o.get(k))
.and_then(Value::as_u64)
.unwrap_or(0)
};
get("secs") * 1_000_000_000 + get("nanos")
}
/// A JSON object of counts as a sorted map.
fn pairs(v: Option<&Value>) -> BTreeMap<String, u64> {
v.and_then(Value::as_object)
.map(|o| {
o.iter()
.filter_map(|(k, v)| Some((k.clone(), v.as_u64()?)))
.collect()
})
.unwrap_or_default()
}
/// `{"counts": {...}}` as a sorted map.
fn counts(parent: &Value, field: &str) -> BTreeMap<String, u64> {
pairs(parent.get(field).and_then(|f| f.get("counts")))
}
/// The tables for what sccache reports beyond the usual counters, empty when it reports nothing.
pub fn extras(s: &Snapshot) -> Vec<Extra> {
let mut out = Vec::new();
if !s.multi_level.is_empty() {
let rows = s
.multi_level
.iter()
.map(|l| {
let per = |total: u64, n: u64| (n > 0).then(|| total as f64 / n as f64 / 1e9);
(
format!("{} \u{2014} {}", l.name, l.location),
format!(
"{} hits \u{b7} {} misses \u{b7} {} writes, {} failed \u{b7} backfilled {} in, {} out \u{b7} avg hit read {} \u{b7} avg write {}",
pretty::thousands(l.hits),
pretty::thousands(l.misses),
pretty::thousands(l.writes),
pretty::thousands(l.write_failures),
pretty::thousands(l.backfills_from),
pretty::thousands(l.backfills_to),
per(l.hit_ns, l.hits).map_or_else(|| "\u{2014}".to_owned(), pretty::short),
per(l.write_ns, l.writes).map_or_else(|| "\u{2014}".to_owned(), pretty::short),
),
)
})
.collect();
out.push(Extra {
title: "Multi-level cache".to_owned(),
rows,
});
}
if !s.dist_compiles.is_empty() || s.dist_errors > 0 {
let mut rows: Vec<_> = s
.dist_compiles
.iter()
.map(|(server, n)| (server.clone(), pretty::thousands(*n)))
.collect();
rows.push((
"Errors (re-run locally)".to_owned(),
pretty::thousands(s.dist_errors),
));
out.push(Extra {
title: "Distributed compiles".to_owned(),
rows,
});
}
out
}
#[cfg(test)]
mod tests {
use super::*;
const LIVE: &str = include_str!("../../../fixtures/live-0.18.0.json");
const MULTILEVEL: &str = include_str!("../../../fixtures/sample-multilevel.json");
const DIST: &str = include_str!("../../../fixtures/sample-dist.json");
fn counters(requests: u64, hits: u64, misses: u64) -> Counters {
Counters {
totals: Totals {
requests,
hits,
misses,
..Totals::default()
},
compilations: misses,
langs: vec![("Rust".to_owned(), [hits, misses, 0])],
..Counters::default()
}
}
#[test]
fn live_output_is_read_as_it_is() {
let s = parse(LIVE).unwrap();
assert_eq!(
s.counters.totals,
Totals {
requests: 7351,
executed: 6495,
hits: 3197,
misses: 3256,
not_cacheable: 829,
not_compile: 27,
other_errors: 0,
compile_fails: 39,
cache_writes: 3256,
..Totals::default()
}
);
assert_eq!(s.counters.compilations, 3256);
assert_eq!(
s.counters.ns,
[2_190_691_578, 8_758_680_079, 25_343_119_040_435]
);
assert_eq!(
s.counters.langs,
vec![
("Assembler".to_owned(), [886, 0, 0]),
("C/C++".to_owned(), [2082, 0, 0]),
("Rust".to_owned(), [229, 3256, 0]),
]
);
assert_eq!(s.counters.not_cached.len(), 7);
assert_eq!(s.counters.not_cached[0], ("-".to_owned(), 35));
assert_eq!(s.version.as_deref(), Some("0.18.0"));
assert_eq!(
s.cache_location.as_deref(),
Some("Local disk: \"/home/swaits/.cache/sccache\"")
);
assert_eq!(
(s.cache_size, s.max_cache_size),
(Some(10_726_353_131), Some(10_737_418_240))
);
assert!(s.multi_level.is_empty() && s.dist_compiles.is_empty() && s.dist_errors == 0);
assert!(
extras(&s).is_empty(),
"nothing extra is reported, so there are no extra tables"
);
}
#[test]
fn counters_survive_the_round_trip_through_saved_state() {
// The totals sccache-dash remembers between polls are saved as JSON.
let counters = parse(LIVE).unwrap().counters;
let text = serde_json::to_string(&counters).unwrap();
assert_eq!(serde_json::from_str::<Counters>(&text).unwrap(), counters);
assert!(text.len() < 1024, "{} bytes: {text}", text.len());
}
#[test]
fn unknown_and_missing_fields_do_not_break_it() {
let s = parse(
"{\"stats\":{\"compile_requests\":\"many\",\"cache_hits\":{\"counts\":{\"Rust\":-1}},\"new_field\":1},\"extra\":2}",
)
.unwrap();
assert_eq!(s.counters, Counters::default());
assert_eq!(parse("{\"stats\":{}}").unwrap(), Snapshot::default());
assert_eq!(
parse("{\"stats\":null,\"version\":\"1.0\"}")
.unwrap()
.version
.as_deref(),
Some("1.0")
);
assert!(parse("not json").is_err());
assert!(parse("{\"error\":\"no server\"}").is_err());
}
#[test]
fn differences_are_what_grew() {
let (older, newer) = (counters(100, 60, 40), counters(130, 80, 50));
let (diff, reset) = newer.since(&older);
assert_eq!(diff.totals.requests, 30);
assert_eq!(diff.totals.hits, 20);
assert_eq!(diff.totals.misses, 10);
assert_eq!(diff.langs, vec![("Rust".to_owned(), [20, 10, 0])]);
assert!(!reset);
let (same, _) = newer.since(&newer);
assert!(same.totals == Totals::default() && same.langs.is_empty());
}
#[test]
fn a_counter_going_down_zeroes_the_whole_reading() {
let mut older = counters(100, 60, 40);
older.not_cached.push(("crate-type".to_owned(), 9));
older.ns[COMPILE] = 400;
let mut newer = counters(130, 5, 0);
newer.not_cached.push(("crate-type".to_owned(), 2));
newer.not_cached.push(("-o".to_owned(), 1));
newer.ns[COMPILE] = 7;
let (diff, reset) = newer.since(&older);
assert!(
reset,
"hits went down, so the counters were zeroed in between"
);
assert_eq!(
diff, newer,
"every difference is the new value, even where the counter grew"
);
}
#[test]
fn sums_merge_languages_and_reasons() {
let mut a = counters(10, 4, 6);
a.not_cached.push(("crate-type".to_owned(), 1));
let mut b = counters(1, 1, 0);
b.compilations = 0;
b.langs = vec![
("C/C++".to_owned(), [1, 0, 0]),
("Rust".to_owned(), [0, 0, 2]),
];
b.not_cached.push(("crate-type".to_owned(), 2));
b.not_cached.push(("incremental".to_owned(), 1));
a.add(&b);
assert_eq!(a.totals.requests, 11);
assert_eq!(a.totals.hits, 5);
assert_eq!(a.compilations, 6);
assert_eq!(
a.langs,
vec![
("Rust".to_owned(), [4, 6, 2]),
("C/C++".to_owned(), [1, 0, 0])
]
);
assert_eq!(
a.not_cached,
vec![("crate-type".to_owned(), 3), ("incremental".to_owned(), 1)]
);
}
#[test]
fn multilevel_sample_becomes_a_table() {
let s = parse(MULTILEVEL).unwrap();
assert_eq!(s.multi_level.len(), 2);
assert_eq!(s.multi_level[1].name, "L1 (s3)");
assert_eq!(s.multi_level[0].hit_ns, 1_500_000_000);
assert_eq!(s.multi_level[1].write_ns, 36_500_000_000);
let extras = extras(&s);
assert_eq!(extras.len(), 1);
assert_eq!(extras[0].title, "Multi-level cache");
assert_eq!(extras[0].rows.len(), 2);
assert_eq!(
extras[0].rows[0].0,
"L0 (disk) \u{2014} Local disk: \"/home/me/.cache/sccache\""
);
assert_eq!(
extras[0].rows[0].1,
"1,500 hits \u{b7} 1,000 misses \u{b7} 1,400 writes, 2 failed \u{b7} backfilled 300 in, 0 out \u{b7} avg hit read 1 ms \u{b7} avg write 2 ms"
);
}
#[test]
fn dist_sample_becomes_a_table() {
let s = parse(DIST).unwrap();
assert_eq!(
s.dist_compiles,
vec![
("10.0.0.11:4226".to_owned(), 402),
("10.0.0.12:4226".to_owned(), 379),
("buildbox.local:4228".to_owned(), 9),
]
);
assert_eq!(s.dist_errors, 7);
let extras = extras(&s);
assert_eq!(extras.len(), 1);
assert_eq!(extras[0].title, "Distributed compiles");
assert_eq!(
extras[0].rows[2],
("buildbox.local:4228".to_owned(), "9".to_owned())
);
assert_eq!(
extras[0].rows[3],
("Errors (re-run locally)".to_owned(), "7".to_owned())
);
}
#[test]
fn only_dist_errors_still_makes_a_table() {
let mut s = parse(DIST).unwrap();
s.dist_compiles.clear();
assert_eq!(
extras(&s)[0].rows,
vec![("Errors (re-run locally)".to_owned(), "7".to_owned())]
);
}
}
+130
View File
@@ -0,0 +1,130 @@
//! Living in systemd: the unit file, and installing or removing it.
use std::path::PathBuf;
use std::process::Command;
use sccache_dash_api::DEFAULT_PORT;
pub const UNIT: &str = "sccache-dash.service";
/// The unit file that runs this program from login on, without opening a browser.
pub fn unit_file(exe: &str, path: &str) -> String {
format!(
"[Unit]\n\
Description=sccache-dash, a dashboard for sccache's cache at http://127.0.0.1:{DEFAULT_PORT}\n\
\n\
[Service]\n\
ExecStart={} --no-open\n\
Environment={}\n\
Restart=on-failure\n\
RestartSec=5\n\
\n\
[Install]\n\
WantedBy=default.target\n",
quote(exe),
quote(&format!("PATH={path}")),
)
}
/// Quotes a value the way systemd unit files read it; `%` would otherwise start a specifier.
fn quote(value: &str) -> String {
format!(
"\"{}\"",
value
.replace('\\', "\\\\")
.replace('"', "\\\"")
.replace('%', "%%")
)
}
fn unit_path() -> Result<PathBuf, String> {
let config = dirs::config_dir()
.ok_or("cannot find the config directory ($XDG_CONFIG_HOME, or ~/.config)")?;
Ok(config.join("systemd").join("user").join(UNIT))
}
fn systemctl(args: &[&str]) -> Result<(), String> {
let output = Command::new("systemctl")
.args(args)
.output()
.map_err(|e| format!("cannot run systemctl: {e}"))?;
if output.status.success() {
return Ok(());
}
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_owned();
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_owned();
Err(format!(
"systemctl {} failed: {}",
args.join(" "),
[stdout, stderr].join(" ").trim()
))
}
/// Writes the unit file for the program as it is running right now, then starts it.
pub fn install() -> Result<(), String> {
let exe =
std::env::current_exe().map_err(|e| format!("cannot find where this program is: {e}"))?;
let path = std::env::var("PATH").unwrap_or_default();
let unit = unit_path()?;
if let Some(dir) = unit.parent() {
std::fs::create_dir_all(dir)
.map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
}
std::fs::write(&unit, unit_file(&exe.to_string_lossy(), &path))
.map_err(|e| format!("cannot write {}: {e}", unit.display()))?;
systemctl(&["--user", "daemon-reload"])?;
systemctl(&["--user", "enable", "--now", UNIT])?;
println!(
"Installed {}. The dashboard is at http://127.0.0.1:{DEFAULT_PORT}",
unit.display()
);
Ok(())
}
/// Stops the service and deletes the unit file.
pub fn uninstall() -> Result<(), String> {
let unit = unit_path()?;
if unit.exists() {
systemctl(&["--user", "disable", "--now", UNIT])?;
std::fs::remove_file(&unit)
.map_err(|e| format!("cannot remove {}: {e}", unit.display()))?;
} else {
println!("{} is not installed; nothing to remove.", unit.display());
}
systemctl(&["--user", "daemon-reload"])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_unit_runs_this_binary_without_a_browser_and_with_the_shell_s_path() {
let unit = unit_file("/home/me/bin/sccache-dash", "/usr/bin:/home/me/.cargo/bin");
assert_eq!(
unit,
"[Unit]\n\
Description=sccache-dash, a dashboard for sccache's cache at http://127.0.0.1:8226\n\
\n\
[Service]\n\
ExecStart=\"/home/me/bin/sccache-dash\" --no-open\n\
Environment=\"PATH=/usr/bin:/home/me/.cargo/bin\"\n\
Restart=on-failure\n\
RestartSec=5\n\
\n\
[Install]\n\
WantedBy=default.target\n"
);
assert!(unit_file("/a b/sccache-dash", "/x")
.contains("ExecStart=\"/a b/sccache-dash\" --no-open\n"));
assert!(
unit_file("/x", "/a%b\"c").contains("Environment=\"PATH=/a%%b\\\"c\"\n"),
"% and quotes cannot change what systemd reads"
);
assert!(
unit_file("relative/sccache-dash", "/x")
.contains("ExecStart=\"relative/sccache-dash\""),
"quoting is the caller's path, verbatim"
);
}
}
File diff suppressed because it is too large. Load diff
+844
View File
@@ -0,0 +1,844 @@
//! The server as seen from a socket, with a stand-in for sccache so that the real one is never touched.
use std::io::{Read, Write};
use std::net::{SocketAddr, TcpStream};
use std::os::unix::fs::PermissionsExt;
use std::path::PathBuf;
use std::sync::Arc;
use std::thread;
use sccache_dash::app::{unix_now, App, Config, Probe, Prober, Task};
use sccache_dash::history::History;
use sccache_dash::stats;
use sccache_dash_api::{Range, Severity, Status, Totals, View};
const LIVE: &str = include_str!("../../../fixtures/live-0.18.0.json");
const ZEROED: &str = "{\"stats\":{\"compile_requests\":0,\"cache_hits\":{\"counts\":{},\"adv_counts\":{}},\"cache_misses\":{\"counts\":{},\"adv_counts\":{}},\"cache_errors\":{\"counts\":{},\"adv_counts\":{}}},\"version\":\"0.18.0\"}";
const NOW: i64 = 1_764_000_000;
/// A script that answers like sccache: it prints a fixture for `--show-stats` and swaps in
/// `ZEROED` when asked to zero the stats. Every call is logged.
struct Fake {
dir: tempfile::TempDir,
script: PathBuf,
log: PathBuf,
history: PathBuf,
}
impl Fake {
fn new() -> Fake {
let dir = tempfile::tempdir().unwrap();
let script = dir.path().join("sccache");
std::fs::write(
&script,
r#"#!/bin/sh
printf '%s\n' "$*" >> "$0.log"
case "$1" in
--version) echo 'sccache 0.18.0' ;;
--zero-stats) cp "$0.zeroed" "$0.out" ;;
--start-server) if [ -e "$0.no-start" ]; then echo "Server startup failed: Address in use" >&2; exit 1; fi; cp "$0.live" "$0.out"; touch "$0.running"; echo started ;;
*) cat "$0.out" ;;
esac
"#,
)
.unwrap();
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
std::fs::write(dir.path().join("sccache.out"), LIVE).unwrap();
std::fs::write(dir.path().join("sccache.live"), LIVE).unwrap();
std::fs::write(dir.path().join("sccache.running"), "").unwrap();
std::fs::write(dir.path().join("sccache.zeroed"), ZEROED).unwrap();
Fake {
log: dir.path().join("sccache.log"),
history: dir.path().join("data").join("history.db"),
dir,
script,
}
}
/// What `--show-stats` prints from now on.
fn answers(&self, text: &str) {
std::fs::write(self.dir.path().join("sccache.out"), text).unwrap();
}
/// The arguments of every call so far, one entry per call.
fn calls(&self) -> Vec<String> {
std::fs::read_to_string(&self.log)
.unwrap_or_default()
.lines()
.map(str::to_owned)
.collect()
}
/// No server running: `--show-stats` then answers with empty counters, as the real one does.
fn down(&self) {
std::fs::remove_file(self.dir.path().join("sccache.running")).unwrap();
self.answers(ZEROED);
}
/// The stand-in for the check on whether sccache's server is listening.
fn probe(&self) -> Prober {
let marker = self.dir.path().join("sccache.running");
Arc::new(move || {
if marker.exists() {
Probe::Running
} else {
Probe::NotRunning
}
})
}
fn config(&self) -> Config {
Config {
sccache: self.script.clone().into(),
history: self.history.clone(),
start_sccache: true,
}
}
}
/// A server on a free port next to an empty history, polled once, answering in the background.
/// The test stands in for the polling task: it holds the history and polls by hand.
fn start(fake: &Fake) -> (Arc<App>, Task, SocketAddr) {
let app = Arc::new(App::with_probe(fake.config(), fake.probe()));
let mut task = Task::memory();
task.poll(&app, NOW);
let server = tiny_http::Server::http("127.0.0.1:0").unwrap();
let addr = server.server_addr().to_ip().unwrap();
let answering = Arc::clone(&app);
thread::spawn(move || sccache_dash::http::answer(server, answering));
(app, task, addr)
}
/// Sends one raw request (`{port}` stands for the server's port) and returns the whole response.
fn send(addr: SocketAddr, request: &str) -> String {
let request = request.replace("{port}", &addr.port().to_string());
let mut stream = TcpStream::connect(addr).unwrap();
stream.write_all(request.as_bytes()).unwrap();
let mut response = String::new();
stream.read_to_string(&mut response).unwrap();
response
}
const GET: &str = " HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n";
/// `POST /api/zero` with the given `Host` and `Origin` headers; returns the status and the response.
fn zero(addr: SocketAddr, host: Option<&str>, origin: Option<&str>) -> (u16, String) {
let mut request = String::from("POST /api/zero HTTP/1.1\r\n");
for (name, value) in [("Host:", host), ("Origin:", origin)] {
if let Some(value) = value {
request.push_str(&format!("{name} {value}\r\n"));
}
}
request.push_str("Content-Length: 0\r\nConnection: close\r\n\r\n");
let response = send(addr, &request);
let code = response
.split_whitespace()
.nth(1)
.and_then(|c| c.parse().ok());
(code.unwrap_or(0), response)
}
#[test]
fn zero_is_refused_for_a_foreign_origin_or_host() {
let fake = Fake::new();
let (app, task, addr) = start(&fake);
// A page anywhere else, in any shape: a bare host, another port, or "null".
for origin in [
"https://evil.example",
"http://127.0.0.1:1",
"http://localhost.evil.example:{port}",
"null",
] {
let (code, response) = zero(addr, Some("127.0.0.1:{port}"), Some(origin));
assert_eq!(
(code, response.contains("refused")),
(403, true),
"Origin {origin}"
);
}
// A host name that merely leads here (DNS rebinding) or is not plainly localhost.
for host in [
"evil.example:{port}",
"127.0.0.1.evil.example:{port}",
"localhost:{port}@evil.example",
"[::1]:{port}",
] {
let (code, _) = zero(addr, Some(host), None);
assert_eq!(code, 403, "Host {host}");
}
let (code, _) = zero(addr, None, None);
assert_eq!(code, 403, "no Host at all");
assert!(
!fake.calls().iter().any(|c| c == "--zero-stats"),
"sccache was never asked to zero: {:?}",
fake.calls()
);
assert_eq!(
task.history.row_count().unwrap(),
0,
"and nothing was written to the history"
);
assert_eq!(
app.lock().tracker.row_base.as_ref().unwrap().totals,
stats::parse(LIVE).unwrap().counters.totals
);
}
#[test]
fn zero_from_the_dashboard_zeroes_sccache_and_keeps_the_history() {
let fake = Fake::new();
let (app, mut task, addr) = start(&fake);
let (code, response) = zero(
addr,
Some("127.0.0.1:{port}"),
Some("http://127.0.0.1:{port}"),
);
assert_eq!(
(code, response.contains("the saved history is kept")),
(200, true),
"{response}"
);
assert_eq!(
zero(addr, Some("localhost:{port}"), None).0,
200,
"no Origin, as from curl"
);
// What the polling task then does, woken by the request: it reads the counters again.
task.poll(&app, unix_now());
let calls = fake.calls();
assert_eq!(calls.iter().filter(|c| *c == "--zero-stats").count(), 2);
assert_eq!(calls.last().unwrap(), "--show-stats --stats-format json");
assert_eq!(
task.history.row_count().unwrap(),
1,
"the history stays, and the zeroing is one more row"
);
assert!(
task.history.last_reset().unwrap().is_some(),
"the zeroing shows in the history as a reset"
);
assert_eq!(
task.history.sums(0, i64::MAX).unwrap(),
Some(stats::Counters::default()),
"nothing has been compiled since"
);
let v = app.view(Range::SinceReset);
assert_eq!(
v.totals,
Totals::default(),
"sccache's counters read zero now"
);
assert!(
v.buckets[0].reset,
"and its chart starts at the reset: {:?}",
v.buckets
);
}
#[test]
fn view_export_and_the_page_answer() {
let fake = Fake::new();
let (_app, _task, addr) = start(&fake);
let response = send(addr, &format!("GET /api/view?range=reset{GET}"));
assert!(
response.starts_with("HTTP/1.1 200 OK\r\n")
&& response.contains("Content-Type: application/json\r\n"),
"{response}"
);
let body = response.split("\r\n\r\n").nth(1).unwrap();
let v: View = serde_json::from_str(body).unwrap();
assert_eq!(v.totals, stats::parse(LIVE).unwrap().counters.totals);
assert_eq!(
(v.range, v.server.status),
(Some(Range::SinceReset), Status::Idle)
);
assert_eq!(
(
v.server.version.as_deref(),
v.server.client_version.as_deref()
),
(Some("0.18.0"), Some("0.18.0"))
);
assert!(v.summary_markdown.starts_with("**sccache, since reset**\n"));
for range in ["1h", "24h", "7d", "30d"] {
let response = send(addr, &format!("GET /api/view?range={range}{GET}"));
let v: View = serde_json::from_str(response.split("\r\n\r\n").nth(1).unwrap()).unwrap();
assert_eq!(v.buckets.len(), 120, "{range}");
}
let response = send(addr, &format!("GET /api/export{GET}"));
assert!(
response.contains("Content-Type: application/json\r\n"),
"{response}"
);
assert!(
response.contains(&format!(
"Content-Disposition: attachment; filename=\"sccache-stats-{}.json\"",
sccache_dash::pretty::stamp(NOW)
)),
"{response}"
);
assert!(response.ends_with(LIVE), "exactly as sccache printed it");
let response = send(addr, &format!("GET /{GET}"));
assert!(
response.starts_with("HTTP/1.1 200 OK\r\n")
&& response.contains("Content-Type: text/html; charset=utf-8\r\n"),
"{response}"
);
assert!(send(addr, &format!("HEAD /{GET}")).starts_with("HTTP/1.1 200 OK\r\n"));
assert!(send(addr, &format!("GET /api/view?range=bogus{GET}")).starts_with("HTTP/1.1 400"));
assert!(
send(addr, &format!("GET /api/view{GET}")).starts_with("HTTP/1.1 400"),
"no range at all"
);
assert!(send(addr, &format!("GET /../Cargo.toml{GET}")).starts_with("HTTP/1.1 404"));
assert!(send(addr, &format!("GET /no-such-file.wasm{GET}")).starts_with("HTTP/1.1 404"));
assert!(send(addr, &format!("PUT /api/zero{GET}")).starts_with("HTTP/1.1 405"));
}
#[test]
fn rows_are_saved_when_counters_change_and_at_most_once_a_minute() {
let fake = Fake::new();
let app = App::with_probe(fake.config(), fake.probe());
let mut task = Task::memory();
task.poll(&app, NOW);
assert_eq!(
task.history.row_count().unwrap(),
0,
"the first reading is a baseline, not a row"
);
task.poll(&app, NOW + 10);
assert_eq!(task.history.row_count().unwrap(), 0, "nothing changed");
fake.answers(&LIVE.replace("\"compile_requests\":7351", "\"compile_requests\":7352"));
task.poll(&app, NOW + 30);
assert_eq!(
task.history.row_count().unwrap(),
0,
"changed, but less than a minute after the baseline"
);
task.poll(&app, NOW + 60);
assert_eq!(
task.history.row_count().unwrap(),
1,
"a minute on, the change is saved"
);
assert_eq!(
task.history
.sums(0, i64::MAX)
.unwrap()
.unwrap()
.totals
.requests,
1
);
assert_eq!(
task.history.last_reset().unwrap(),
None,
"a change is not a reset"
);
task.poll(&app, NOW + 700);
assert_eq!(
task.history.row_count().unwrap(),
1,
"unchanged: nothing more is saved, however long the quiet lasts"
);
assert!(
task.history.build_obs_stamp().unwrap() == (0, 0),
"and with no misses there is no build observation"
);
assert_eq!(app.lock().views.len(), 5, "every poll makes the five views");
}
#[test]
fn the_history_survives_a_restart_in_its_file() {
let fake = Fake::new();
let app = App::new(fake.config());
let path = fake.history.clone();
// The first run sees the baseline and a change, then stops.
let history = History::open(&path).unwrap();
history.prune(NOW).unwrap();
let mut tracker = history.tracker();
assert_eq!(tracker, Default::default(), "a new file remembers nothing");
let (a, b) = (
stats::parse(LIVE).unwrap().counters,
stats::parse(LIVE).unwrap().counters,
);
history.record(&mut tracker, &a, NOW).unwrap();
history.record(&mut tracker, &b, NOW + 10).unwrap();
drop(history);
// The next run picks up where it stopped: the difference is not lost or counted twice.
let history = History::open(&path).unwrap();
let mut tracker = history.tracker();
assert_eq!(
tracker.row_base,
Some(a.clone()),
"the totals at the baseline"
);
let mut c = b.clone();
c.totals.requests += 5;
history.record(&mut tracker, &c, NOW + 70).unwrap();
assert_eq!(history.row_count().unwrap(), 1);
assert_eq!(
history.sums(0, i64::MAX).unwrap().unwrap().totals.requests,
5
);
assert_eq!(
app.view(Range::Day).range,
Some(Range::Day),
"and a server that has not polled yet answers with an empty view"
);
}
#[test]
fn old_rows_are_deleted_at_startup() {
let fake = Fake::new();
// A real file, as the service has, in WAL mode.
let history = History::open(&fake.history).unwrap();
let mut tracker = Default::default();
let day = 86_400;
let mut c = stats::Counters::default();
for (t, requests) in [
(NOW - 33 * day, 1),
(NOW - 31 * day, 2),
(NOW - 30 * day + 3600, 3),
(NOW - 3600, 4),
(NOW, 5),
] {
c.totals.requests = requests;
history.record(&mut tracker, &c, t).unwrap();
}
assert_eq!(
history.row_count().unwrap(),
4,
"rows carry differences; the first reading is the baseline"
);
assert_eq!(
history.prune(NOW).unwrap(),
1,
"the one row older than 30 days"
);
assert_eq!(history.row_count().unwrap(), 3);
assert_eq!(
history.first_row().unwrap(),
Some(NOW - 30 * day + 3600),
"the oldest row left"
);
assert_eq!(history.prune(NOW).unwrap(), 0, "nothing more to delete");
assert!(
fake.history.with_extension("db-wal").exists()
|| fake.history.with_extension("db-shm").exists(),
"WAL mode is on"
);
}
#[test]
fn a_missing_sccache_server_is_left_alone_unless_starting_was_asked_for() {
let fake = Fake::new();
fake.down();
let app = App::with_probe(
Config {
start_sccache: false,
..fake.config()
},
fake.probe(),
);
let mut task = Task::memory();
task.poll(&app, NOW);
task.poll(&app, NOW + 120);
let calls = fake.calls();
assert!(!calls.iter().any(|c| c == "--start-server"), "{calls:?}");
assert!(app
.lock()
.error
.as_deref()
.is_some_and(|e| e.contains("your next build starts it")));
}
#[test]
fn a_missing_sccache_server_is_started_once_then_read() {
let fake = Fake::new();
fake.down();
let app = App::with_probe(fake.config(), fake.probe());
let mut task = Task::memory();
task.poll(&app, NOW);
let calls = fake.calls();
assert_eq!(
calls.iter().filter(|c| *c == "--start-server").count(),
1,
"{calls:?}"
);
assert_eq!(
calls.last().unwrap(),
"--show-stats --stats-format json",
"the counters are read again after starting"
);
let v = app.view(Range::SinceReset);
assert_eq!(v.server.status, Status::Idle, "{:?}", v.server.error);
assert_eq!(
v.totals,
stats::parse(LIVE).unwrap().counters.totals,
"the started server's counters, not the empty ones"
);
task.poll(&app, NOW + 10);
assert_eq!(
fake.calls()
.iter()
.filter(|c| *c == "--start-server")
.count(),
1,
"not started again while it is running"
);
}
#[test]
fn a_server_that_will_not_start_is_reported_and_not_retried_for_a_minute() {
let fake = Fake::new();
fake.down();
std::fs::write(fake.dir.path().join("sccache.no-start"), "").unwrap();
let app = App::with_probe(fake.config(), fake.probe());
let mut task = Task::memory();
for at in [NOW, NOW + 10, NOW + 50] {
task.poll(&app, at);
let v = app.view(Range::Day);
assert_eq!(v.server.status, Status::NotRunning, "polled at {at}");
assert!(
v.server
.error
.as_deref()
.is_some_and(|e| e.contains("`sccache --start-server` failed")),
"{:?}",
v.server.error
);
assert!(
v.problems
.iter()
.any(|p| p.severity == Severity::Error && p.title == "sccache is not running"),
"{:?}",
v.problems
);
}
assert_eq!(
fake.calls()
.iter()
.filter(|c| *c == "--start-server")
.count(),
1,
"tried once"
);
task.poll(&app, NOW + 60);
assert_eq!(
fake.calls()
.iter()
.filter(|c| *c == "--start-server")
.count(),
2,
"and again a minute later"
);
// Meanwhile the server came up by itself (a compile started it): no more error. Its counters
// differ from the empty ones, so that counts as compiles having arrived.
std::fs::write(fake.dir.path().join("sccache.running"), "").unwrap();
fake.answers(LIVE);
task.poll(&app, NOW + 70);
assert_eq!(app.view(Range::Day).server.status, Status::Running);
assert_eq!(app.view(Range::Day).server.error, None);
}
/// The real output with `more` more Rust builds in it: that many more requests, misses and compiles.
fn with_more_rust_builds(more: u64) -> String {
let text = LIVE.replace(
"\"compile_requests\":7351",
&format!("\"compile_requests\":{}", 7351 + more),
);
let text = text.replace("\"Rust\":3256", &format!("\"Rust\":{}", 3256 + more));
let text = text.replace("\"rust\":3256", &format!("\"rust\":{}", 3256 + more));
let text = text.replace(
"\"compilations\":3256",
&format!("\"compilations\":{}", 3256 + more),
);
let text = text.replace(
"\"cache_writes\":3256",
&format!("\"cache_writes\":{}", 3256 + more),
);
text.replace(
"\"compiler_write_duration\":{\"secs\":25343",
&format!(
"\"compiler_write_duration\":{{\"secs\":{}",
25343 + 8 * more
),
)
}
#[test]
fn the_bootstrap_is_not_redrawn_on_every_poll_of_a_build_in_flight() {
let fake = Fake::new();
let app = App::with_probe(fake.config(), fake.probe());
let mut task = Task::memory();
let rust_builds = |app: &App| {
app.view(Range::Day)
.build_times
.first()
.map_or(0, |t| t.compiles)
};
task.poll(&app, NOW);
assert_eq!(rust_builds(&app), 0, "nothing seen yet");
// A build adds one Rust build between every pair of polls. Each is stored at once. The first
// is drawn at the next poll (the empty draw before it started no wait); the rest wait for
// the one-minute beat that began with that draw.
for step in 1..7u64 {
fake.answers(&with_more_rust_builds(step));
task.poll(&app, NOW + (step as i64) * 10);
assert_eq!(
task.history.build_obs_stamp().unwrap().0,
step as i64,
"observation {step} is stored at once"
);
assert_eq!(
rust_builds(&app),
1,
"the first draw stands for the minute (step {step})"
);
}
fake.answers(&with_more_rust_builds(7));
task.poll(&app, NOW + 70);
assert_eq!(
rust_builds(&app),
7,
"a minute after the last draw, everything seen so far is drawn in"
);
fake.answers(&with_more_rust_builds(8));
task.poll(&app, NOW + 80);
assert_eq!(
rust_builds(&app),
7,
"and it stands again until the next beat"
);
}
#[test]
fn a_full_history_costs_few_rows_on_the_second_poll() {
// Thirty days with a row every minute: the most there can ever be. Two languages miss most
// minutes, so only one minute in ten gives a build observation.
let fake = Fake::new();
let app = App::with_probe(fake.config(), fake.probe());
let mut task = Task::memory();
let day = 86_400;
let mut c = stats::Counters::default();
let mut readings = Vec::new();
for step in 0..43_200i64 {
let (rust, cxx) = if step % 10 == 0 { (2, 0) } else { (1, 1) };
c.totals.requests += 10;
c.totals.executed += 8;
c.totals.hits += 6;
c.totals.misses += rust + cxx;
c.totals.not_cacheable += 2;
c.totals.cache_writes += rust + cxx;
c.compilations += rust + cxx;
c.ns = [
c.ns[0] + 6 * 10_000_000,
c.ns[1] + (rust + cxx) * 1_000_000_000,
c.ns[2] + (rust + cxx) * 8_000_000_000,
];
c.langs = vec![
("Assembler".to_owned(), [2, 0, 0]),
("C/C++".to_owned(), [4, cxx, 0]),
("Rust".to_owned(), [0, rust, 0]),
];
readings.push((NOW - 30 * day + step * 60, c.clone()));
}
task.history.fill(&readings).unwrap();
assert_eq!(
task.history.row_count().unwrap(),
43_199,
"the first reading is the baseline"
);
let observations = task.history.build_obs_stamp().unwrap().0;
assert_eq!(
observations, 4_319,
"one for every tenth minute after the baseline"
);
task.poll(&app, NOW);
let first = app.lock().views_rows;
task.poll(&app, NOW + 10);
let second = app.lock().views_rows;
eprintln!("rows handed out: first poll {first} (reading {observations} build observations once), second poll {second}");
assert!(
first >= observations as usize,
"the first poll reads every observation once"
);
assert!(second < 3_000, "the second poll handed out {second} rows");
let v = app.view(Range::Day);
assert_eq!(v.buckets.len(), 120);
}
/// What sccache prints after `k` more rounds of work: every round adds 3 requests, 2 hits and
/// 1 Rust miss that took 5 s to compile.
fn after_rounds(k: u64) -> String {
let mut v: serde_json::Value = serde_json::from_str(LIVE).unwrap();
let s = &mut v["stats"];
let add = |s: &mut serde_json::Value, key: &str, n: u64| {
s[key] = (s[key].as_u64().unwrap() + n).into();
};
add(s, "compile_requests", 3 * k);
add(s, "requests_executed", k);
add(s, "cache_writes", k);
add(s, "compilations", k);
s["cache_hits"]["counts"]["Rust"] = (229 + 2 * k).into();
s["cache_misses"]["counts"]["Rust"] = (3256 + k).into();
let secs = 25343 + 5 * k;
s["compiler_write_duration"]["secs"] = secs.into();
v.to_string()
}
/// Polls once a `step` seconds from `from` to `to`, the counters rising a round each time.
fn run_polls(
fake: &Fake,
app: &App,
task: &mut Task,
rounds: &mut u64,
span: (i64, i64),
step: i64,
) {
let mut t = span.0;
while t <= span.1 {
fake.answers(&after_rounds(*rounds));
task.poll(app, t);
*rounds += 1;
t += step;
}
}
#[test]
fn a_restart_loses_nothing_and_counts_nothing_twice() {
let fake = Fake::new();
let mut rounds = 0;
let app = App::with_probe(fake.config(), fake.probe());
let mut task = Task::open(&fake.history, NOW).unwrap();
// Five minutes of polls, every ten seconds, with work in each; the last 30 s after a row.
run_polls(&fake, &app, &mut task, &mut rounds, (NOW, NOW + 330), 10);
let before = app.view(Range::Day);
assert!(before.totals.requests > 0, "{:?}", before.totals);
assert!(
task.history.row_count().unwrap() >= 4,
"a row a minute on disk while it runs, not at the end: {}",
task.history.row_count().unwrap()
);
drop(task);
drop(app);
// The restart: a new process opens the same file and polls once, ten seconds later, with
// the same counters sccache had (no work in between).
let app = App::with_probe(fake.config(), fake.probe());
let mut task = Task::open(&fake.history, NOW + 340).unwrap();
rounds -= 1;
run_polls(
&fake,
&app,
&mut task,
&mut rounds,
(NOW + 340, NOW + 340),
10,
);
let after = app.view(Range::Day);
assert_eq!(
(after.totals, after.previous),
(before.totals, before.previous),
"a view's totals are the same just before and just after a restart"
);
}
#[test]
fn a_restart_counts_the_work_done_while_it_was_down() {
let fake = Fake::new();
let mut rounds = 0;
let app = App::with_probe(fake.config(), fake.probe());
let mut task = Task::open(&fake.history, NOW).unwrap();
run_polls(&fake, &app, &mut task, &mut rounds, (NOW, NOW + 200), 10);
let before = app.view(Range::Day).totals.requests;
drop(task);
drop(app);
// sccache went on working for 4 rounds while sccache-dash was stopped.
rounds += 3;
let app = App::with_probe(fake.config(), fake.probe());
let mut task = Task::open(&fake.history, NOW + 260).unwrap();
run_polls(
&fake,
&app,
&mut task,
&mut rounds,
(NOW + 260, NOW + 260),
10,
);
assert_eq!(
app.view(Range::Day).totals.requests,
before + 4 * 3,
"the difference since the last poll before the stop is counted, once"
);
}
#[test]
fn build_times_show_within_a_minute_of_the_observations() {
let fake = Fake::new();
let mut rounds = 0;
let app = App::with_probe(fake.config(), fake.probe());
let mut task = Task::open(&fake.history, NOW).unwrap();
// The first poll draws the (empty) bootstrap; the observations come after it.
run_polls(&fake, &app, &mut task, &mut rounds, (NOW, NOW + 600), 10);
let shown = |t: &Task| t.history.build_obs_stamp().unwrap().0;
assert!(shown(&task) >= 50, "observations were recorded");
let times = app.view(Range::Day).build_times;
assert_eq!(times.len(), 1, "Rust has a histogram after ten minutes");
// Stop polling for work: after one more poll a minute on, the newest are in too.
let seen = times[0].compiles;
run_polls(
&fake,
&app,
&mut task,
&mut rounds,
(NOW + 610, NOW + 680),
10,
);
let now = app.view(Range::Day).build_times[0].compiles;
assert!(now > seen, "the histogram keeps up: {seen} then {now}");
}
#[test]
fn the_first_observations_show_at_the_next_poll_not_a_minute_later() {
let fake = Fake::new();
let mut rounds = 0;
let app = App::with_probe(fake.config(), fake.probe());
let mut task = Task::open(&fake.history, NOW).unwrap();
// The first poll draws nothing: there is nothing to draw, and that must not start the
// minute's wait for the first real observations.
run_polls(&fake, &app, &mut task, &mut rounds, (NOW, NOW + 30), 10);
assert!(task.history.build_obs_stamp().unwrap().0 >= 3);
assert_eq!(
app.view(Range::Day).build_times.len(),
1,
"seconds after the first observation, not a minute"
);
}
+166 -74
View File
@@ -140,87 +140,135 @@ pub struct Saved {
/// may not hold (cached compiles may be larger or smaller than the typical /// may not hold (cached compiles may be larger or smaller than the typical
/// miss); nor does it cover errors in `hits` or `hit_read_seconds`, or any /// miss); nor does it cover errors in `hits` or `hit_read_seconds`, or any
/// drift in build times over time. /// drift in build times over time.
///
/// Several sets of hits over the same observations (one per range, say) should
/// go through [`Resampled`] instead: it draws the bootstrap once.
pub fn time_saved(langs: &[LanguageHits], hit_read_seconds: f64) -> Saved { pub fn time_saved(langs: &[LanguageHits], hit_read_seconds: f64) -> Saved {
let hit_read = if hit_read_seconds.is_finite() && hit_read_seconds > 0.0 { let obs: Vec<&[Observation]> = langs.iter().map(|l| l.obs).collect();
hit_read_seconds Resampled::new(&obs).time_saved(langs, hit_read_seconds)
} else { }
0.0
}; /// The bootstrap drawn once for a set of languages, so that the time saved for
let mut left_out = 0u64; /// several sets of hits can be worked out from the same draws: the build times
// (hits, (compiles, seconds) pairs) for counted languages. /// seen are the same for every set, only the hits differ.
let mut counted: Vec<(f64, Vec<(f64, f64)>)> = Vec::new(); #[derive(Debug)]
for l in langs { pub struct Resampled {
let data: Vec<(f64, f64)> = l /// Per replicate, per language: the resampled (compiles, seconds). A language
.obs /// with too little data has zeros there and is left out.
.iter() replicates: Vec<Vec<(f64, f64)>>,
.filter(|o| usable(o)) /// Whether each language has enough observations to be counted.
.map(|o| (o.compiles as f64, o.seconds)) counted: Vec<bool>,
.collect(); }
if data.len() < MIN_OBSERVATIONS {
left_out = left_out.saturating_add(l.hits); impl Resampled {
/// Resamples every language that has [`MIN_OBSERVATIONS`] usable observations.
pub fn new(obs_per_language: &[&[Observation]]) -> Resampled {
let data: Vec<Vec<(f64, f64)>> = obs_per_language.iter().map(|obs| points(obs)).collect();
let counted: Vec<bool> = data.iter().map(|d| d.len() >= MIN_OBSERVATIONS).collect();
let mut rng = Rng(SEED);
let mut replicates = Vec::with_capacity(REPLICATES);
for _ in 0..REPLICATES {
replicates.push(data.iter().map(|d| resample(d, &mut rng)).collect());
}
Resampled {
replicates,
counted,
}
}
/// [`time_saved`] for one set of hits, from the draws already made. `langs`
/// must give each language in the order its observations were given to
/// [`new`](Resampled::new); the slices need not be the same ones.
pub fn time_saved(&self, langs: &[LanguageHits<'_>], hit_read_seconds: f64) -> Saved {
let hit_read = if hit_read_seconds.is_finite() && hit_read_seconds > 0.0 {
hit_read_seconds
} else { } else {
counted.push((l.hits as f64, data)); 0.0
}
}
let saving = |hits: f64, c: f64, s: f64| hits * (s / c - hit_read).max(0.0);
let seconds: f64 = counted
.iter()
.map(|(h, d)| {
let (c, s) = sums(d.iter());
saving(*h, c, s)
})
.sum();
if counted.is_empty() {
return Saved {
seconds,
interval_90: None,
hits_left_out: left_out,
}; };
} let saving = |hits: f64, c: f64, s: f64| hits * (s / c - hit_read).max(0.0);
let counted = |i: usize| langs.get(i).is_some_and(|_| self.counted[i]);
let mut rng = Rng(SEED); let mut left_out = 0u64;
let mut totals: Vec<f64> = Vec::with_capacity(REPLICATES); let seconds: f64 = langs
for _ in 0..REPLICATES { .iter()
let mut total = 0.0; .enumerate()
for (h, d) in &counted { .filter(|(i, _)| counted(*i))
if *h == 0.0 { .map(|(_, l)| {
continue; let d = points(l.obs);
let (c, s) = sums(d.iter());
saving(l.hits as f64, c, s)
})
.sum();
for (i, l) in langs.iter().enumerate() {
if !counted(i) {
left_out = left_out.saturating_add(l.hits);
} }
let n = d.len() as u64;
// Two 32-bit draws per 64-bit output; (r * n) >> 32 is in 0..n.
// Two independent accumulator pairs keep the adds from chaining.
let pick = |r: u64| d[((r * n) >> 32) as usize];
let (mut c, mut s) = (0.0, 0.0);
let (mut c2, mut s2) = (0.0, 0.0);
for _ in 0..d.len() / 2 {
let x = rng.next();
let (dc, ds) = pick(x >> 32);
let (ec, es) = pick(x & 0xFFFF_FFFF);
c += dc;
s += ds;
c2 += ec;
s2 += es;
}
if d.len() % 2 == 1 {
let (dc, ds) = pick(rng.next() >> 32);
c += dc;
s += ds;
}
let (c, s) = (c + c2, s + s2);
total += saving(*h, c, s);
} }
totals.push(total); if langs.is_empty() || !self.counted.iter().take(langs.len()).any(|c| *c) {
return Saved {
seconds,
interval_90: None,
hits_left_out: left_out,
};
}
let mut totals: Vec<f64> = self
.replicates
.iter()
.map(|replicate| {
langs
.iter()
.zip(replicate)
.enumerate()
.filter(|(i, _)| counted(*i))
.map(|(_, (l, (c, s)))| saving(l.hits as f64, *c, *s))
.sum()
})
.collect();
totals.sort_unstable_by(|a, b| a.total_cmp(b));
let lo = totals[REPLICATES / 20].min(seconds);
let hi = totals[REPLICATES - REPLICATES / 20 - 1].max(seconds);
Saved {
seconds,
interval_90: Some((lo, hi)),
hits_left_out: left_out,
}
} }
totals.sort_unstable_by(|a, b| a.total_cmp(b)); }
let lo = totals[REPLICATES / 20].min(seconds);
let hi = totals[REPLICATES - REPLICATES / 20 - 1].max(seconds); /// The usable observations of a language as (compiles, seconds).
Saved { fn points(obs: &[Observation]) -> Vec<(f64, f64)> {
seconds, obs.iter()
interval_90: Some((lo, hi)), .filter(|o| usable(o))
hits_left_out: left_out, .map(|o| (o.compiles as f64, o.seconds))
.collect()
}
/// One bootstrap replicate of a language: its observations drawn with replacement, summed.
/// A language with too little data draws nothing.
fn resample(data: &[(f64, f64)], rng: &mut Rng) -> (f64, f64) {
if data.len() < MIN_OBSERVATIONS {
return (0.0, 0.0);
} }
let n = data.len() as u64;
// Two 32-bit draws per 64-bit output; (r * n) >> 32 is in 0..n.
// Two independent accumulator pairs keep the adds from chaining.
let pick = |r: u64| data[((r * n) >> 32) as usize];
let (mut c, mut s) = (0.0, 0.0);
let (mut c2, mut s2) = (0.0, 0.0);
for _ in 0..data.len() / 2 {
let x = rng.next();
let (dc, ds) = pick(x >> 32);
let (ec, es) = pick(x & 0xFFFF_FFFF);
c += dc;
s += ds;
c2 += ec;
s2 += es;
}
if data.len() % 2 == 1 {
let (dc, ds) = pick(rng.next() >> 32);
c += dc;
s += ds;
}
(c + c2, s + s2)
} }
fn sums<'a>(it: impl Iterator<Item = &'a (f64, f64)>) -> (f64, f64) { fn sums<'a>(it: impl Iterator<Item = &'a (f64, f64)>) -> (f64, f64) {
@@ -466,3 +514,47 @@ mod tests {
assert_eq!(s.interval_90, Some((0.0, 0.0))); assert_eq!(s.interval_90, Some((0.0, 0.0)));
} }
} }
#[cfg(test)]
mod resampled {
use super::*;
fn o(compiles: u64, seconds: f64) -> Observation {
Observation { compiles, seconds }
}
#[test]
fn several_hit_sets_from_one_draw_each_match_the_one_shot_call() {
let rust: Vec<Observation> = (0..40).map(|i| o(1, 4.0 + (i % 7) as f64)).collect();
let c: Vec<Observation> = (0..30).map(|i| o(1, 0.2 + 0.01 * (i % 5) as f64)).collect();
let tiny: Vec<Observation> = (0..3).map(|_| o(1, 9.0)).collect();
let draws = Resampled::new(&[&rust, &c, &tiny]);
for (rh, ch, th) in [(120, 40, 5), (0, 40, 5), (120, 0, 0), (1, 1, 1)] {
let langs = [
LanguageHits {
hits: rh,
obs: &rust,
},
LanguageHits { hits: ch, obs: &c },
LanguageHits {
hits: th,
obs: &tiny,
},
];
let once = time_saved(&langs, 0.01);
let again = draws.time_saved(&langs, 0.01);
assert_eq!(once.seconds, again.seconds, "{rh}/{ch}/{th}");
assert_eq!(once.hits_left_out, again.hits_left_out, "{rh}/{ch}/{th}");
assert_eq!(
again.hits_left_out, th,
"a language with three observations is left out"
);
let (lo, hi) = again.interval_90.expect("two languages have enough data");
assert!(
lo <= again.seconds && again.seconds <= hi,
"{rh}/{ch}/{th}: {lo} <= {} <= {hi}",
again.seconds
);
}
}
}
+33
View File
@@ -0,0 +1,33 @@
[package]
name = "sccache-dash-ui"
description = "Dashboard page for sccache-dash"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
sccache-dash-api = { path = "../api" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
# The page is drawn with eframe in the browser for now. A native window would
# open the same `Dashboard`, and needs eframe here with its x11 and wayland features.
[target.'cfg(target_arch = "wasm32")'.dependencies]
eframe = { version = "0.37", default-features = false, features = [
"default_fonts",
"glow",
"persistence",
] }
egui_plot = "0.38"
ehttp = "0.7"
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
js-sys = "0.3"
web-sys = { version = "0.3", features = [
"Document",
"Element",
"HtmlAnchorElement",
"HtmlCanvasElement",
"Window",
] }
+92
View File
@@ -0,0 +1,92 @@
Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION AND CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+93
View File
@@ -0,0 +1,93 @@
Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
+39
View File
@@ -0,0 +1,39 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="color-scheme" content="dark light" />
<title>sccache dash</title>
<!-- A gauge in the page's own colours. -->
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 32 32%22%3E%3Crect width=%2232%22 height=%2232%22 rx=%227%22 fill=%22%23161a22%22/%3E%3Cpath d=%22M6 22a10 10 0 0 1 20 0%22 fill=%22none%22 stroke=%22%233a4254%22 stroke-width=%224%22 stroke-linecap=%22round%22/%3E%3Cpath d=%22M6 22a10 10 0 0 1 15-8.66%22 fill=%22none%22 stroke=%22%234cc38a%22 stroke-width=%224%22 stroke-linecap=%22round%22/%3E%3Cpath d=%22M16 22l6-8%22 stroke=%22%23e6e9ef%22 stroke-width=%222.5%22 stroke-linecap=%22round%22/%3E%3Ccircle cx=%2216%22 cy=%2222%22 r=%222.5%22 fill=%22%23e6e9ef%22/%3E%3C/svg%3E" />
<link data-trunk rel="rust" data-bin="sccache-dash-ui" />
<style>
/* The page is one canvas that fills the window and scrolls inside itself. */
html,
body {
height: 100%;
height: 100dvh;
margin: 0;
overflow: hidden;
/* The page colour of each theme (crates/ui/src/theme.rs), so nothing flashes while the page loads. */
background: #0e1116;
}
@media (prefers-color-scheme: light) {
html,
body {
background: #f5f6f8;
}
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
</style>
</head>
<body>
<canvas id="the_canvas_id"></canvas>
</body>
</html>
+936
View File
@@ -0,0 +1,936 @@
//! The dashboard: what it remembers, how it fetches, and the top of the page.
use std::time::Duration;
use eframe::egui;
use sccache_dash_api::{Range, View};
use crate::disclosure;
use crate::fmt;
use crate::theme;
use crate::{cards, extras, net, overtime, problems, raw, speed, style, where_went};
/// Refresh intervals offered, in seconds; zero means off.
const REFRESH_CHOICES: [u64; 4] = [0, 5, 10, 30];
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
enum ThemeChoice {
/// Follow the browser's own light or dark setting.
Auto,
Light,
Dark,
}
impl ThemeChoice {
const ALL: [Self; 3] = [Self::Auto, Self::Light, Self::Dark];
fn name(self) -> &'static str {
match self {
Self::Auto => "Auto",
Self::Light => "Light",
Self::Dark => "Dark",
}
}
fn preference(self) -> egui::ThemePreference {
match self {
Self::Auto => egui::ThemePreference::System,
Self::Light => egui::ThemePreference::Light,
Self::Dark => egui::ThemePreference::Dark,
}
}
}
/// What a request in flight is for.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Ask {
View,
Zero,
}
/// The whole page. It draws one `View` at a time and keeps the last one on
/// screen until the next arrives.
pub struct Dashboard {
range: Range,
refresh_secs: u64,
theme: ThemeChoice,
view: Option<View>,
pending: Option<(Ask, net::Answer)>,
/// Why the last request failed, if it did.
error: Option<String>,
/// Page time, in seconds, when the last view was asked for.
sent_at: Option<f64>,
/// Languages unticked in the "Over time" filter.
hidden_languages: Vec<String>,
/// Whether the "Zero stats" question is open.
asking_zero: bool,
/// A short message for the controls row, and the page time it goes away.
note: Option<(String, f64)>,
/// Set when the range, refresh interval or theme changed and should be remembered.
settings_changed: bool,
}
impl Dashboard {
pub fn new(cc: &eframe::CreationContext<'_>) -> Self {
let storage = cc.storage;
let dashboard = Self {
range: remembered(storage, "range").unwrap_or(Range::Day),
refresh_secs: remembered(storage, "refresh").unwrap_or(10),
theme: remembered(storage, "theme").unwrap_or(ThemeChoice::Auto),
view: None,
pending: None,
error: None,
sent_at: None,
hidden_languages: Vec::new(),
asking_zero: false,
note: None,
settings_changed: false,
};
let ctx = &cc.egui_ctx;
ctx.set_theme(dashboard.theme.preference());
theme::install(ctx);
dashboard
}
fn now(ctx: &egui::Context) -> f64 {
ctx.input(|input| input.time)
}
/// Send a request, replacing any request still in flight.
fn send(&mut self, ctx: &egui::Context, ask: Ask) {
if ask == Ask::View {
self.sent_at = Some(Self::now(ctx));
}
let request = match ask {
Ask::View => net::view(self.range),
Ask::Zero => net::zero(),
};
self.pending = Some((ask, net::Answer::send(request, ctx)));
}
/// Pick up the answer to the request in flight, if it has arrived.
fn collect(&mut self, ctx: &egui::Context, now: f64) {
if self.note.as_ref().is_some_and(|(_, until)| *until <= now) {
self.note = None;
}
let Some(answer) = self
.pending
.as_ref()
.and_then(|(_, answer)| answer.take())
else {
return;
};
let Some((ask, _)) = self.pending.take() else {
return;
};
match ask {
Ask::View => match net::view_from(answer) {
Ok(view) => {
self.view = Some(view);
self.error = None;
}
Err(error) => self.error = Some(error),
},
Ask::Zero => match net::accepted(answer) {
Ok(()) => {
self.flash("Stats zeroed", now);
self.send(ctx, Ask::View);
}
Err(error) => self.error = Some(format!("The stats could not be zeroed: {error}")),
},
}
}
/// Keep asking for a new view at the chosen interval.
fn tick(&mut self, ctx: &egui::Context, now: f64) {
if self.pending.is_some() {
return;
}
let Some(sent_at) = self.sent_at else {
self.send(ctx, Ask::View);
return;
};
if self.refresh_secs == 0 {
return;
}
let every = self.refresh_secs as f64;
let since = now - sent_at;
if since >= every {
self.send(ctx, Ask::View);
} else {
ctx.request_repaint_after(Duration::from_secs_f64((every - since).max(0.05)));
}
}
fn flash(&mut self, text: impl Into<String>, now: f64) {
self.note = Some((text.into(), now + 4.0));
}
}
impl eframe::App for Dashboard {
/// Runs before every frame, also while the window is hidden: pick up answers and keep asking.
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
let now = Self::now(ctx);
self.collect(ctx, now);
self.tick(ctx, now);
}
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
// The whole window in the page colour first: the toolbar sits outside the
// scrolling panel, and the browser's own canvas colour must never show.
ui.painter()
.rect_filled(ui.max_rect(), 0.0, theme::ctx(ui.ctx()).page);
controls(self, ui);
if let (Some(view), Some(error)) = (&self.view, &self.error) {
lost_contact(
ui.ctx(),
error,
view.generated_at,
ui.available_rect_before_wrap().width(),
);
}
egui::CentralPanel::default()
.frame(
egui::Frame::NONE
.fill(theme::ctx(ui.ctx()).page)
.inner_margin(egui::Margin::symmetric(
theme::space::PAGE_MARGIN as i8,
theme::space::PAGE_MARGIN as i8,
)),
)
.show(ui, |ui| {
egui::ScrollArea::vertical()
.auto_shrink([false; 2])
.show(ui, |ui| {
let Self {
range,
view,
hidden_languages,
..
} = self;
match view {
None => waiting(ui, self.error.as_deref(), self.refresh_secs),
Some(view) => page(ui, view, *range, hidden_languages),
}
});
});
if self.asking_zero {
zero_question(self, ui.ctx());
}
if self.settings_changed {
if let Some(storage) = frame.storage_mut() {
remember(self, storage);
}
self.settings_changed = false;
}
}
/// Remember the range, refresh interval and theme when the page is closed.
fn save(&mut self, storage: &mut dyn eframe::Storage) {
remember(self, storage);
}
}
/// Put the range, refresh interval and theme into the storage eframe keeps between visits.
fn remember(dashboard: &Dashboard, storage: &mut dyn eframe::Storage) {
eframe::set_value(storage, "range", &dashboard.range);
eframe::set_value(storage, "refresh", &dashboard.refresh_secs);
eframe::set_value(storage, "theme", &dashboard.theme);
}
fn remembered<T: serde::de::DeserializeOwned>(
storage: Option<&dyn eframe::Storage>,
key: &str,
) -> Option<T> {
storage.and_then(|storage| eframe::get_value(storage, key))
}
fn theme_labels() -> [&'static str; 3] {
ThemeChoice::ALL.map(|theme| theme.name())
}
/// The wordmark at the left of the top bar.
fn wordmark(ui: &mut egui::Ui) {
ui.add(egui::Label::new(
egui::RichText::new("sccache dash")
.font(theme::number_font(15.0))
.color(theme::ui(ui).text),
));
}
fn wordmark_width(ui: &egui::Ui) -> f32 {
style::text_width(ui, "sccache dash", theme::number_font(15.0))
}
/// About how wide the row of actions is, from the width of its labels.
fn actions_width(ui: &egui::Ui) -> f32 {
let medium = theme::medium(theme::px::BODY);
let label = |text: &str| style::text_width(ui, text, medium.clone()) + 18.0;
let gaps = theme::space::TOOL_GAP;
label(&fmt::refresh_label(30)) + 20.0 + label("Refresh")
+ theme_labels().iter().map(|text| style::text_width(ui, text, medium.clone()) + 2.0 * theme::space::CONTROL_PAD).sum::<f32>()
+ label("Copy summary") + label("Export JSON") + label("Zero stats")
+ theme::space::TOOLBAR_NOTE_WIDTH
+ gaps * 7.0
}
/// The slim bar at the top of the page: the wordmark and the range at the left; the
/// actions at the right, on their own line where there is no room beside the range.
fn controls(dashboard: &mut Dashboard, ui: &mut egui::Ui) {
let ctx = ui.ctx().clone();
let now = Dashboard::now(&ctx);
let gap = theme::space::TOOL_GAP;
let margin = theme::space::PAGE_MARGIN;
let vertical = 10.0;
ui.add_space(vertical);
let width = ui.available_rect_before_wrap().width() - 2.0 * margin;
let medium = theme::medium(theme::px::BODY);
let range_width: f32 = Range::ALL
.iter()
.map(|range| style::text_width(ui, range.code(), medium.clone()) + 2.0 * theme::space::CONTROL_PAD)
.sum();
let left_width = wordmark_width(ui) + 2.0 * theme::space::PANEL_GAP + range_width;
let one_line = left_width + gap + actions_width(ui) <= width;
let phone = width + 2.0 * theme::space::PAGE_MARGIN < theme::layout::TWO_COLUMNS_FROM;
let labels: Vec<&str> = Range::ALL.iter().map(|range| range.code()).collect();
let chosen = Range::ALL.iter().position(|range| *range == dashboard.range).unwrap_or(0);
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = gap;
ui.add_space(margin);
wordmark(ui);
ui.add_space(theme::space::PANEL_GAP - gap);
if let Some(index) = style::segmented(ui, "range", &labels, chosen) {
if index != chosen {
dashboard.range = Range::ALL[index];
dashboard.settings_changed = true;
dashboard.send(&ctx, Ask::View);
}
}
if one_line {
ui.add_space((ui.available_width() - actions_width(ui) - margin).max(0.0));
ui.allocate_ui_with_layout(
egui::vec2(actions_width(ui), theme::layout::TOOLBAR_HEIGHT),
egui::Layout::left_to_right(egui::Align::Center),
|ui| actions(dashboard, ui, &ctx, now, gap),
);
}
});
if !one_line {
let height = theme::layout::TOOLBAR_HEIGHT;
ui.add_space(gap);
let room = ui.available_rect_before_wrap().width() - 2.0 * margin;
let group_width = if phone { room } else { actions_width(ui).min(room) };
// On a phone the actions wrap at the left; on a narrower window they sit
// on a second line, at the right.
let layout = if phone {
egui::Layout::left_to_right(egui::Align::Center).with_main_wrap(true)
} else {
egui::Layout::right_to_left(egui::Align::Center)
};
ui.horizontal(|ui| {
ui.add_space(margin);
ui.allocate_ui_with_layout(egui::vec2(room, height), layout, |ui| {
if !phone {
ui.allocate_ui_with_layout(
egui::vec2(group_width, height),
egui::Layout::left_to_right(egui::Align::Center),
|ui| actions(dashboard, ui, &ctx, now, gap),
);
} else {
ui.spacing_mut().item_spacing = egui::vec2(gap, gap);
actions(dashboard, ui, &ctx, now, gap);
}
});
});
}
ui.add_space(vertical);
let rule = ui.available_rect_before_wrap();
ui.painter().hline(
rule.x_range(),
rule.top() + 0.5,
egui::Stroke::new(1.0, theme::ctx(&ctx).border),
);
ui.add_space(1.0);
}
/// Refresh, theme, Copy summary, Export JSON, Zero stats, and the message slot.
fn actions(dashboard: &mut Dashboard, ui: &mut egui::Ui, ctx: &egui::Context, now: f64, gap: f32) {
ui.spacing_mut().item_spacing.x = gap;
let mut refresh_secs = dashboard.refresh_secs;
egui::ComboBox::from_id_salt("refresh")
.selected_text(fmt::refresh_label(refresh_secs))
.show_ui(ui, |ui| {
for secs in REFRESH_CHOICES {
ui.selectable_value(&mut refresh_secs, secs, fmt::refresh_label(secs));
}
});
if refresh_secs != dashboard.refresh_secs {
dashboard.refresh_secs = refresh_secs;
dashboard.settings_changed = true;
}
if ui.button("Refresh").clicked() {
dashboard.send(ctx, Ask::View);
}
let theme_chosen = ThemeChoice::ALL
.iter()
.position(|theme| *theme == dashboard.theme)
.unwrap_or(0);
if let Some(index) = style::segmented(ui, "theme", &theme_labels(), theme_chosen) {
let theme = ThemeChoice::ALL[index];
dashboard.theme = theme;
dashboard.settings_changed = true;
ctx.set_theme(theme.preference());
}
let online = dashboard.view.is_some();
let copy = ui.add_enabled(online, egui::Button::new("Copy summary"));
if copy.clicked() {
if let Some(view) = &dashboard.view {
ctx.copy_text(view.summary_markdown.clone());
}
dashboard.flash("Summary copied", now);
}
let export = ui.add_enabled(online, egui::Button::new("Export JSON"));
if export.clicked() {
let note = net::download("/api/export").map_or_else(
|error| format!("Export failed: {error}"),
|()| "Export started".to_owned(),
);
dashboard.flash(note, now);
}
let zeroing = dashboard
.pending
.as_ref()
.is_some_and(|(ask, _)| *ask == Ask::Zero);
let zero = ui.add_enabled(online && !zeroing, egui::Button::new("Zero stats"));
if zero.clicked() {
dashboard.asking_zero = true;
}
// A fixed-size slot, so that messages come and go without moving the controls.
ui.allocate_ui_with_layout(
egui::vec2(theme::space::TOOLBAR_NOTE_WIDTH, theme::layout::TOOLBAR_HEIGHT),
egui::Layout::left_to_right(egui::Align::Center),
|ui| {
if dashboard
.pending
.as_ref()
.is_some_and(|(ask, _)| *ask == Ask::View)
{
ui.spinner();
ui.add(egui::Label::new(theme::small(ui, "Updating")).truncate());
} else if let Some((note, _)) = &dashboard.note {
ui.add(egui::Label::new(theme::small(ui, note.clone())).truncate());
}
},
);
}
/// Ask before zeroing: it can't be undone.
fn zero_question(dashboard: &mut Dashboard, ctx: &egui::Context) {
let modal = egui::Modal::new(egui::Id::unique("zero-stats-question")).show(ctx, |ui| {
ui.set_max_width(360.0);
ui.add(egui::Label::new(theme::strong("Zero sccache's stats?")).wrap());
ui.add_space(theme::space::ITEM);
ui.add(egui::Label::new(theme::body(
"The counters go back to zero. The saved history stays, so the charts keep their \
older data. This can't be undone.",
))
.wrap());
ui.add_space(theme::space::PANEL_GAP);
ui.horizontal(|ui| {
if ui.button("Zero stats").clicked() {
Some(true)
} else if ui.button("Cancel").clicked() {
Some(false)
} else {
None
}
})
.inner
});
let answer = modal.inner;
if modal.should_close() || answer == Some(false) {
dashboard.asking_zero = false;
}
if answer == Some(true) {
dashboard.asking_zero = false;
dashboard.send(ctx, Ask::Zero);
}
}
/// What the page says while no view has arrived yet.
fn waiting(ui: &mut egui::Ui, error: Option<&str>, refresh_secs: u64) {
let p = theme::ui(ui);
let retry = if refresh_secs > 0 {
format!("Trying again every {refresh_secs} seconds.")
} else {
"Press Refresh to try again.".to_owned()
};
let (heading, body, color) = match error {
Some(error) => (
"Can't reach the server".to_owned(),
format!(
"{error}.\n\nCheck that sccache-dash is running on this machine. {retry}"
),
p.bad,
),
None => (
"Waiting for the first figures".to_owned(),
"Asking the server for your cache numbers.".to_owned(),
p.text,
),
};
// The same height the headline and cards take, so the page doesn't jump when they arrive.
let width = ui.available_rect_before_wrap().width();
let height = theme::layout::HEADLINE_HEIGHT + theme::space::PANEL_GAP + theme::layout::STRIP_ROW_HEIGHT * 2.0;
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, height), egui::Sense::hover());
let mut place = ui.new_child(
egui::UiBuilder::new()
.max_rect(rect)
.layout(egui::Layout::centered_and_justified(egui::Direction::TopDown)),
);
place.vertical(|ui| {
ui.add(egui::Label::new(theme::strong(heading).color(color)).wrap());
ui.add(egui::Label::new(theme::small(ui, body)).wrap());
});
}
/// A notice that the server can't be reached, shown over the page rather than
/// in it, so what is already on screen keeps its place and height.
fn lost_contact(ctx: &egui::Context, error: &str, from: i64, page_width: f32) {
let p = theme::ctx(ctx);
let when = fmt::moment_text(from + fmt::local_offset());
egui::Area::new(egui::Id::unique("lost-contact"))
.anchor(
egui::Align2::RIGHT_TOP,
egui::vec2(-theme::space::PAGE_MARGIN, theme::layout::TOOLBAR_HEIGHT + 3.0 * theme::space::PAGE_MARGIN),
)
.order(egui::Order::Foreground)
.show(ctx, |ui| {
let width = (page_width - 2.0 * theme::space::PAGE_MARGIN).min(440.0);
egui::Frame::NONE
.fill(p.panel)
.stroke(egui::Stroke::new(1.0, p.bad))
.corner_radius(theme::space::PANEL_RADIUS)
.inner_margin(theme::space::PANEL_PAD_Y)
.show(ui, |ui| {
ui.set_max_width(width - 2.0 * theme::space::PANEL_PAD_Y);
ui.add(
egui::Label::new(
theme::strong(format!(
"Can't reach the server: {error}. These figures are from {when}."
))
.color(p.bad),
),
);
});
});
}
/// The rectangles of one row of the grid: each entry of `spans` is how many
/// columns that panel takes; all are at least `height` tall.
fn row(ui: &egui::Ui, height: f32, spans: &[usize]) -> Vec<egui::Rect> {
style::cells(ui, height, spans)
}
/// Close the row: the cursor moves below the tallest of its panels.
fn close_row(ui: &mut egui::Ui, taken: &[egui::Rect]) {
style::end_row(ui, taken);
}
/// One panel across the whole page, as tall as what it holds.
fn single(ui: &mut egui::Ui, title: &str, body: impl FnOnce(&mut egui::Ui)) {
let [rect] = row(ui, 0.0, &[1]).try_into().expect("one panel");
let (_, taken) = style::panel(ui, rect, title, body);
close_row(ui, &[taken]);
}
/// How tall a panel is that holds `rows` table rows under its title.
fn table_height(fixed: f32, rows: usize) -> f32 {
fixed + rows as f32 * theme::space::ROW
}
/// How tall "Speed" is.
fn speed_height(view: &View) -> f32 {
use theme::layout as l;
let with_histograms = view
.build_times
.iter()
.filter(|times| times.compiles > 0 && !times.bins.is_empty())
.count();
table_height(l::SPEED_FIXED_HEIGHT, 0) + with_histograms as f32 * l::HISTOGRAM_HEIGHT
}
/// The whole page below the controls: a grid of panels. Two columns of panels
/// from the medium width up, one below it; the counter strip is six across,
/// three across, or two.
fn page(ui: &mut egui::Ui, view: &View, asked: Range, hidden_languages: &mut Vec<String>) {
let p = theme::ui(ui);
use theme::layout as l;
let gap = theme::space::PANEL_GAP;
if let Some(error) = &view.server.error {
style::banner(ui, egui::RichText::new(format!("sccache is not working: {error}")), p.bad);
ui.add_space(gap);
}
let columns = theme::columns(ui.available_rect_before_wrap().width());
headline(ui, view, asked);
// Six counters in one row on a wide screen; three in the medium layout; two on a phone.
let per_row = match columns {
3 => 6,
2 => 3,
_ => 2,
};
cards::row(ui, view, per_row);
if columns >= 2 {
let half = style::span_width(ui, 2, 1);
let languages_h = table_height(l::LANGUAGES_FIXED_HEIGHT, view.languages.len() + 1);
let [a, b] = row(ui, l::WHERE_FIXED_HEIGHT.max(languages_h), &[1, 1]).try_into().expect("two panels");
let (_, a) = style::panel(ui, a, "Where compiles went", |ui| where_went::section(ui, view));
let (_, b) = style::panel(ui, b, "By language", |ui| where_went::languages(ui, view));
close_row(ui, &[a, b]);
overtime::filter(ui, view, hidden_languages);
ui.add_space(theme::space::ITEM);
let hidden: &[String] = hidden_languages;
let [a, b] = row(ui, l::CHART_PANEL_HEIGHT, &[1, 1]).try_into().expect("two panels");
let (_, a) = style::panel(ui, a, "Hit rate over time", |ui| {
overtime::hit_rate_panel(ui, view, hidden, theme::drawing::CHART_HEIGHT)
});
let (_, b) = style::panel(ui, b, "Compiles over time", |ui| {
overtime::volume_panel(ui, view, hidden, theme::drawing::CHART_HEIGHT)
});
close_row(ui, &[a, b]);
let height = speed_height(view).max(where_went::reasons_height(ui, view, half));
let [a, b] = row(ui, height, &[1, 1]).try_into().expect("two panels");
let (_, a) = style::panel(ui, a, "Speed", |ui| speed::section(ui, view));
let (_, b) = style::panel(ui, b, "Why compiles were not cacheable", |ui| where_went::reasons(ui, view));
close_row(ui, &[a, b]);
} else {
// One column: each panel as tall as what it holds.
single(ui, "Where compiles went", |ui| where_went::section(ui, view));
single(ui, "By language", |ui| where_went::languages(ui, view));
overtime::filter(ui, view, hidden_languages);
ui.add_space(theme::space::ITEM);
let hidden: &[String] = hidden_languages;
single(ui, "Hit rate over time", |ui| {
overtime::hit_rate_panel(ui, view, hidden, theme::drawing::CHART_HEIGHT)
});
single(ui, "Compiles over time", |ui| {
overtime::volume_panel(ui, view, hidden, theme::drawing::CHART_HEIGHT)
});
single(ui, "Speed", |ui| speed::section(ui, view));
single(ui, "Why compiles were not cacheable", |ui| where_went::reasons(ui, view));
}
extras(ui, view);
let open = ui
.ctx()
.data_mut(|data| data.get_temp::<bool>(egui::Id::new("raw-counters-open")))
.unwrap_or(false);
let full = style::span_width(ui, 1, 1);
let [rect] = row(ui, raw::height(view, full, open), &[1]).try_into().expect("one panel");
let taken = raw::section(ui, view, rect);
close_row(ui, &[taken]);
ui.add_space(theme::space::PAGE_MARGIN);
}
/// The "Extras" panels, side by side where there are several.
fn extras(ui: &mut egui::Ui, view: &View) {
if view.extras.is_empty() {
return;
}
let columns = theme::columns(ui.available_rect_before_wrap().width()).min(2);
let per_row = columns.min(view.extras.len()).max(1);
for line in view.extras.chunks(per_row) {
let spans: Vec<usize> = line.iter().map(|_| 1).collect();
let height = theme::space::ROW * (line.iter().map(|extra| extra.rows.len()).max().unwrap_or(0) + 1) as f32
+ theme::space::PANEL_PAD_Y * 2.0 + theme::space::UNDER_TITLE + 12.0;
let cells = style::cells(ui, height, &spans);
let mut taken = Vec::with_capacity(cells.len());
for (rect, extra) in cells.iter().zip(line) {
let title: &str = Box::leak(extra.title.clone().into_boxed_str());
let (_, rect) = style::panel(ui, *rect, title, |ui| extras::section(ui, view));
taken.push(rect);
}
close_row(ui, &taken);
}
}
/// One of the three big figures.
struct Figure<'a> {
value: String,
/// The size of the figure's text: a number, or words at the card size.
size: f32,
color: egui::Color32,
caption: String,
/// Smaller print under the figure.
small: String,
/// A second line of smaller print; the block keeps its height when it is empty.
small2: String,
/// A trend line and the value it is drawn against.
trend: Option<(&'a [Option<f64>], f64)>,
/// Instead of a trend line and small print: the problems list.
problems: Option<&'a View>,
hover: Option<String>,
}
/// The line the figure's number sits on: every figure's number has this much room, so all
/// the captions below start at the same height whatever size the number is drawn at.
const VALUE_ROW: f32 = theme::px::HEADLINE * 1.25;
/// The room the storage line (meter and text) is given under the figures; a phone has a second text line.
const STORAGE_LINE: f32 = 30.0;
impl Figure<'_> {
/// Draw in a column `width` wide and always the same height.
fn draw(self, ui: &mut egui::Ui, width: f32) {
let gap = theme::space::LINE;
let block = ui.allocate_ui_with_layout(
egui::vec2(width, theme::layout::FIGURE_HEIGHT),
egui::Layout::top_down(egui::Align::Min),
|ui| {
ui.set_width(width);
ui.spacing_mut().item_spacing = egui::vec2(gap, gap);
// Shrink a long figure to the column instead of cutting it.
let natural = style::text_width(ui, &self.value, theme::number_font(self.size));
let size = if natural > width { (self.size * width / natural).max(20.0) } else { self.size };
ui.allocate_ui_with_layout(
egui::vec2(width, VALUE_ROW),
egui::Layout::left_to_right(egui::Align::Max),
|ui| {
let value = egui::Label::new(
egui::RichText::new(&self.value)
.font(theme::number_font(size))
.color(self.color),
)
.truncate();
ui.add(value.sense(egui::Sense::hover())).on_hover_text(&self.value);
},
);
ui.add(egui::Label::new(theme::title(ui, self.caption.clone())).truncate());
ui.add_space(gap * 2.0);
if let Some(view) = self.problems {
let room = ui.available_height();
problems::hero_list(ui, view, room);
return;
}
match self.trend {
Some((values, top)) => style::sparkline(ui, theme::drawing::SPARKLINE, values, top, self.color),
None => ui.add_space(theme::drawing::SPARKLINE + gap),
}
ui.add(egui::Label::new(theme::small(ui, self.small.clone())).truncate());
ui.add(egui::Label::new(theme::small(ui, self.small2.clone())).truncate());
},
);
if let Some(hover) = self.hover {
block.response.on_hover_text(hover);
}
}
}
/// The big numbers, what they mean, and where the cache lives.
fn headline(ui: &mut egui::Ui, view: &View, asked: Range) {
let range = view.range.unwrap_or(asked);
let totals = &view.totals;
let p = theme::ui(ui);
let rates: Vec<Option<f64>> = view
.buckets
.iter()
.map(|bucket| (!bucket.gap).then(|| overtime::hit_rate(bucket.hits, bucket.misses)).flatten())
.collect();
let saved: Vec<Option<f64>> = view
.buckets
.iter()
.map(|bucket| (!bucket.gap).then_some(bucket.saved_seconds))
.collect();
let saved_top = saved.iter().flatten().fold(0.0_f64, |top, seconds| top.max(*seconds));
let problems = view.problems.len();
let counts = format!(
"{} compiles · {} from cache · {} built",
fmt::count(totals.requests),
fmt::count(totals.hits),
fmt::count(totals.misses)
);
let title_text = theme::title(ui, range.label()).text().to_owned();
let counts_text = counts.clone();
let width = ui.available_rect_before_wrap().width();
// Side by side where there is room; one under another on a phone.
let side_by_side = width >= 600.0;
let spacing = theme::space::PANEL_GAP;
let height = if side_by_side {
theme::layout::HEADLINE_HEIGHT
} else {
theme::layout::HEADLINE_HEIGHT + 2.0 * (theme::layout::FIGURE_HEIGHT + spacing) + STORAGE_LINE / 2.0
};
let rect = egui::Rect::from_min_size(ui.cursor().min, egui::vec2(width, height));
let (_, taken) = style::panel_titled(
ui,
rect,
|ui| {
ui.horizontal(|ui| {
ui.add(egui::Label::new(theme::title(ui, title_text)).truncate());
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.add(egui::Label::new(theme::small(ui, counts_text)).truncate());
});
});
},
|ui| {
let width = ui.available_rect_before_wrap().width();
let columns = if side_by_side { 3.0 } else { 1.0 };
let column = (width - spacing * (columns - 1.0)) / columns;
ui.add_space(theme::space::ITEM);
let draw = |ui: &mut egui::Ui, figure: Figure<'_>| figure.draw(ui, column);
// Timeouts, cache errors and forced recaches are inside the built count, as sccache counts them.
let first = Figure {
value: fmt::percent(totals.hit_rate()),
size: theme::px::HEADLINE,
color: p.hero,
caption: "from cache".into(),
small: format!("{} of all compiler calls", fmt::percent(totals.hit_rate_of_all())),
trend: Some((&rates, 1.0)),
problems: None,
hover: None,
small2: String::new(),
};
// A saving is never written in milliseconds; and when no language's build time is
// known yet, the figure says so instead of showing nothing.
let seconds = view.time_saved.seconds;
let left_out = view.time_saved.hits_left_out;
let left_out_line = if left_out > 0 {
format!("{} hits left out of this figure", fmt::count(left_out))
} else {
"every hit counted".to_owned()
};
let interval = view
.time_saved
.interval_90
.map(|(low, high)| format!("{} – {} (90% range)", fmt::duration(low), fmt::duration(high)));
let (value, size, small, small2) = if seconds >= 1.0 {
(format!("~{}", fmt::duration(seconds)), theme::px::HEADLINE, interval.unwrap_or_default(), left_out_line)
} else if seconds > 0.0 {
("~under 1 s".to_owned(), theme::px::HEADLINE, interval.unwrap_or_default(), left_out_line)
} else if left_out > 0 {
(
"not enough data yet".to_owned(),
theme::px::CARD_NUMBER,
String::new(),
format!(
"{} hits not counted: no build time known yet for their language",
fmt::count(left_out)
),
)
} else {
("nothing saved yet".to_owned(), theme::px::CARD_NUMBER, String::new(), String::new())
};
let second = Figure {
value,
size,
color: p.hero,
caption: "saved (rough)".into(),
small,
small2,
trend: Some((&saved, saved_top)),
problems: None,
hover: Some(view.time_saved.note.clone()),
};
let third = Figure {
value: fmt::count(problems as u64),
size: theme::px::HEADLINE,
color: if problems > 0 { p.bad } else { p.text },
caption: if problems == 1 { "problem".into() } else { "problems".into() },
small: String::new(),
small2: String::new(),
trend: None,
problems: Some(view),
hover: None,
};
let top = ui.cursor().top();
let left = ui.cursor().left();
if side_by_side {
ui.horizontal_top(|ui| {
ui.spacing_mut().item_spacing.x = spacing;
draw(ui, first);
draw(ui, second);
draw(ui, third);
});
// A hairline in the middle of each gutter between figures.
let y = top..=top + theme::layout::FIGURE_HEIGHT;
for index in 1..3 {
let x = left + index as f32 * column + (index as f32 - 0.5) * spacing;
ui.painter().vline(x.round() + 0.5, y.clone(), egui::Stroke::new(1.0, p.grid));
}
} else {
draw(ui, first);
ui.add_space(spacing);
draw(ui, second);
ui.add_space(spacing);
draw(ui, third);
}
ui.add_space(theme::space::ITEM);
style::rule(ui);
ui.add_space(theme::space::ITEM + 2.0);
let server = &view.server;
let mut parts = Vec::new();
if let Some(location) = &server.cache_location {
// sccache words it `Local disk: "/home/me/.cache/sccache"`; the kind is enough here.
let kind = location.split(':').next().unwrap_or(location);
let kind = if kind.eq_ignore_ascii_case("LOCAL DISK") {
"Local disk".to_owned()
} else {
kind.to_owned()
};
parts.push(kind);
}
if let (Some(size), Some(max)) = (server.cache_size, server.max_cache_size) {
parts.push(format!("{} of {}", fmt::bytes(size), fmt::bytes(max)));
}
if let Some(version) = server.version.as_deref().or(server.client_version.as_deref()) {
parts.push(format!("sccache {version}"));
}
parts.push(
match server.status {
sccache_dash_api::Status::Running => "running",
sccache_dash_api::Status::Idle => "idle",
sccache_dash_api::Status::NotRunning => "not running",
}
.to_owned(),
);
let line = parts.join(" · ");
// The meter first, then the text under it, in a box of fixed height.
let lines = if side_by_side { 1.0 } else { 2.0 };
let text_height = STORAGE_LINE / 2.0 * lines;
if let (Some(size), Some(max)) = (server.cache_size, server.max_cache_size) {
let full = if max > 0 { size as f64 / max as f64 } else { 0.0 };
let color = if full >= theme::state::CACHE_FULL { p.bad } else { p.hero };
style::meter(ui, theme::drawing::USAGE_BAR, full, color);
ui.add_space(theme::space::ITEM);
}
let response = ui
.allocate_ui_with_layout(
egui::vec2(width, text_height),
egui::Layout::top_down(egui::Align::Min),
|ui| ui.add(egui::Label::new(theme::small(ui, line)).wrap()),
)
.inner;
if let Some(location) = &server.cache_location {
response.on_hover_text(location.clone());
}
},
);
ui.allocate_rect(taken, egui::Sense::hover());
ui.add_space(theme::space::PANEL_GAP);
}
+143
View File
@@ -0,0 +1,143 @@
//! The six counters under the headline: one quiet strip, all cells the same size, tops in a line.
use eframe::egui::{self, Color32, Pos2, Rect, RichText};
use sccache_dash_api::{Range, View};
use crate::fmt;
use crate::style;
use crate::theme;
/// The cards in `per_row` per row: six in one row on a wide screen, three in
/// the two-column layout, two on a phone.
pub fn row(ui: &mut egui::Ui, view: &View, per_row: usize) {
let totals = &view.totals;
let previous = view.previous.as_ref();
let range = view.range.unwrap_or(Range::Day);
let p = theme::ui(ui);
let requests = totals.requests;
let cache_errors = totals.errors();
let cards = [
Card {
title: "Cache hits",
count: totals.hits,
color: None,
detail: format!("{} of compiler calls", fmt::share(totals.hits, requests)),
previous: previous.map(|previous| previous.hits),
good_when_up: true,
},
Card {
title: "Cache misses",
count: totals.misses,
color: None,
detail: format!("{} of compiler calls", fmt::share(totals.misses, requests)),
previous: previous.map(|previous| previous.misses),
good_when_up: false,
},
Card {
title: "Timeouts",
count: totals.timeouts,
color: (totals.timeouts > 0).then_some(p.bad),
detail: String::new(),
previous: previous.map(|previous| previous.timeouts),
good_when_up: false,
},
Card {
title: "Cache errors",
count: cache_errors,
color: (cache_errors > 0).then_some(p.bad),
detail: format!(
"{} read · {} write · {} other",
fmt::count(totals.read_errors),
fmt::count(totals.write_errors),
fmt::count(totals.other_errors)
),
previous: previous.map(|previous| previous.errors()),
good_when_up: false,
},
Card {
title: "Compile failures",
count: totals.compile_fails,
color: None,
detail: String::new(),
previous: previous.map(|previous| previous.compile_fails),
good_when_up: false,
},
Card {
title: "Forced recaches",
count: totals.forced_recaches,
color: None,
detail: String::new(),
previous: previous.map(|previous| previous.forced_recaches),
good_when_up: false,
},
];
let per_row = per_row.max(1);
let left = ui.cursor().left();
let mut top = ui.cursor().top();
let width = ui.available_rect_before_wrap().width();
let cell_width = width / per_row as f32;
let height = theme::layout::STRIP_ROW_HEIGHT;
let rule = egui::Stroke::new(1.0, p.border);
ui.painter().hline(left..=left + width, top + 0.5, rule);
for (line_index, line) in cards.chunks(per_row).enumerate() {
if line_index > 0 {
ui.painter().hline(left..=left + width, top + 0.5, egui::Stroke::new(1.0, p.grid));
}
for (index, card) in line.iter().enumerate() {
let change = change(card.count, card.previous, range, card.good_when_up, p);
style::card(
ui,
Rect::from_min_size(Pos2::new(left + index as f32 * cell_width, top), egui::vec2(cell_width, height)),
index == 0,
card.title,
&fmt::count(card.count),
&card.detail,
change,
card.color.unwrap_or(p.text),
);
}
top += height;
}
ui.painter().hline(left..=left + width, top - 0.5, rule);
ui.add_space(top - ui.cursor().top());
ui.add_space(theme::space::PANEL_GAP);
}
struct Card {
title: &'static str,
count: u64,
/// The colour of the count when it is worth a look.
color: Option<Color32>,
/// The line between the count and the comparison.
detail: String,
/// The same count in the period before, when the server has one.
previous: Option<u64>,
/// Whether more of this count is good news.
good_when_up: bool,
}
/// How a count compares with the period before, and the colour that change deserves.
fn change(count: u64, previous: Option<u64>, range: Range, good_when_up: bool, p: &theme::Palette) -> RichText {
let Some(previous) = previous else {
return RichText::new("").font(egui::FontId::proportional(theme::px::SMALL));
};
if previous == 0 {
return small_plain(p, if count == 0 { String::new() } else { "was 0 before".into() });
}
let change = (count as f64 - previous as f64) / previous as f64 * 100.0;
if change.abs() < 0.5 {
return small_plain(p, "no change".into());
}
let better = (change > 0.0) == good_when_up;
RichText::new(format!("{change:+.0}% vs {}", fmt::previous_label(range)))
.font(egui::FontId::proportional(theme::px::SMALL))
.color(if better { p.good } else { p.bad })
}
fn small_plain(p: &theme::Palette, text: String) -> RichText {
RichText::new(text)
.font(egui::FontId::proportional(theme::px::SMALL))
.color(p.muted)
}
+88
View File
@@ -0,0 +1,88 @@
//! The arithmetic of a list of lines that open: which start open, how tall the
//! list is, and whether stacking panels beside it wastes less room. No drawing
//! here, so it is tested natively.
/// A line that opens to show a text beneath it, laid out for a width.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Entry {
/// The line itself.
pub row: f32,
pub open: bool,
/// The first paragraph's height; used only when open.
pub meaning: f32,
/// The second paragraph's height, `None` when there is none; used only when open.
pub action: Option<f32>,
}
/// Whether a line is open: what was clicked, else open when `fixable`.
pub fn is_open(stored: Option<bool>, fixable: bool) -> bool {
stored.unwrap_or(fixable)
}
/// How tall one line is: `gap` between its parts, `pad` under the open text.
pub fn entry_height(entry: &Entry, gap: f32, pad: f32) -> f32 {
if !entry.open {
return entry.row;
}
let action = entry.action.map_or(0.0, |height| gap + height);
entry.row + gap + entry.meaning + action + pad
}
/// How tall the whole list is: its lines and a hairline `separator` tall between them.
pub fn list_height(entries: &[Entry], gap: f32, pad: f32, separator: f32) -> f32 {
let lines: f32 = entries.iter().map(|entry| entry_height(entry, gap, pad)).sum();
lines + entries.len().saturating_sub(1) as f32 * separator
}
/// Whether to stack the panels (`stacked` tall in all) beside a panel `beside` tall rather
/// than put the one `single` panel there: yes when that leaves less empty room.
pub fn stack_beside(single: f32, stacked: f32, beside: f32) -> bool {
(stacked - beside).abs() < (single - beside).abs()
}
#[cfg(test)]
mod tests {
use super::*;
fn entry(open: bool) -> Entry {
Entry { row: 28.0, open, meaning: 45.0, action: Some(30.0) }
}
#[test]
fn only_fixable_lines_start_open() {
assert!(is_open(None, true));
assert!(!is_open(None, false));
}
#[test]
fn a_click_wins_over_the_default() {
assert!(!is_open(Some(false), true));
assert!(is_open(Some(true), false));
}
#[test]
fn a_closed_line_is_one_row_and_an_open_one_adds_its_text() {
assert_eq!(entry_height(&entry(false), 3.0, 8.0), 28.0);
assert_eq!(entry_height(&entry(true), 3.0, 8.0), 28.0 + 3.0 + 45.0 + 3.0 + 30.0 + 8.0);
let no_action = Entry { action: None, ..entry(true) };
assert_eq!(entry_height(&no_action, 3.0, 8.0), 28.0 + 3.0 + 45.0 + 8.0);
}
#[test]
fn a_list_is_its_lines_and_the_hairlines_between() {
let list = [entry(true), entry(false), entry(false)];
assert_eq!(list_height(&list, 3.0, 8.0, 1.0), 117.0 + 28.0 + 28.0 + 2.0);
assert_eq!(list_height(&[], 3.0, 8.0, 1.0), 0.0);
assert_eq!(list_height(&[entry(false)], 3.0, 8.0, 1.0), 28.0);
}
#[test]
fn stacking_is_chosen_only_when_it_fills_the_room_better() {
// Everything closed: the lone panel (244) is close to the list (300); three stacked (500) are not.
assert!(!stack_beside(244.0, 500.0, 300.0));
// Two open: the list (520) is nearer the stack.
assert!(stack_beside(244.0, 500.0, 520.0));
// A tie keeps the simple layout.
assert!(!stack_beside(200.0, 400.0, 300.0));
}
}
+22
View File
@@ -0,0 +1,22 @@
//! Extras: the tables sccache only fills in for some setups, one panel each.
use sccache_dash_api::View;
use crate::style::{self, Cell};
use crate::theme;
pub fn section(ui: &mut eframe::egui::Ui, view: &View) {
for extra in &view.extras {
let rows: Vec<Vec<Cell>> = extra
.rows
.iter()
.map(|(label, value)| {
vec![
Cell::Text(theme::strong(label.clone())),
Cell::Text(theme::number(value.clone())),
]
})
.collect();
style::table(ui, &[], &rows);
}
}
+313
View File
@@ -0,0 +1,313 @@
//! How numbers, durations and times are written on the page.
use sccache_dash_api::Range;
/// How a comparison with the period before is worded, from the range's own
/// label: "previous 24 hours".
pub fn previous_label(range: Range) -> String {
let label = range.label();
format!("previous {}", label.strip_prefix("last ").unwrap_or(label))
}
/// The lowest edge of a row of panels: the largest of their `bottoms`, or
/// `empty` when there are none. The bottoms are screen positions, so they are
/// negative while the row is scrolled above the top of the window.
pub fn lowest(bottoms: impl IntoIterator<Item = f32>, empty: f32) -> f32 {
bottoms.into_iter().reduce(f32::max).unwrap_or(empty)
}
/// Whole-number percentages of `parts` that add up to exactly 100, giving the
/// leftovers of rounding to the largest shares. All zero when nothing is counted.
pub fn shares(parts: &[u64]) -> Vec<u64> {
let total: u64 = parts.iter().sum();
if total == 0 {
return vec![0; parts.len()];
}
let exact: Vec<f64> = parts
.iter()
.map(|part| 100.0 * *part as f64 / total as f64)
.collect();
let mut whole: Vec<u64> = exact.iter().map(|value| value.floor() as u64).collect();
let mut left = 100 - whole.iter().sum::<u64>();
let mut by_fraction: Vec<usize> = (0..parts.len()).collect();
by_fraction.sort_by(|a, b| exact[*b].fract().total_cmp(&exact[*a].fract()));
for index in by_fraction {
if left == 0 {
break;
}
whole[index] += 1;
left -= 1;
}
whole
}
/// How the refresh control names an interval: "Every 10 s", or "Off".
pub fn refresh_label(secs: u64) -> String {
if secs == 0 {
"Off".into()
} else {
format!("Every {secs} s")
}
}
/// A count with thousands separators: 2815 becomes "2,815".
pub fn count(n: u64) -> String {
let digits = n.to_string();
let first = (digits.len() - 1) % 3 + 1;
let mut out = String::with_capacity(digits.len() + digits.len() / 3);
out.push_str(&digits[..first]);
for (index, digit) in digits[first..].chars().enumerate() {
if index % 3 == 0 {
out.push(',');
}
out.push(digit);
}
out
}
/// A ratio as whole percent: 0.456 becomes "46%"; "—" when there is no ratio.
pub fn percent(ratio: Option<f64>) -> String {
ratio.map_or_else(|| "—".into(), |ratio| format!("{:.0}%", ratio * 100.0))
}
/// `part` of `whole` as whole percent; "—" when `whole` is zero.
pub fn share(part: u64, whole: u64) -> String {
percent((whole > 0).then(|| part as f64 / whole as f64))
}
/// Seconds the short way: "0.7 ms", "8.1 s", "3m 05s", "3h 05m", "2d 3h".
pub fn duration(seconds: f64) -> String {
if !seconds.is_finite() {
return "—".into();
}
let seconds = seconds.max(0.0);
if seconds < 1.0 {
return format!("{:.1} ms", seconds * 1000.0);
}
let tenths = (seconds * 10.0).round() as u64;
let (whole, tenth) = (tenths / 10, tenths % 10);
if whole < 60 {
return format!("{whole}.{tenth} s");
}
let (minutes, second) = (whole / 60, whole % 60);
if minutes < 60 {
return format!("{minutes}m {second:02}s");
}
let (hours, minute) = (minutes / 60, minutes % 60);
if hours < 24 {
return format!("{hours}h {minute:02}m");
}
let (days, hour) = (hours / 24, hours % 24);
format!("{days}d {hour}h")
}
/// A multiple in round numbers: 11432.7 becomes "11,000", 7.42 becomes "7.4".
pub fn round_number(n: f64) -> String {
if !n.is_finite() || n <= 0.0 {
return "—".into();
}
if n < 10.0 {
return format!("{n:.1}");
}
let round_to = if n >= 1000.0 {
100.0
} else if n >= 100.0 {
10.0
} else {
1.0
};
count((n / round_to).round() as u64 * round_to as u64)
}
/// A size in bytes the way file managers show it: "10.0 GB".
pub fn bytes(n: u64) -> String {
const K: f64 = 1024.0;
let (value, unit) = match n as f64 {
value if value < K => return format!("{n} B"),
value if value < K * K => (value / K, "KB"),
value if value < K * K * K => (value / (K * K), "MB"),
value if value < K * K * K * K => (value / (K * K * K), "GB"),
value => (value / (K * K * K * K), "TB"),
};
format!("{value:.1} {unit}")
}
/// Seconds to add to a Unix time to get the clock time of this computer.
/// The browser knows its time zone; a native window would need to find it another way.
pub fn local_offset() -> i64 {
#[cfg(target_arch = "wasm32")]
{
// `get_timezone_offset` is minutes to add to local time to get UTC.
-(js_sys::Date::new_0().get_timezone_offset() as i64) * 60
}
#[cfg(not(target_arch = "wasm32"))]
{
0
}
}
/// A moment as month, day and clock time.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Moment {
pub month: u32,
pub day: u32,
pub hour: u32,
pub minute: u32,
}
/// The moment `unix` seconds after 1 January 1970.
pub fn moment(unix: i64) -> Moment {
let days = unix.div_euclid(86_400);
let secs_of_day = unix.rem_euclid(86_400);
// Howard Hinnant's civil-from-days.
let z = days + 719_468;
let day_of_era = z.rem_euclid(146_097);
let year_of_era =
(day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
let mp = (5 * day_of_year + 2) / 153;
let day = day_of_year - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
Moment {
month: month as u32,
day: day as u32,
hour: (secs_of_day / 3600) as u32,
minute: (secs_of_day % 3600 / 60) as u32,
}
}
impl Moment {
/// "14:05"
pub fn clock(self) -> String {
format!("{:02}:{:02}", self.hour, self.minute)
}
/// "Nov 12"
pub fn date(self) -> String {
const MONTHS: [&str; 12] = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
];
let month = MONTHS[(self.month.clamp(1, 12) - 1) as usize];
format!("{month} {}", self.day)
}
}
/// "Nov 12, 14:05" for a moment given in Unix seconds.
pub fn moment_text(unix: i64) -> String {
let moment = moment(unix);
format!("{}, {}", moment.date(), moment.clock())
}
/// Spacing of the ticks on a time axis that long, in seconds: whole minutes,
/// hours or days, giving about four to eight ticks.
pub fn tick_step(span_secs: f64) -> i64 {
const STEPS: [i64; 14] = [
60, 120, 300, 600, 900, 1800, 3600, 7200, 10_800, 21_600, 43_200, 86_400, 172_800,
604_800,
];
STEPS
.into_iter()
.find(|step| span_secs / *step as f64 <= 7.5)
.unwrap_or(604_800)
}
/// The label for one tick of a time axis: the clock time, or the date for
/// ticks that fall on midnight or are a day or more apart.
pub fn tick_label(unix: i64, step: i64) -> String {
let moment = moment(unix);
if step >= 86_400 || unix.rem_euclid(86_400) == 0 {
moment.date()
} else {
moment.clock()
}
}
/// What is hidden after the "All languages" box changes: ticked shows every
/// language, cleared hides them all.
pub fn hidden_after_all<'a>(ticked: bool, languages: impl Iterator<Item = &'a str>) -> Vec<String> {
if ticked {
Vec::new()
} else {
languages.map(str::to_owned).collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_row_scrolled_above_the_window_still_ends_at_its_own_bottom() {
// Rows closed by their lowest panel: the same answer wherever the page is scrolled.
assert_eq!(lowest([260.0, 300.0, 280.0], 0.0), 300.0);
assert_eq!(lowest([-340.0, -300.0, -320.0], 0.0), -300.0);
assert_eq!(lowest([-17250.0, -17210.5], 0.0), -17210.5);
assert_eq!(lowest([], 42.0), 42.0);
}
#[test]
fn counts_have_thousands_separators() {
assert_eq!(count(0), "0");
assert_eq!(count(325), "325");
assert_eq!(count(2815), "2,815");
assert_eq!(count(123_456), "123,456");
assert_eq!(count(1_234_567_890), "1,234,567,890");
}
#[test]
fn durations_are_short_and_round_cleanly() {
assert_eq!(duration(0.0007), "0.7 ms");
assert_eq!(duration(0.0), "0.0 ms");
assert_eq!(duration(8.14), "8.1 s");
assert_eq!(duration(59.96), "1m 00s");
assert_eq!(duration(185.0), "3m 05s");
assert_eq!(duration(11_100.0), "3h 05m");
assert_eq!(duration(183_600.0), "2d 3h");
assert_eq!(duration(f64::NAN), "—");
}
#[test]
fn moments_match_the_calendar() {
assert_eq!(
moment(0),
Moment {
month: 1,
day: 1,
hour: 0,
minute: 0
}
);
// 1,700,000,000 is 14 November 2023, 22:13:20 UTC.
assert_eq!(moment_text(1_700_000_000), "Nov 14, 22:13");
// Day 95 after the epoch is 6 April 1970.
assert_eq!(moment_text(95 * 86_400 + 12 * 3600), "Apr 6, 12:00");
}
#[test]
fn numbers_are_round_and_ticked() {
assert_eq!(round_number(11_432.7), "11,400");
assert_eq!(round_number(7.42), "7.4");
assert_eq!(bytes(10 * 1024 * 1024 * 1024), "10.0 GB");
assert_eq!(tick_step(3660.0), 600);
assert_eq!(tick_step(86_640.0), 21_600);
assert_eq!(tick_label(43_200, 600), "12:00");
assert_eq!(tick_label(86_400, 600), "Jan 2");
}
#[test]
fn shares_add_up_to_one_hundred() {
assert_eq!(shares(&[50, 33, 17]), [50, 33, 17]);
assert_eq!(shares(&[1, 1, 1]), [34, 33, 33]);
assert_eq!(shares(&[7351, 0, 0, 0, 0]), [100, 0, 0, 0, 0]);
assert_eq!(shares(&[0, 0]), [0, 0]);
let parts = [3254, 3256, 829, 14, 13];
assert_eq!(shares(&parts).iter().sum::<u64>(), 100);
}
#[test]
fn all_languages_box_turns_them_back_on() {
let names = ["Rust", "C/C++"];
assert_eq!(hidden_after_all(true, names.into_iter()), Vec::<String>::new());
assert_eq!(hidden_after_all(false, names.into_iter()), vec!["Rust", "C/C++"]);
}
}
+175
View File
@@ -0,0 +1,175 @@
//! The sccache-dash dashboard page. `trunk` compiles this to WebAssembly and
//! the sccache-dash server serves it at http://127.0.0.1:8226.
pub mod disclosure;
pub mod fmt;
// Drawing needs eframe, which is only built for the browser so far; the rest
// (and the tests) build anywhere.
#[cfg(target_arch = "wasm32")]
mod app;
#[cfg(target_arch = "wasm32")]
mod cards;
#[cfg(target_arch = "wasm32")]
mod extras;
#[cfg(target_arch = "wasm32")]
mod net;
#[cfg(target_arch = "wasm32")]
mod overtime;
#[cfg(target_arch = "wasm32")]
mod problems;
#[cfg(target_arch = "wasm32")]
mod raw;
#[cfg(target_arch = "wasm32")]
mod speed;
#[cfg(target_arch = "wasm32")]
mod style;
#[cfg(target_arch = "wasm32")]
mod theme;
#[cfg(target_arch = "wasm32")]
mod where_went;
/// The canvas in `index.html` the page is drawn on.
pub const CANVAS_ID: &str = "the_canvas_id";
/// Open the dashboard page in the browser.
pub fn open() {
#[cfg(target_arch = "wasm32")]
web::open();
#[cfg(not(target_arch = "wasm32"))]
eprintln!(
"sccache-dash-ui is a web page: build it with `trunk build` in crates/ui. \
There is no native window yet."
);
}
#[cfg(target_arch = "wasm32")]
mod web {
use super::{app::Dashboard, CANVAS_ID};
pub fn open() {
use wasm_bindgen::JsCast;
let canvas = web_sys::window()
.and_then(|window| window.document())
.and_then(|document| document.get_element_by_id(CANVAS_ID))
.and_then(|element| element.dyn_into::<web_sys::HtmlCanvasElement>().ok())
.unwrap_or_else(|| panic!("index.html has no canvas named #{CANVAS_ID}"));
wasm_bindgen_futures::spawn_local(async move {
let options = eframe::WebOptions::default();
eframe::WebRunner::new()
.start(canvas, options, Box::new(|cc| Ok(Box::new(Dashboard::new(cc)))))
.await
.unwrap_or_else(|error| panic!("eframe failed to start: {error:?}"));
});
}
}
#[cfg(test)]
mod tests {
use sccache_dash_api::{Range, View};
/// A view with something in every part of the page.
const SAMPLE: &str = r#"{
"range": "24h",
"generated_at": 1764300000,
"server": {
"status": "Running",
"version": "0.18.0",
"client_version": "0.18.0",
"cache_location": "Local disk: \"/home/me/.cache/sccache\"",
"cache_size": 10726353131,
"max_cache_size": 10737418240,
"error": null
},
"totals": {
"requests": 5610, "executed": 5610, "hits": 2815, "misses": 2795,
"not_cacheable": 0, "unsupported_compiler": 0, "not_compile": 0,
"timeouts": 3, "read_errors": 2, "write_errors": 1, "other_errors": 0,
"compile_fails": 12, "forced_recaches": 4, "cache_writes": 2795
},
"previous": {
"requests": 5000, "executed": 5000, "hits": 2000, "misses": 3000,
"not_cacheable": 0, "unsupported_compiler": 0, "not_compile": 0,
"timeouts": 0, "read_errors": 0, "write_errors": 0, "other_errors": 0,
"compile_fails": 9, "forced_recaches": 0, "cache_writes": 3000
},
"timing": { "avg_hit_read_ms": 0.72, "avg_cache_write_ms": 310.0, "avg_compile_ms": 8050.0 },
"time_saved": {
"seconds": 11100.0, "interval_90": [9700.0, 12600.0], "hits_left_out": 7,
"note": "Low on purpose."
},
"build_times": [
{ "language": "Rust", "compiles": 3256, "mean_ms": 7780.0, "median_ms": 7100.0,
"p90_ms": 21200.0,
"bins": [
{ "from_ms": 1000.0, "to_ms": 1778.28, "compiles": 120 },
{ "from_ms": 1778.28, "to_ms": 3162.28, "compiles": 980 }
] },
{ "language": "CUDA", "compiles": 0, "mean_ms": 0.0, "median_ms": 0.0,
"p90_ms": 0.0, "bins": [] }
],
"languages": [
{ "name": "Rust", "hits": 229, "misses": 3256, "errors": 0 },
{ "name": "C/C++", "hits": 2082, "misses": 0, "errors": 0 }
],
"not_cached": [{"reason": "crate-type", "count": 621, "name": "Programs and libraries that get linked", "meaning": "m", "action": "a", "fixable": false}, {"reason": "incremental", "count": 105, "name": "n", "meaning": "m", "action": "a", "fixable": true}],
"buckets": [
{ "start": 1764290000, "hits": 10, "misses": 5, "other": 1, "errors": 0, "saved_seconds": 60.0,
"languages": [["Rust", 10, 5]], "reset": false, "gap": false },
{ "start": 1764290600, "hits": 0, "misses": 0, "other": 0, "errors": 0, "saved_seconds": 0.0,
"languages": [], "reset": false, "gap": true },
{ "start": 1764291200, "hits": 4, "misses": 4, "other": 0, "errors": 0, "saved_seconds": 30.0,
"languages": [["C/C++", 4, 4]], "reset": true, "gap": false }
],
"problems": [
{ "severity": "Warning", "title": "Rust hit rate 8%", "detail": "Most Rust compiles miss." }
],
"extras": [ { "title": "Multi-level cache", "rows": [["Levels", "2"]] } ],
"raw": { "stats": { "compile_requests": 5610 }, "version": "0.18.0" },
"summary_markdown": "**Cache:** 50%"
}"#;
#[test]
fn a_view_deserialises() {
let view: View = serde_json::from_str(SAMPLE).expect("the sample is a View");
assert_eq!(view.range, Some(Range::Day));
assert_eq!(view.totals.hit_rate(), Some(2815.0 / 5610.0));
assert_eq!(view.server.version.as_deref(), Some("0.18.0"));
assert_eq!(view.time_saved.interval_90, Some((9700.0, 12600.0)));
assert_eq!(view.build_times[0].bins[1].compiles, 980);
assert_eq!(view.build_times[1].compiles, 0);
assert_eq!((view.not_cached[0].reason.as_str(), view.not_cached[0].count), ("crate-type", 621));
assert!(view.not_cached[1].fixable);
assert_eq!(view.buckets[1].gap, true);
assert_eq!(view.extras[0].rows[0].1, "2");
}
#[test]
fn an_empty_view_deserialises() {
// Every field is present, as the server always sends them; several are empty.
let view: View = serde_json::from_str(
r#"{"range": null, "generated_at": 0, "server": {"status": "NotRunning"},
"totals": {
"requests": 0, "executed": 0, "hits": 0, "misses": 0, "not_cacheable": 0,
"unsupported_compiler": 0, "not_compile": 0, "timeouts": 0, "read_errors": 0,
"write_errors": 0, "other_errors": 0, "compile_fails": 0, "forced_recaches": 0,
"cache_writes": 0
},
"previous": null,
"timing": {
"avg_hit_read_ms": null, "avg_cache_write_ms": null, "avg_compile_ms": null
},
"time_saved": {"seconds": 0.0, "hits_left_out": 0, "note": ""},
"languages": [], "not_cached": [], "buckets": [], "problems": [], "extras": [],
"raw": null, "summary_markdown": ""}"#,
)
.expect("an empty view is still a View");
assert_eq!(view.totals.hit_rate(), None);
assert_eq!(view.time_saved.interval_90, None);
assert!(view.build_times.is_empty());
assert!(view.raw.is_null());
}
}
+5
View File
@@ -0,0 +1,5 @@
//! Entry point of the WebAssembly module; the page itself lives in the library.
fn main() {
sccache_dash_ui::open();
}
+110
View File
@@ -0,0 +1,110 @@
//! Talking to the server. One request is in flight at a time.
use std::sync::{Arc, Mutex};
use eframe::egui;
use sccache_dash_api::{Range, View};
/// A request sent to the server; its answer is picked up on a later frame.
pub struct Answer {
slot: Arc<Mutex<Option<Result<ehttp::Response, String>>>>,
}
impl Answer {
pub fn send(request: ehttp::Request, ctx: &egui::Context) -> Self {
let slot = Arc::new(Mutex::new(None));
let sink = Arc::clone(&slot);
let ctx = ctx.clone();
ehttp::fetch(request, move |result| {
if let Ok(mut sink) = sink.lock() {
*sink = Some(result);
}
ctx.request_repaint();
});
Self { slot }
}
/// The answer, once it has arrived.
pub fn take(&self) -> Option<Result<ehttp::Response, String>> {
self.slot.lock().ok().and_then(|mut slot| slot.take())
}
}
/// Ask for the view of a range.
pub fn view(range: Range) -> ehttp::Request {
ehttp::Request::get(format!("/api/view?range={}", range.code()))
}
/// Ask the server to zero sccache's counters.
pub fn zero() -> ehttp::Request {
ehttp::Request::post("/api/zero", Vec::new())
}
/// The view inside a server answer.
pub fn view_from(answer: Result<ehttp::Response, String>) -> Result<View, String> {
let response = answer?;
if !response.ok {
return Err(format!(
"the server answered {} {}{}",
response.status,
response.status_text,
body_hint(response.text())
));
}
serde_json::from_slice(&response.bytes)
.map_err(|error| format!("the server's answer could not be read ({error})"))
}
/// Whether a request that changes something was accepted.
pub fn accepted(answer: Result<ehttp::Response, String>) -> Result<(), String> {
let response = answer?;
if response.ok {
Ok(())
} else {
Err(format!(
"the server answered {} {}{}",
response.status,
response.status_text,
body_hint(response.text())
))
}
}
fn body_hint(body: Option<&str>) -> String {
let body = body.map_or("", |body| body.trim());
if body.is_empty() {
String::new()
} else {
let shown: String = body.chars().take(200).collect();
format!(": {shown}")
}
}
/// Have the browser download a file the server serves.
pub fn download(url: &str) -> Result<(), String> {
#[cfg(target_arch = "wasm32")]
{
use wasm_bindgen::JsCast;
let document = web_sys::window()
.and_then(|window| window.document())
.ok_or("the browser has no document")?;
let element = document
.create_element("a")
.map_err(|error| error.as_string().unwrap_or_default())?;
let link = element
.dyn_into::<web_sys::HtmlAnchorElement>()
.map_err(|_| "the browser could not make a download link".to_owned())?;
link.set_href(url);
link.set_attribute("download", "")
.map_err(|error| error.as_string().unwrap_or_default())?;
link.click();
Ok(())
}
#[cfg(not(target_arch = "wasm32"))]
{
let _ = url;
Err("saving files is only wired up for the browser".into())
}
}
+397
View File
@@ -0,0 +1,397 @@
//! Over time: hit rate and compile volume per bucket, with a language filter.
//! Both charts always show the whole selected range; time nothing was recorded
//! in is tinted and labelled once.
use eframe::egui::{self, Stroke, Ui};
use egui_plot::{
Bar, BarChart, CoordinatesFormatter, Corner, GridInput, GridMark, Line, LineStyle, Plot,
PlotBounds, PlotPoint, PlotPoints, PlotResponse, PlotUi, Span, VLine,
};
use sccache_dash_api::{Bucket, Range, View};
use crate::fmt;
use crate::style;
use crate::theme;
/// Hits out of the cacheable compiles; `None` when there were none.
pub fn hit_rate(hits: u64, misses: u64) -> Option<f64> {
(hits + misses > 0).then(|| hits as f64 / (hits + misses) as f64)
}
fn axes_of(view: &View, dark: bool) -> Axes {
let step = bucket_step(&view.buckets, view.range);
Axes {
window: range_window(view, step),
step,
tz: fmt::local_offset() as f64,
dark,
}
}
/// The body of the "Hit rate over time" panel.
pub fn hit_rate_panel(ui: &mut Ui, view: &View, hidden: &[String], chart_height: f32) {
let axes = axes_of(view, theme::ui(ui).dark);
hit_rate_chart(ui, view, hidden, axes, chart_height);
}
/// The body of the "Compiles over time" panel.
pub fn volume_panel(ui: &mut Ui, view: &View, hidden: &[String], chart_height: f32) {
let axes = axes_of(view, theme::ui(ui).dark);
volume_chart(ui, view, hidden, axes, chart_height);
}
/// The title of one part of a panel, in the style of a panel title.
pub fn part_title(ui: &mut Ui, text: &str) {
ui.add(egui::Label::new(theme::title(ui, text)).truncate());
}
/// Checkboxes that narrow both charts to some languages.
pub fn filter(ui: &mut Ui, view: &View, hidden: &mut Vec<String>) {
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing.x = theme::space::PANEL_GAP;
let mut all = hidden.is_empty();
if ui.checkbox(&mut all, "All languages").changed() {
*hidden = fmt::hidden_after_all(all, view.languages.iter().map(|l| l.name.as_str()));
}
for language in &view.languages {
let mut ticked = !hidden.iter().any(|name| name == &language.name);
if ui.checkbox(&mut ticked, language.name.as_str()).changed() {
if ticked {
hidden.retain(|name| name != &language.name);
} else {
hidden.push(language.name.clone());
}
}
}
});
if !hidden.is_empty() {
ui.add(
egui::Label::new(
theme::small(
ui,
"Only the chosen languages are counted. The other outcomes can't be split by \
language, so they're left out.",
),
),
);
}
}
/// How many seconds each bucket covers.
fn bucket_step(buckets: &[Bucket], range: Option<Range>) -> f64 {
let length = match range {
Some(Range::Hour) => 3_600.0,
Some(Range::Day) => 86_400.0,
Some(Range::Week) => 604_800.0,
Some(Range::Month) => 2_592_000.0,
_ => 7_200.0,
};
match buckets.len() {
0 | 1 => length / 120.0,
count => (buckets[count - 1].start - buckets[0].start) as f64 / (count - 1) as f64,
}
}
/// The whole selected range as Unix seconds (start, end): a fixed-length range
/// runs back from now by its length, whatever the buckets cover; "since reset"
/// runs from the first bucket to the last one's end.
fn range_window(view: &View, step: f64) -> (f64, f64) {
let now = view.generated_at as f64;
let (first, last) = match (view.buckets.first(), view.buckets.last()) {
(Some(first), Some(last)) => (first.start as f64, last.start as f64 + step),
_ => (now - step, now),
};
match view.range {
Some(Range::Hour) => (now - 3_600.0, now),
Some(Range::Day) => (now - 86_400.0, now),
Some(Range::Week) => (now - 604_800.0, now),
Some(Range::Month) => (now - 2_592_000.0, now),
_ => (first, last.max(first + step)),
}
}
/// The stretches of the window no recorded bucket covers.
fn unrecorded(buckets: &[Bucket], window: (f64, f64), step: f64) -> Vec<(f64, f64)> {
let mut stretches = Vec::new();
let mut cursor = window.0;
for bucket in buckets.iter().filter(|bucket| !bucket.gap) {
let (from, to) = (bucket.start as f64, bucket.start as f64 + step);
if from > cursor {
stretches.push((cursor, from));
}
cursor = cursor.max(to);
}
if cursor < window.1 {
stretches.push((cursor, window.1));
}
stretches
}
/// What both charts share.
#[derive(Clone, Copy)]
struct Axes {
/// Start and end of the range in Unix seconds.
window: (f64, f64),
/// Seconds per bucket.
step: f64,
/// Seconds to add to a Unix time to get local clock time.
tz: f64,
dark: bool,
}
/// A chart with a time axis over the whole range: clock times as ticks and a
/// readout of where the pointer is. It can't be zoomed or dragged, so the wheel
/// and a finger keep scrolling the page; that also means it can fit its data
/// afresh every frame, so new buckets are never cut off. A little air either
/// side keeps the first and last time label inside the plot.
fn time_plot<'a>(
name: &'static str,
axes: Axes,
height: f32,
readout: impl Fn(&PlotPoint) -> String + 'a,
) -> Plot<'a> {
let (first, last) = (axes.window.0 + axes.tz, axes.window.1 + axes.tz);
let span = last - first;
let air = span * theme::drawing::CHART_SIDE_AIR;
let tick = fmt::tick_step(span);
let label_font = egui::FontId::proportional(theme::px::SMALL);
let label_color = theme::of(axes.dark).muted;
let (from, to) = (first, last);
Plot::new(name)
.height(height)
.show_background(false)
.grid_color(theme::of(axes.dark).grid)
.allow_scroll(false)
.allow_drag(false)
.allow_zoom(false)
.allow_boxed_zoom(false)
.custom_x_axes(vec![egui_plot::AxisHints::new_x()
.tick_label_font(label_font.clone())
.tick_label_color(label_color)])
.custom_y_axes(vec![egui_plot::AxisHints::new_y()
.tick_label_font(label_font)
.tick_label_color(label_color)])
// The range and a little air either side, so the edge labels are not cut off.
.default_x_bounds(first - air, last + air)
.x_grid_spacer(move |input: GridInput| {
ticks(input.bounds.0, input.bounds.1, tick)
.into_iter()
.filter(|mark| mark.value >= from && mark.value <= to)
.collect()
})
.x_axis_formatter(move |mark: GridMark, _range| {
fmt::tick_label(mark.value.round() as i64, tick)
})
.coordinates_formatter(
Corner::LeftTop,
CoordinatesFormatter::new(move |point: &PlotPoint, _bounds: &PlotBounds| readout(point)),
)
.reset()
}
fn ticks(from: f64, to: f64, tick: i64) -> Vec<GridMark> {
let tick = tick.max(1);
let first = from.ceil() as i64;
let mut value = first - first.rem_euclid(tick);
let mut marks = Vec::new();
while value as f64 <= to {
marks.push(GridMark {
value: value as f64,
step_size: tick as f64,
});
value += tick;
}
marks
}
/// Resets as dashed lines, and everything unrecorded as one tinted band per stretch.
fn marks(plot: &mut PlotUi<'_>, buckets: &[Bucket], axes: Axes) {
let p = theme::of(axes.dark);
for bucket in buckets {
if bucket.reset {
plot.vline(
VLine::new("Reset", bucket.start as f64 + axes.tz)
.stroke(Stroke::new(1.5, p.warn))
.style(LineStyle::Dashed { length: 12.0 }),
);
}
}
for (from, to) in unrecorded(buckets, axes.window, axes.step) {
plot.span(
Span::new("Not recorded", (from + axes.tz)..=(to + axes.tz))
.fill(p.unrecorded)
.border_width(0.0),
);
}
}
/// Whether there is anything to mark: a reset, or time nothing was recorded in.
fn marked(buckets: &[Bucket], axes: Axes) -> (bool, bool) {
let any_reset = buckets.iter().any(|bucket| bucket.reset);
let any_gap = !unrecorded(buckets, axes.window, axes.step).is_empty();
(any_reset, any_gap)
}
fn overlay(ui: &mut Ui, chart: &PlotResponse<()>, text: &str) {
ui.painter().text(
chart.response.rect.center(),
egui::Align2::CENTER_CENTER,
text,
egui::FontId::proportional(theme::px::SMALL),
theme::ui(ui).muted,
);
}
/// Hits and misses of a bucket, for the languages that are ticked.
fn split(bucket: &Bucket, hidden: &[String]) -> (u64, u64) {
if hidden.is_empty() {
(bucket.hits, bucket.misses)
} else {
bucket
.languages
.iter()
.filter(|(name, _, _)| !hidden.contains(name))
.fold((0, 0), |(hits, misses), (_, hits_here, misses_here)| {
(hits + hits_here, misses + misses_here)
})
}
}
fn hit_rate_chart(ui: &mut Ui, view: &View, hidden: &[String], axes: Axes, height: f32) {
let p = theme::ui(ui);
// One line per stretch of buckets that have a hit rate.
let mut runs: Vec<Vec<PlotPoint>> = Vec::new();
let mut run: Vec<PlotPoint> = Vec::new();
for bucket in view.buckets.iter().filter(|bucket| !bucket.gap) {
let (hits, misses) = split(bucket, hidden);
match hit_rate(hits, misses) {
Some(rate) => run.push(PlotPoint::new(
bucket.start as f64 + axes.tz,
rate * 100.0,
)),
None if !run.is_empty() => runs.push(std::mem::take(&mut run)),
None => {}
}
}
if !run.is_empty() {
runs.push(run);
}
let plot = time_plot(
"hit-rate-chart",
axes,
height,
|point| format!("{} · {:.0}%", fmt::moment_text(point.x.round() as i64), point.y),
)
.default_y_bounds(0.0, 100.0)
// A mark every quarter, so the axis reads 0%, 25%, 50%, 75%, 100%.
.y_grid_spacer(|_: GridInput| {
(0..=4)
.map(|quarter| GridMark {
value: quarter as f64 * 25.0,
step_size: 25.0,
})
.collect()
})
.y_axis_formatter(|mark: GridMark, _| format!("{:.0}%", mark.value));
let chart = plot.show(ui, |plot| {
marks(plot, &view.buckets, axes);
for points in &runs {
plot.line(
Line::new("Hit rate", PlotPoints::Owned(points.clone()))
.color(p.from_cache)
.width(2.0),
);
}
});
if runs.is_empty() {
overlay(ui, &chart, "No cacheable compiles in this range");
}
let (any_reset, any_gap) = marked(&view.buckets, axes);
let mut entries = vec![(style::Mark::Line(p.from_cache), "Hit rate".to_owned())];
if any_reset {
entries.push((style::Mark::Dashed(p.warn), "Reset".to_owned()));
}
if any_gap {
entries.push((style::Mark::Band, "Not recorded".to_owned()));
}
style::legend(ui, entries);
}
fn volume_chart(ui: &mut Ui, view: &View, hidden: &[String], axes: Axes, height: f32) {
let p = theme::ui(ui);
// The tallest stack of one bucket, with a little air above it.
let top = view
.buckets
.iter()
.filter(|bucket| !bucket.gap)
.fold(4.0_f64, |top, bucket| {
let (hits, misses) = split(bucket, hidden);
let other = if hidden.is_empty() { bucket.other } else { 0 };
top.max((hits + misses + other) as f64 * 1.1)
});
let plot = time_plot(
"volume-chart",
axes,
height,
|point| fmt::moment_text(point.x.round() as i64),
)
.default_y_bounds(0.0, top)
.y_axis_formatter(|mark: GridMark, _| fmt::count(mark.value.max(0.0).round() as u64));
let width = axes.step * 0.8;
let (mut from_cache, mut built, mut other) = (vec![], vec![], vec![]);
let mut any = false;
for bucket in view.buckets.iter().filter(|bucket| !bucket.gap) {
let x = bucket.start as f64 + axes.tz;
let (hits, misses) = split(bucket, hidden);
for (bars, count) in [
(&mut from_cache, hits),
(&mut built, misses),
(&mut other, bucket.other),
] {
if count > 0 {
bars.push(Bar::new(x, count as f64));
any = true;
}
}
}
let chart = plot.show(ui, |plot| {
marks(plot, &view.buckets, axes);
let from_cache = BarChart::new("From cache", from_cache)
.width(width)
.color(p.from_cache);
let built = BarChart::new("Built", built)
.width(width)
.color(p.built);
let other = BarChart::new("Not cacheable and other", other)
.width(width)
.color(p.not_cacheable);
let built = built.stack_on(&[&from_cache]);
let other = other.stack_on(&[&built]);
plot.bar_chart(from_cache);
plot.bar_chart(built);
if hidden.is_empty() {
plot.bar_chart(other);
}
});
if !any {
overlay(ui, &chart, "Nothing recorded in this range");
}
let (any_reset, any_gap) = marked(&view.buckets, axes);
let mut entries = vec![
(style::Mark::Fill(p.from_cache), "From cache".to_owned()),
(style::Mark::Fill(p.built), "Built".to_owned()),
];
if hidden.is_empty() {
entries.push((style::Mark::Fill(p.not_cacheable), "Not cacheable and other".to_owned()));
}
if any_reset {
entries.push((style::Mark::Dashed(p.warn), "Reset".to_owned()));
}
if any_gap {
entries.push((style::Mark::Band, "Not recorded".to_owned()));
}
style::legend(ui, entries);
}
+77
View File
@@ -0,0 +1,77 @@
//! Problems: what is wrong, most serious first, as the list under the hero's problem
//! count. Each problem is a line (a square for how serious, its title, a chevron); clicking
//! it shows the full explanation under it, as the reasons list does. The list scrolls inside
//! a fixed height, so a longer list or an open explanation never moves the page.
use eframe::egui::{self, Sense, Ui};
use sccache_dash_api::{Severity, View};
use crate::theme;
use crate::where_went::chevron;
const ROW: f32 = 22.0;
const GAP: f32 = 8.0;
const CHEVRON: f32 = 8.0;
fn open_id(title: &str) -> egui::Id {
egui::Id::new(("problem-open", title))
}
/// The problems of `view` in a list `height` tall.
pub fn hero_list(ui: &mut Ui, view: &View, height: f32) {
let p = theme::ui(ui);
if view.problems.is_empty() {
ui.add(egui::Label::new(theme::small(ui, "Nothing needs attention.")).truncate());
return;
}
egui::ScrollArea::vertical()
.id_salt("hero-problems")
.max_height(height)
.auto_shrink([false, false])
.show(ui, |ui| {
ui.spacing_mut().item_spacing.y = 0.0;
let width = ui.available_width();
let indent = theme::drawing::SEVERITY_DOT + GAP;
for problem in &view.problems {
let id = open_id(&problem.title);
let open = ui.ctx().data(|data| data.get_temp::<bool>(id)).unwrap_or(false);
let (row, response) = ui.allocate_exact_size(egui::vec2(width, ROW), Sense::click());
let response = response.on_hover_cursor(egui::CursorIcon::PointingHand);
response.widget_info(|| {
egui::WidgetInfo::labeled(egui::WidgetType::Button, true, problem.title.as_str())
});
if response.clicked() {
ui.ctx().data_mut(|data| data.insert_temp(id, !open));
ui.ctx().request_repaint();
}
if response.hovered() {
ui.painter().rect_filled(row, theme::space::CONTROL_RADIUS, p.hover);
}
let color = match problem.severity {
Severity::Error => p.bad,
Severity::Warning => p.warn,
};
let side = theme::drawing::SEVERITY_DOT;
ui.painter().rect_filled(
egui::Rect::from_center_size(egui::pos2(row.left() + side / 2.0, row.center().y), egui::vec2(side, side)),
0.0,
color,
);
let chevron_x = row.right() - CHEVRON;
chevron(ui.painter(), egui::pos2(chevron_x + CHEVRON / 2.0, row.center().y), open, p.muted);
let title = crate::style::galley(ui, theme::body(problem.title.clone()), false, f32::INFINITY);
let room = (chevron_x - GAP - row.left() - indent).max(10.0);
let place = egui::Rect::from_min_size(egui::pos2(row.left() + indent, row.top()), egui::vec2(room, ROW));
ui.painter().with_clip_rect(place).galley(
egui::pos2(place.left(), row.center().y - title.size().y / 2.0),
title,
p.text,
);
if open {
let detail = crate::style::galley(ui, theme::small(ui, problem.detail.clone()), true, width - indent);
let (place, _) = ui.allocate_exact_size(egui::vec2(width, detail.size().y + 6.0), Sense::hover());
ui.painter().galley(egui::pos2(place.left() + indent, place.top()), detail, p.muted);
}
}
});
}
+157
View File
@@ -0,0 +1,157 @@
//! Raw counters: the sccache stats exactly as the server read them, as compact
//! key/value lines that flow in columns. The panel opens and closes; it starts
//! closed, as one line.
use std::cell::Cell;
use eframe::egui::{self, Pos2, Rect, Sense, Ui};
use sccache_dash_api::View;
use crate::style;
use crate::theme;
/// Every leaf of the JSON as its dotted path and its value as text.
fn leaves(value: &serde_json::Value, path: String, out: &mut Vec<(String, String)>) {
match value {
serde_json::Value::Object(fields) => {
for (name, value) in fields {
let path = if path.is_empty() { name.clone() } else { format!("{path}.{name}") };
leaves(value, path, out);
}
}
serde_json::Value::Array(items) => {
for (index, value) in items.iter().enumerate() {
leaves(value, format!("{path}[{index}]"), out);
}
}
leaf => out.push((
path,
match leaf {
serde_json::Value::String(text) => text.clone(),
serde_json::Value::Null => "null".to_owned(),
number => number.to_string(),
},
)),
}
}
/// How many columns of key/value lines fit in a panel's `inner` width.
fn columns(inner: f32) -> usize {
let gap = theme::space::PANEL_GAP + 4.0;
(((inner + gap) / (theme::layout::RAW_LINE_WIDTH + gap)) as usize).clamp(1, 3)
}
/// How tall the panel is when it is `width` wide: its title and, when open,
/// its lines.
pub fn height(view: &View, width: f32, open: bool) -> f32 {
let title = theme::space::ROW + theme::space::UNDER_TITLE + 2.0 * theme::space::PANEL_PAD_Y;
if !open {
return title - theme::space::UNDER_TITLE + theme::space::LINE;
}
let mut lines = 0;
if !view.raw.is_null() {
let mut out = Vec::new();
leaves(&view.raw, String::new(), &mut out);
lines = out.len();
}
let inner = width - 2.0 * theme::space::PANEL_PADDING;
title + lines.div_ceil(columns(inner)) as f32 * theme::space::ROW
}
/// The panel at `rect`; its title opens and closes it. Returns the rect it took.
pub fn section(ui: &mut Ui, view: &View, rect: Rect) -> Rect {
let id = egui::Id::new("raw-counters-open");
let open = Cell::new(ui.ctx().data_mut(|data| data.get_temp::<bool>(id)).unwrap_or(false));
let (_, taken) = style::panel_titled(
ui,
rect,
|ui| {
let mut now = open.get();
style::toggling_title(ui, "Raw counters", &mut now);
open.set(now);
},
|ui| {
let open = open.get();
ui.ctx().data_mut(|data| data.insert_temp(id, open));
if !open {
return;
}
match &view.raw {
serde_json::Value::Null => {
ui.label(theme::body("sccache's raw counters could not be read."));
}
value => {
let mut lines = Vec::new();
leaves(value, String::new(), &mut lines);
flow(ui, &lines);
}
}
},
);
taken
}
/// Key/value lines in as many columns of the raw line width as fit, filled
/// left to right and then down: each line in its own cell, the key in small
/// print and the value in mono right after it.
fn flow(ui: &mut Ui, lines: &[(String, String)]) {
let p = theme::ui(ui);
let width = ui.available_rect_before_wrap().width();
let gap = theme::space::PANEL_GAP + 4.0;
let columns = columns(width);
let cell = (width - gap * (columns - 1) as f32) / columns as f32;
let font = egui::FontId::proportional(theme::px::SMALL);
let mono = theme::number_font(theme::px::SMALL);
for line in lines.chunks(columns) {
// One exact row of cells: a row is laid out, never wrapped, so every column is used.
ui.allocate_ui_with_layout(
egui::vec2(width, theme::space::ROW),
egui::Layout::left_to_right(egui::Align::Center),
|ui| {
ui.spacing_mut().item_spacing.x = gap;
for (key, value) in line {
let (rect, response) =
ui.allocate_exact_size(egui::vec2(cell, theme::space::ROW), Sense::hover());
let painter = ui.painter();
let clip = rect.intersect(ui.clip_rect());
let value_galley = painter.layout_no_wrap(value.clone(), mono.clone(), p.text);
let value_width = value_galley.size().x;
// The value follows its key by the key/value gap, not pushed to the cell's edge;
// where the two do not fit, the key ends in "…" and all of it shows on hover.
let key_room = (rect.width() - theme::space::KEY_VALUE_GAP - value_width).max(0.0);
let key_galley = painter.layout_no_wrap(key.clone(), font.clone(), p.muted);
let key_width = key_galley.size().x;
let cut = key_width > key_room;
let key_galley = if cut {
let mut chars = key.chars().count();
loop {
chars -= 1;
let shorter: String = key.chars().take(chars).collect::<String>() + "…";
let galley = painter.layout_no_wrap(shorter, font.clone(), p.muted);
if galley.size().x <= key_room || chars <= 1 {
break galley;
}
}
} else {
key_galley
};
let key_width = key_galley.size().x;
painter.with_clip_rect(clip).galley(
Pos2::new(rect.left(), rect.center().y - key_galley.size().y / 2.0),
key_galley,
p.muted,
);
let value_left = rect.left() + key_width + theme::space::KEY_VALUE_GAP;
painter.with_clip_rect(clip).galley(
Pos2::new(value_left, rect.center().y - value_galley.size().y / 2.0),
value_galley,
p.text,
);
if cut || value_left + value_width > rect.right() {
response.on_hover_text(format!("{key} {value}"));
}
}
},
);
}
}
+210
View File
@@ -0,0 +1,210 @@
//! Speed: how long a cache fetch, a cache write and a build take on average,
//! and how build times spread for each language.
use eframe::egui::{self, Pos2, Rect, Sense, Ui};
use sccache_dash_api::{BuildTimes, View};
use crate::fmt;
use crate::style;
use crate::theme;
/// The slowest build time the axis reaches, as log10 of milliseconds (1,000 s).
const AXIS_TOP: f64 = 6.0;
/// The width of the label and of the value beside each speed bar.
const LABEL_WIDTH: f32 = 128.0;
const VALUE_WIDTH: f32 = 60.0;
pub fn section(ui: &mut Ui, view: &View) {
let p = theme::ui(ui);
let timing = view.timing;
let rows = [
("Cache fetch (a hit)", timing.avg_hit_read_ms, p.from_cache),
("Cache write", timing.avg_cache_write_ms, p.muted),
("Compile one crate", timing.avg_compile_ms, p.built),
];
for (label, ms, color) in rows {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = theme::space::ITEM;
let (label_rect, _) =
ui.allocate_exact_size(egui::vec2(LABEL_WIDTH, theme::space::ROW), Sense::hover());
let label = style::galley(ui, theme::body(label), false, f32::INFINITY);
ui.painter().with_clip_rect(label_rect).galley(
Pos2::new(label_rect.left(), label_rect.center().y - label.size().y / 2.0),
label,
p.text,
);
let text = ms.map_or("—".into(), |ms| fmt::duration(ms / 1000.0));
let value = style::galley(ui, theme::number(text), false, f32::INFINITY);
let value_rect = ui
.allocate_exact_size(egui::vec2(VALUE_WIDTH, theme::space::ROW), Sense::hover())
.0;
ui.painter().with_clip_rect(value_rect).galley(
Pos2::new(value_rect.right() - value.size().x, value_rect.center().y - value.size().y / 2.0),
value,
p.text,
);
let bar_rect = ui
.allocate_exact_size(
egui::vec2(ui.available_rect_before_wrap().width(), theme::space::ROW),
Sense::hover(),
)
.0;
let bar = Rect::from_center_size(
bar_rect.center(),
egui::vec2(bar_rect.width(), theme::drawing::SPEED_BAR),
);
style::fill_bar(ui, bar, ms.map_or(0.0, style::log_fraction), color);
});
}
let hit = timing.avg_hit_read_ms;
let write = timing.avg_cache_write_ms;
let build = timing.avg_compile_ms;
let sentence = if let Some(times) = faster(build, hit) {
format!("A cache hit is about {times}x faster than compiling the crate.")
} else if let Some(times) = faster(build, write) {
format!("Writing to the cache is about {times}x faster than compiling the crate.")
} else {
"There are no timings to compare in this range.".to_owned()
};
ui.add_space(theme::space::ITEM);
ui.add(egui::Label::new(theme::strong(sentence).color(p.hero)).wrap());
ui.add(
egui::Label::new(
theme::small(
ui,
"The bars use a log scale, so a fraction of a millisecond and several seconds are \
both visible.",
),
),
);
build_times(ui, view);
}
/// `faster` is about how many times shorter than `slower`, when both are known and positive.
fn faster(slower: Option<f64>, faster: Option<f64>) -> Option<String> {
let (slower, faster) = (slower?, faster?);
(slower > 0.0 && faster > 0.0).then(|| fmt::round_number(slower / faster))
}
/// "How long one crate takes to compile": one histogram per language, all on the
/// same log scale of build time, with the mean, median and p90 marked.
fn build_times(ui: &mut Ui, view: &View) {
let p = theme::ui(ui);
let languages: Vec<&BuildTimes> = view
.build_times
.iter()
.filter(|times| times.compiles > 0 && !times.bins.is_empty())
.collect();
if languages.is_empty() {
return;
}
ui.add_space(theme::space::BETWEEN_PARTS);
crate::overtime::part_title(ui, "How long one crate takes to compile");
// One shared axis, from a quarter step before the fastest bin to a quarter step after the slowest.
let (mut low, mut high) = (f64::MAX, 0.0_f64);
for times in &languages {
for bin in &times.bins {
low = low.min(bin.from_ms);
high = high.max(bin.to_ms);
}
}
let low = (low.max(1.0).log10() - 0.25).max(0.0);
let high = (high.log10() + 0.25).min(AXIS_TOP);
for times in languages {
ui.add_space(theme::space::ITEM);
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = theme::space::ITEM;
ui.add(egui::Label::new(theme::strong(times.language.clone())).truncate());
ui.add(egui::Label::new(theme::small(ui, format!("{} compiles", fmt::count(times.compiles)))).truncate());
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.spacing_mut().item_spacing.x = theme::space::ITEM;
for (name, value, color) in [
("p90", times.p90_ms, p.p90),
("median", times.median_ms, p.median),
("mean", times.mean_ms, p.mean),
] {
ui.label(theme::small(ui, format!("{name} {}", ms(value))).color(color));
}
});
});
histogram(ui, times, low, high, p);
axis(ui, low, high);
}
ui.add(
egui::Label::new(
theme::small(
ui,
"Each point is the average of the builds that finished within one 10-second reading.",
),
),
);
}
fn ms(value: f64) -> String {
fmt::duration(value / 1000.0)
}
/// The bins as bars, build time along the bottom on a log scale, with a line
/// for the mean, median and p90.
fn histogram(ui: &mut Ui, times: &BuildTimes, low: f64, high: f64, p: &theme::Palette) {
let width = ui.available_rect_before_wrap().width();
let (rect, response) = ui.allocate_exact_size(
egui::vec2(width, theme::drawing::BUILD_HISTOGRAM),
Sense::hover(),
);
let painter = ui.painter();
painter.hline(rect.x_range(), rect.bottom() - 0.5, egui::Stroke::new(1.0, p.grid));
let at = |value: f64| {
let position = ((value.max(1.0).log10() - low) / (high - low)).clamp(0.0, 1.0);
rect.left() + rect.width() * position as f32
};
let top = times.bins.iter().map(|bin| bin.compiles).max().unwrap_or(0);
for bin in &times.bins {
if bin.compiles == 0 {
continue;
}
let height = theme::drawing::BUILD_HISTOGRAM * bin.compiles as f32 / top.max(1) as f32;
let bar = Rect::from_min_max(
Pos2::new(at(bin.from_ms), rect.bottom() - height),
Pos2::new((at(bin.to_ms) - 1.0).max(at(bin.from_ms) + 1.0), rect.bottom()),
);
painter.rect_filled(bar, 1.0, p.built);
}
for (value, color) in [times.mean_ms, times.median_ms, times.p90_ms].into_iter().zip([p.mean, p.median, p.p90]) {
let x = at(value);
painter.rect_filled(
Rect::from_min_max(Pos2::new(x, rect.top()), Pos2::new(x + 2.0, rect.bottom())),
0.0,
color,
);
}
response.on_hover_text(format!(
"{} builds: mean {}, median {}, p90 {}",
fmt::count(times.compiles),
ms(times.mean_ms),
ms(times.median_ms),
ms(times.p90_ms)
));
}
/// The times along the bottom of a histogram: one mark every tenfold step.
fn axis(ui: &mut Ui, low: f64, high: f64) {
let p = theme::ui(ui);
let width = ui.available_rect_before_wrap().width();
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, theme::drawing::BUILD_AXIS), Sense::hover());
let font = egui::FontId::proportional(theme::px::SMALL);
for step in 0..=AXIS_TOP as i64 {
let value = step as f64;
if value < low || value > high {
continue;
}
let x = rect.left() + rect.width() * ((value - low) / (high - low)) as f32;
let text = ms(10.0_f64.powf(value));
let galley = ui.painter().layout_no_wrap(text, font.clone(), p.muted);
let x = x.clamp(rect.left(), rect.right() - galley.size().x);
ui.painter().galley(Pos2::new(x, rect.center().y - galley.size().y / 2.0), galley, p.muted);
}
}
+630
View File
@@ -0,0 +1,630 @@
//! Drawings shared by the panels: the grid, panels, cards, tables, bars and
//! chart keys. Every colour and size comes from [`crate::theme`].
use std::sync::Arc;
use eframe::egui::{self, Align, Align2, Color32, Galley, Layout, Pos2, Rect, RichText, Sense, Shape, Stroke, StrokeKind, Ui};
use egui::TextWrapMode;
use crate::theme::{self, px, space};
/// The palette of the theme being drawn.
pub fn p(ui: &Ui) -> &'static theme::Palette {
theme::ui(ui)
}
/// The width of `text` in `font`.
pub fn text_width(ui: &Ui, text: &str, font: egui::FontId) -> f32 {
ui.painter()
.layout_no_wrap(text.to_owned(), font, theme::ui(ui).text)
.size()
.x
}
/// Lay `text` out: on one line, or wrapped at `width` when `wrap` is set.
pub fn galley(ui: &Ui, text: RichText, wrap: bool, width: f32) -> Arc<Galley> {
egui::WidgetText::from(text).into_galley(
ui,
Some(if wrap { TextWrapMode::Wrap } else { TextWrapMode::Extend }),
width,
egui::FontSelection::Default,
)
}
/// A colour made see-through.
pub fn tint(color: Color32, share: f32) -> Color32 {
theme::tint(color, share)
}
// ---- The grid ----
/// How wide a panel is that spans `span` of the `columns` columns of a row.
pub fn span_width(ui: &Ui, columns: usize, span: usize) -> f32 {
let all = ui.available_rect_before_wrap().width();
span_of(all, columns, span)
}
/// The same, from the row's width instead of a `Ui`.
pub fn span_of(row_width: f32, columns: usize, span: usize) -> f32 {
let gaps = space::PANEL_GAP;
let one = (row_width - gaps * (columns as f32 - 1.0)) / columns as f32;
one * span as f32 + gaps * (span as f32 - 1.0)
}
/// Where the panels of a row go: one rectangle per entry of `spans` (each the
/// number of columns the panel spans), all `height` tall, starting at the
/// cursor. Nothing is allocated yet; [`end_row`] does that.
pub fn cells(ui: &Ui, height: f32, spans: &[usize]) -> Vec<Rect> {
let columns: usize = spans.iter().sum();
let top_left = ui.cursor().min;
let mut left = top_left.x;
spans
.iter()
.map(|span| {
let width = span_width(ui, columns, *span);
let rect = Rect::from_min_size(Pos2::new(left, top_left.y), egui::vec2(width, height));
left += width + space::PANEL_GAP;
rect
})
.collect()
}
/// Close a row of panels drawn at `rects`: the cursor moves below the tallest.
pub fn end_row(ui: &mut Ui, rects: &[Rect]) {
let bottom = crate::fmt::lowest(rects.iter().map(|rect| rect.bottom()), ui.cursor().top());
let left = rects.first().map_or(ui.cursor().left(), |rect| rect.left());
ui.allocate_rect(
Rect::from_min_max(Pos2::new(left, ui.cursor().top()), Pos2::new(ui.cursor().right(), bottom)),
Sense::hover(),
);
ui.add_space(space::PANEL_GAP);
}
/// A hairline across the panel at the cursor.
pub fn rule(ui: &mut Ui) {
let (rect, _) = ui.allocate_exact_size(
egui::vec2(ui.available_rect_before_wrap().width(), 1.0),
Sense::hover(),
);
ui.painter()
.hline(rect.x_range(), rect.top() + 0.5, Stroke::new(1.0, p(ui).border));
}
// ---- Panels and cards ----
/// A panel with a title, at `rect`: no fill and no box, a hairline across its top.
/// It comes out at least as tall as `rect`; the rect it took is returned second.
pub fn panel<R>(ui: &mut Ui, rect: Rect, title: &str, body: impl FnOnce(&mut Ui) -> R) -> (R, Rect) {
let text = theme::title(ui, title).text().to_owned();
panel_titled(
ui,
rect,
|ui| {
ui.add(egui::Label::new(theme::title(ui, text)).truncate());
},
body,
)
}
/// [`panel`] with the title drawn by `title`: one line, `UNDER_TITLE` under it.
pub fn panel_titled<R>(
ui: &mut Ui,
rect: Rect,
title: impl FnOnce(&mut Ui),
body: impl FnOnce(&mut Ui) -> R,
) -> (R, Rect) {
let p = p(ui);
let pad = egui::vec2(space::PANEL_PADDING, space::PANEL_PAD_Y);
let mut inner = ui.new_child(
egui::UiBuilder::new()
.max_rect(rect.shrink2(pad))
.layout(Layout::top_down(Align::Min)),
);
inner.set_width((rect.width() - 2.0 * pad.x).max(0.0));
inner.set_min_height((rect.height() - 2.0 * pad.y).max(0.0));
inner.spacing_mut().item_spacing = egui::vec2(space::ITEM, space::LINE);
title(&mut inner);
inner.add_space(space::UNDER_TITLE);
let value = body(&mut inner);
let taken = inner.min_rect().expand2(pad);
ui.painter().hline(taken.x_range(), taken.top() + 0.5, Stroke::new(1.0, p.border));
(value, taken)
}
/// A message that must be noticed: the bad colour as a tint and a border, on
/// the panel colour.
pub fn banner(ui: &mut Ui, text: RichText, color: Color32) {
let p = p(ui);
let width = ui.available_rect_before_wrap().width();
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, 40.0), Sense::hover());
ui.painter().rect(
rect,
space::CONTROL_RADIUS,
tint(color, 0.14),
Stroke::new(1.0, tint(color, 0.5)),
StrokeKind::Inside,
);
let galley = galley(
ui,
text.strong().font(theme::semibold(px::BODY)),
true,
width - 2.0 * space::PANEL_PADDING,
);
ui.painter().galley(
Pos2::new(rect.left() + space::PANEL_PADDING, rect.center().y - galley.size().y / 2.0),
galley,
p.text,
);
}
/// The title of a panel that opens and closes when clicked. `open` is read and
/// written through `toggle`; returns whether it is open after the click.
pub fn toggling_title(ui: &mut Ui, title: &str, open: &mut bool) -> bool {
let p = p(ui);
let width = ui.available_rect_before_wrap().width();
let (rect, response) = ui.allocate_exact_size(egui::vec2(width, space::ROW), Sense::click());
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, title));
if response.clicked() {
*open = !*open;
}
let painter = ui.painter();
let color = if response.hovered() { p.text } else { p.muted };
let galley = galley(ui, theme::title(ui, title).color(color), false, f32::INFINITY);
painter.galley(
Pos2::new(rect.left(), rect.center().y - galley.size().y / 2.0),
galley,
color,
);
// A small chevron at the right: down when open, right when closed.
let at = Pos2::new(rect.right() - 4.0, rect.center().y);
let stroke = Stroke::new(1.5, p.muted);
let points = if *open {
vec![
Pos2::new(at.x - 4.0, at.y - 2.0),
at,
Pos2::new(at.x + 4.0, at.y - 2.0),
]
} else {
vec![
Pos2::new(at.x - 2.0, at.y - 4.0),
at,
Pos2::new(at.x - 2.0, at.y + 4.0),
]
};
painter.add(Shape::line(points, stroke));
*open
}
/// One cell of the counter strip: a small upper-case label, the number in mono, one line of
/// small print and the change against the period before. Exactly `rect`; a hairline stands at
/// its left unless it is the first of its row.
pub fn card(ui: &mut Ui, rect: Rect, first: bool, label: &str, number: &str, detail: &str, change: RichText, color: Color32) {
let p = p(ui);
ui.allocate_rect(rect, Sense::hover());
let inset = if first { 0.0 } else { 16.0 };
if !first {
ui.painter().vline(rect.left() + 0.5, rect.y_range().shrink(10.0), Stroke::new(1.0, p.grid));
}
let inner_rect = Rect::from_min_max(
Pos2::new(rect.left() + inset, rect.top() + 10.0),
Pos2::new(rect.right() - 8.0, rect.bottom() - 6.0),
);
let mut inner = ui.new_child(egui::UiBuilder::new().max_rect(inner_rect).layout(Layout::top_down(Align::Min)));
inner.set_width(inner_rect.width());
inner.spacing_mut().item_spacing = egui::vec2(space::ITEM, 1.0);
inner.add(egui::Label::new(theme::title(ui, label)).truncate());
inner.add(
egui::Label::new(
RichText::new(number)
.font(theme::number_font(px::CARD_NUMBER))
.color(color),
)
.truncate(),
);
let detail_label = inner.add(egui::Label::new(theme::small(ui, detail)).truncate());
if !detail.is_empty() {
detail_label.on_hover_text(detail);
}
inner.add(egui::Label::new(change).truncate());
}
// ---- Controls ----
/// One segmented control: `labels` side by side in one pill, the `chosen` one
/// marked with the accent. Returns the segment that was clicked.
pub fn segmented(ui: &mut Ui, id_salt: &'static str, labels: &[&str], chosen: usize) -> Option<usize> {
let p = p(ui);
let font = theme::medium(px::BODY);
let widths: Vec<f32> = labels
.iter()
.map(|label| text_width(ui, label, font.clone()) + 2.0 * space::CONTROL_PAD)
.collect();
let total: f32 = widths.iter().sum();
let (rect, _) = ui.allocate_exact_size(egui::vec2(total, space::CONTROL_HEIGHT), Sense::hover());
let painter = ui.painter();
painter.rect(
rect,
space::CONTROL_RADIUS,
p.track,
Stroke::new(1.0, p.border),
StrokeKind::Inside,
);
let mut left = rect.left();
let mut clicked = None;
for (index, (label, width)) in labels.iter().zip(&widths).enumerate() {
let segment = Rect::from_min_max(Pos2::new(left, rect.top()), Pos2::new(left + width, rect.bottom()));
let response = ui
.interact(segment, ui.scope_id().with(id_salt).with(index), Sense::click())
.on_hover_cursor(egui::CursorIcon::PointingHand);
let selected = index == chosen;
let fill = if selected {
p.accent
} else if response.hovered() {
p.hover
} else {
Color32::TRANSPARENT
};
if selected || response.hovered() {
painter.rect_filled(segment.shrink2(egui::vec2(1.0, 1.0)), space::CONTROL_RADIUS - 2.0, fill);
}
if index > 0 && !selected && index - 1 != chosen {
painter.vline(segment.left() + 0.5, segment.y_range().shrink(7.0), Stroke::new(1.0, p.border));
}
let color = if selected {
p.on_accent
} else if response.hovered() {
p.text
} else {
p.muted
};
painter.text(segment.center(), Align2::CENTER_CENTER, *label, font.clone(), color);
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, selected, *label));
if response.clicked() {
clicked = Some(index);
}
left += width;
}
clicked
}
// ---- Tables ----
/// What one cell of a [`table`] holds.
pub enum Cell {
Text(RichText),
/// A colour square, then text: the entry of a legend.
Marked(Color32, RichText),
/// A hit-rate bar for `hits` out of `hits + misses`; its column is fixed width.
Bar(u64, u64),
}
/// A table that lives inside its panel: columns as wide as what they hold, the
/// first column taking the slack; numbers in mono, right-aligned when the head
/// is; rows 24 px, a hairline between them; the head in the panel-title style.
/// A cell whose text does not fit is cut, and shows all of it on hover.
pub fn table(ui: &mut Ui, head: &[&str], rows: &[Vec<Cell>]) {
let p = p(ui);
let width = ui.available_rect_before_wrap().width();
let columns = head.len().max(rows.first().map_or(0, |row| row.len()));
let pad = space::CELL_PAD;
let title_font = theme::title_font();
let mut natural: Vec<f32> = head
.iter()
.map(|text| {
text_width(ui, &text.to_uppercase(), title_font.clone()) + 2.0 * pad
+ text.chars().count() as f32 * space::TITLE_SPACING
})
.collect();
natural.resize(columns, 0.0);
let mut galleys: Vec<Vec<(Option<Arc<Galley>>, String)>> = Vec::with_capacity(rows.len());
for row in rows {
let mut line = Vec::with_capacity(columns);
for (column, cell) in row.iter().enumerate() {
match cell {
Cell::Marked(_, text) | Cell::Text(text) => {
let galley = galley(ui, text.clone(), false, f32::INFINITY);
let mark = if matches!(cell, Cell::Marked(..)) {
theme::drawing::LEGEND_SWATCH + 6.0
} else {
0.0
};
natural[column] = natural[column].max(galley.size().x + 2.0 * pad + mark);
line.push((Some(galley), text.text().to_owned()));
}
Cell::Bar(..) => {
natural[column] = natural[column].max(theme::drawing::HIT_BAR + 2.0 * pad);
line.push((None, String::new()));
}
}
}
galleys.push(line);
}
// The label column takes the slack, and gives first when the table is too
// wide (after a bar column, which can shrink to a stub).
// The table reaches `pad` past both edges, so the first column's text and the last
// column's numbers line up with the panel's own edges.
let width_cells = width + 2.0 * pad;
let whole: f32 = natural.iter().sum();
let slack = width_cells - whole;
if slack >= 0.0 {
natural[0] += slack;
} else {
let bar = rows.first().and_then(|row| {
row.iter().position(|cell| matches!(cell, Cell::Bar(..)))
});
let mut missing = -slack;
if let Some(bar) = bar {
let give = missing.min((natural[bar] - 28.0).max(0.0));
natural[bar] -= give;
missing -= give;
}
let give = missing.min((natural[0] - 2.0 * pad - space::LABEL_MIN).max(0.0));
natural[0] -= give;
missing -= give;
if missing > 0.0 && whole > 0.0 {
for size in &mut natural {
*size -= missing * *size / whole;
}
}
}
let lefts: Vec<f32> = natural
.iter()
.scan(ui.cursor().left() - pad, |left, size| {
let at = *left;
*left += size;
Some(at)
})
.collect();
let height = space::ROW * (rows.len() + usize::from(!head.is_empty())) as f32;
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, height), Sense::hover());
let painter = ui.painter().with_clip_rect(rect);
let cell_rect = |column: usize, top: f32| {
Rect::from_min_max(
Pos2::new(lefts[column], top),
Pos2::new(lefts[column] + natural[column], top + space::ROW),
)
};
let put = |ui: &mut Ui, place: Rect, galley: &Arc<Galley>, text: &str, right: bool, id: egui::Id| {
let fits = galley.size().x + 2.0 * pad <= place.width() + 0.5;
let x = if right { place.right() - pad - galley.size().x } else { place.left() + pad };
let pos = Pos2::new(x, place.center().y - galley.size().y / 2.0);
let clip = place.intersect(ui.clip_rect());
ui.painter().with_clip_rect(clip).galley(pos, galley.clone(), p.text);
if !fits {
ui.interact(place, id, Sense::hover()).on_hover_text(text.to_owned());
}
};
let mut top = rect.top();
if !head.is_empty() {
for (column, text) in head.iter().enumerate() {
let place = cell_rect(column, top);
if text.is_empty() {
continue;
}
let galley = ui.painter().layout_no_wrap(text.to_uppercase(), title_font.clone(), p.muted);
put(ui, place, &galley, text, column > 0, ui.scope_id().with(("head", column)));
}
painter.hline(rect.x_range(), top.round() + space::ROW + 0.5, Stroke::new(1.0, p.border));
top += space::ROW;
}
// The rows start under the head, or at the top when there is none.
let first = top;
for (index, (row, line)) in rows.iter().zip(&galleys).enumerate() {
top = first + index as f32 * space::ROW;
if index + 1 < rows.len() {
painter.hline(rect.x_range(), top.round() + space::ROW + 0.5, Stroke::new(1.0, p.grid));
}
for (column, cell) in row.iter().enumerate() {
let place = cell_rect(column, top);
match cell {
Cell::Text(_) => {
let (galley, text) = &line[column];
if let Some(galley) = galley {
put(ui, place, galley, text, column > 0, ui.scope_id().with(("cell", index, column)));
}
}
Cell::Marked(color, _) => {
let side = theme::drawing::LEGEND_SWATCH;
let square = Rect::from_center_size(
Pos2::new(place.left() + pad + side / 2.0, place.center().y),
egui::vec2(side, side),
);
ui.painter().rect_filled(square, 0.0, *color);
let (galley, text) = &line[column];
if let Some(galley) = galley {
let text_place = Rect::from_min_max(
Pos2::new(place.left() + pad + side + 6.0, place.top()),
place.max,
);
put(ui, text_place, galley, text, false, ui.scope_id().with(("cell", index, column)));
}
}
Cell::Bar(hits, misses) => {
// As wide as its column, which shrinks before the text does.
let bar = Rect::from_min_size(
Pos2::new(place.left() + pad, place.center().y - theme::drawing::HIT_BAR_HEIGHT / 2.0),
egui::vec2((place.width() - 2.0 * pad).max(0.0), theme::drawing::HIT_BAR_HEIGHT),
);
hit_bar(ui, bar, *hits, *misses);
}
}
}
}
}
/// A bar filled from the left to `fraction` of its width (0 to 1), always `height` tall.
pub fn meter(ui: &mut Ui, height: f32, fraction: f64, fill: Color32) {
let width = ui.available_rect_before_wrap().width();
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, height), Sense::hover());
fill_bar(ui, rect, fraction, fill);
}
/// The same, in a rectangle already chosen.
pub fn fill_bar(ui: &mut Ui, rect: Rect, fraction: f64, fill: Color32) {
let p = p(ui);
let painter = ui.painter();
painter.rect_filled(rect, 0.0, p.track);
let width = rect.width() * fraction.clamp(0.0, 1.0) as f32;
if width > 0.5 {
painter.rect_filled(
Rect::from_min_max(rect.min, Pos2::new(rect.left() + width, rect.bottom())),
0.0,
fill,
);
}
}
/// One bar split into coloured parts. The parts fill the whole width when
/// their counts add up to `total`; a part with no count gets no width. What
/// each part holds shows on hover.
pub fn stacked_bar(ui: &mut Ui, parts: &[(&'static str, u64, Color32)], total: u64) {
let p = p(ui);
let width = ui.available_rect_before_wrap().width();
let (rect, response) = ui.allocate_exact_size(
egui::vec2(width, theme::drawing::STACKED_BAR),
Sense::hover(),
);
let painter = ui.painter();
painter.rect_filled(rect, 0.0, p.track);
let mut x = rect.left();
let mut tip = String::new();
for (name, part, color) in parts {
let width = if total > 0 { rect.width() * *part as f64 as f32 / total as f32 } else { 0.0 };
if width > 0.0 {
let part_rect = Rect::from_min_max(Pos2::new(x, rect.top()), Pos2::new(x + width, rect.bottom()));
painter.rect_filled(part_rect, 0.0, *color);
x += width;
tip.push_str(&format!(
"{name}: {} ({})\n",
crate::fmt::count(*part),
crate::fmt::share(*part, total)
));
}
}
if !tip.is_empty() {
response.on_hover_text(tip.trim_end());
}
}
/// A short bar showing hits (in the "from cache" colour) against misses.
pub fn hit_bar(ui: &mut Ui, rect: Rect, hits: u64, misses: u64) {
let p = p(ui);
let painter = ui.painter();
painter.rect_filled(rect, 0.0, p.track);
let total = hits + misses;
if total > 0 {
let hit_width = rect.width() * hits as f32 / total as f32;
painter.rect_filled(
Rect::from_min_max(rect.min, Pos2::new(rect.left() + hit_width, rect.bottom())),
0.0,
p.from_cache,
);
}
}
/// A trend line one point per bucket, drawn in a strip `height` tall. `None`
/// points break the line, so a gap never looks like a zero. `top` is the value
/// drawn at the top of the strip.
pub fn sparkline(ui: &mut Ui, height: f32, values: &[Option<f64>], top: f64, color: Color32) {
let p = p(ui);
let width = ui.available_rect_before_wrap().width();
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, height), Sense::hover());
let painter = ui.painter();
painter.hline(rect.x_range(), rect.bottom() - 0.5, Stroke::new(1.0, p.grid));
if values.is_empty() || top <= 0.0 {
return;
}
let at = |index: usize, value: f64| {
Pos2::new(
rect.left() + rect.width() * ((index as f32 + 0.5) / values.len() as f32),
rect.bottom() - (rect.height() * (value / top) as f32).min(rect.height()),
)
};
let mut run: Vec<Pos2> = Vec::new();
let flush = |run: &mut Vec<Pos2>, painter: &egui::Painter| match run.len() {
0 => {}
1 => {
painter.circle_filled(run[0], 2.0, color);
run.clear();
}
_ => {
painter.add(Shape::line(std::mem::take(run), Stroke::new(1.5, color)));
}
};
for (index, value) in values.iter().enumerate() {
match value {
Some(value) => run.push(at(index, *value)),
None => flush(&mut run, painter),
}
}
flush(&mut run, painter);
}
/// Where a value between a tenth of a millisecond and 100 seconds sits on a
/// scale that lets 0.7 ms and 8 s both be seen.
pub fn log_fraction(ms: f64) -> f64 {
const LOW: f64 = -1.0;
const HIGH: f64 = 5.0;
if !ms.is_finite() || ms <= 0.0 {
return 0.0;
}
let position = (ms.log10() - LOW) / (HIGH - LOW);
position.clamp(0.02, 1.0)
}
// ---- Chart keys ----
/// What an entry of a chart's key stands for.
pub enum Mark {
/// A bar.
Fill(Color32),
/// A line.
Line(Color32),
/// A dashed line: a reset.
Dashed(Color32),
/// Time nothing was recorded in.
Band,
}
/// The swatch for one entry of a chart's key.
pub fn key(ui: &mut Ui, mark: Mark) {
let p = p(ui);
let (rect, _) = ui.allocate_exact_size(
egui::vec2(theme::drawing::KEY_SWATCH, theme::drawing::KEY_SWATCH),
Sense::hover(),
);
let painter = ui.painter();
let left = Pos2::new(rect.left(), rect.center().y);
let right = Pos2::new(rect.right(), rect.center().y);
match mark {
Mark::Fill(color) => {
painter.rect_filled(rect.shrink(3.0), 2.0, color);
}
Mark::Line(color) => {
painter.add(Shape::line(vec![left, right], Stroke::new(2.0, color)));
}
Mark::Dashed(color) => {
painter.add(Shape::dashed_line(&[left, right], Stroke::new(1.5, color), 4.0, 3.0));
}
Mark::Band => {
painter.rect_filled(rect.shrink(3.0), 2.0, p.unrecorded);
painter.rect_stroke(rect.shrink(3.0), 2.0, Stroke::new(1.0, p.border), StrokeKind::Inside);
}
}
}
/// The key to a chart, drawn under it so it never sits on the data.
pub fn legend(ui: &mut Ui, entries: Vec<(Mark, String)>) {
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing.x = 14.0;
for (mark, text) in entries {
key(ui, mark);
let response = ui.add(egui::Label::new(theme::small(ui, text.clone())).truncate());
response.on_hover_text(text);
}
});
}
+444
View File
@@ -0,0 +1,444 @@
//! Every colour, size, spacing and font of the page, in one place. A change of
//! taste is an edit in this file and nowhere else.
//!
//! The type is Inter and JetBrains Mono (both under the SIL Open Font License;
//! the licence files sit beside the font files in `assets/`).
use eframe::egui::{self, Color32, FontFamily, FontId, RichText, TextStyle};
pub static INTER_REGULAR_TTF: &[u8] = include_bytes!("../assets/Inter-Regular.ttf");
pub static INTER_MEDIUM_TTF: &[u8] = include_bytes!("../assets/Inter-Medium.ttf");
pub static INTER_SEMIBOLD_TTF: &[u8] = include_bytes!("../assets/Inter-SemiBold.ttf");
pub static MONO_REGULAR_TTF: &[u8] = include_bytes!("../assets/JetBrainsMono-Regular.ttf");
pub static MONO_MEDIUM_TTF: &[u8] = include_bytes!("../assets/JetBrainsMono-Medium.ttf");
const fn rgb(hex: u32) -> Color32 {
Color32::from_rgb((hex >> 16) as u8, (hex >> 8) as u8, hex as u8)
}
/// The colours of one theme. State colours (`good`, `warn`, `bad`) are used
/// only for state; the series colours only for the five outcomes of a compile.
#[derive(Clone, Copy, Debug)]
pub struct Palette {
pub dark: bool,
pub page: Color32,
pub panel: Color32,
pub border: Color32,
pub text: Color32,
pub muted: Color32,
/// Hairlines inside a panel: between table rows and across a chart.
pub grid: Color32,
/// The recessed track of a bar, and of a control.
pub track: Color32,
/// A control under the pointer.
pub hover: Color32,
pub good: Color32,
pub warn: Color32,
pub bad: Color32,
pub from_cache: Color32,
pub built: Color32,
pub not_cacheable: Color32,
pub unsupported: Color32,
pub not_compile: Color32,
/// Selected controls.
pub accent: Color32,
/// Text on the accent: what a selected control says.
pub on_accent: Color32,
/// Amber as text and lines: the hero figures and key lines (darker in the light theme to pass contrast).
pub hero: Color32,
/// The tint over time nothing was recorded in.
pub unrecorded: Color32,
/// The line of the mean, the median and the p90 on a build-time histogram.
pub mean: Color32,
pub median: Color32,
pub p90: Color32,
}
pub const DARK: Palette = Palette {
dark: true,
page: rgb(0x0f0f10),
panel: rgb(0x161617),
border: rgb(0x2a2a2c),
text: rgb(0xe8e6e1),
muted: rgb(0x8f8d87),
grid: rgb(0x1f1f21),
track: rgb(0x1b1b1d),
hover: rgb(0x1f1f21),
good: rgb(0x3ecf8e),
warn: rgb(0xffb000),
bad: rgb(0xff5f56),
from_cache: rgb(0x3ecf8e),
built: rgb(0x5b8def),
not_cacheable: rgb(0x8a8a8f),
unsupported: rgb(0x5f5f64),
not_compile: rgb(0x424246),
accent: rgb(0xffb000),
on_accent: rgb(0x0f0f10),
hero: rgb(0xffb000),
unrecorded: Color32::from_rgba_premultiplied(14, 14, 14, 14),
mean: rgb(0xe8e6e1),
median: rgb(0xffb000),
p90: rgb(0x8a8a8f),
};
pub const LIGHT: Palette = Palette {
dark: false,
page: rgb(0xf6f3ec),
panel: rgb(0xfffdf8),
border: rgb(0xd5cfc1),
text: rgb(0x1d1b17),
muted: rgb(0x6a655b),
grid: rgb(0xe6e1d6),
track: rgb(0xebe6da),
hover: rgb(0xe9e4d8),
good: rgb(0x1a8f5a),
warn: rgb(0xb87400),
bad: rgb(0xc62f26),
from_cache: rgb(0x1f9d63),
built: rgb(0x2f63d0),
not_cacheable: rgb(0x7a766c),
unsupported: rgb(0xa39f94),
not_compile: rgb(0xc2beb2),
accent: rgb(0xffb000),
on_accent: rgb(0x1d1b17),
hero: rgb(0x8a5600),
unrecorded: Color32::from_rgba_premultiplied(0, 0, 0, 16),
mean: rgb(0x1d1b17),
median: rgb(0x8a5600),
p90: rgb(0x7a766c),
};
/// The palette of the theme being drawn.
pub fn of(dark: bool) -> &'static Palette {
if dark {
&DARK
} else {
&LIGHT
}
}
/// The palette of the theme `ctx` is drawing in.
pub fn ctx(ctx: &egui::Context) -> &'static Palette {
of(ctx.theme() == egui::Theme::Dark)
}
/// The palette of the theme `ui` is drawing in.
pub fn ui(ui: &egui::Ui) -> &'static Palette {
ctx(ui.ctx())
}
/// A colour made see-through: `color` over the panel at `share` of its strength.
pub fn tint(color: Color32, share: f32) -> Color32 {
let alpha = (share.clamp(0.0, 1.0) * 255.0).round() as u8;
Color32::from_rgba_premultiplied(color.r(), color.g(), color.b(), alpha)
}
/// Font sizes in pixels. There are no others.
pub mod px {
/// Panel titles, table heads and small labels: upper case, letter-spaced.
pub const TITLE: f32 = 11.0;
/// Text, and the controls.
pub const BODY: f32 = 13.0;
/// Small print.
pub const SMALL: f32 = 11.0;
/// The number on a stat card.
pub const CARD_NUMBER: f32 = 22.0;
/// The three figures of the headline panel.
pub const HEADLINE: f32 = 56.0;
}
/// Space in pixels.
pub mod space {
pub const PAGE_MARGIN: f32 = 16.0;
/// Between panels, and between cards.
pub const PANEL_GAP: f32 = 24.0;
/// Between the controls of the top bar.
pub const TOOL_GAP: f32 = 8.0;
/// Panels have no side padding: their content lines up with the hairline above it.
pub const PANEL_PADDING: f32 = 0.0;
/// Room between a panel's top hairline and its title, and under its content.
pub const PANEL_PAD_Y: f32 = 12.0;
pub const PANEL_RADIUS: f32 = 0.0;
pub const CONTROL_RADIUS: f32 = 2.0;
/// Between items that follow each other in a panel.
pub const ITEM: f32 = 8.0;
/// Between lines of one paragraph.
pub const LINE: f32 = 3.0;
/// One table row.
pub const ROW: f32 = 24.0;
/// Space either side of the text in a table cell.
pub const CELL_PAD: f32 = 8.0;
/// The narrowest the label column of a table gets before its text is cut.
pub const LABEL_MIN: f32 = 72.0;
pub const CONTROL_HEIGHT: f32 = 24.0;
pub const CONTROL_PAD: f32 = 9.0;
pub const TITLE_SPACING: f32 = 0.8;
pub const TOOLBAR_NOTE_WIDTH: f32 = 150.0;
/// Between a raw counter's key and its value.
pub const KEY_VALUE_GAP: f32 = 16.0;
/// Room under a title before the panel's content.
pub const UNDER_TITLE: f32 = 8.0;
/// Room between titled parts of one panel.
pub const BETWEEN_PARTS: f32 = 14.0;
}
/// How the page is laid out, in pixels of window width.
pub mod layout {
/// From this width the page has three columns of panels.
pub const THREE_COLUMNS_FROM: f32 = 1100.0;
/// From this width it has two; below it, one.
pub const TWO_COLUMNS_FROM: f32 = 700.0;
/// How many columns of key/value lines the raw counters run in, per page column.
pub const RAW_LINE_WIDTH: f32 = 400.0;
pub const TOOLBAR_HEIGHT: f32 = 24.0;
/// The hero band on a wide page: caption row, one row of figures and the storage line.
pub const HEADLINE_HEIGHT: f32 = 296.0;
/// A hero figure: the number, its caption, the trend line and two lines of small print.
pub const FIGURE_HEIGHT: f32 = 176.0;
/// One row of the counter strip.
pub const STRIP_ROW_HEIGHT: f32 = 92.0;
/// "Where compiles went": its bar, legend and the "of the built" line.
pub const WHERE_FIXED_HEIGHT: f32 = 212.0;
/// "Why compiles were not cacheable" needs this much beside its reasons: padding, title and the room under it.
pub const REASONS_FIXED_HEIGHT: f32 = 56.0;
/// From this panel width the "By language" table has room for its hit-rate bars.
pub const LANGUAGE_BARS_FROM: f32 = 380.0;
/// "By language" needs this much beside its rows.
pub const LANGUAGES_FIXED_HEIGHT: f32 = 50.0;
/// "Speed" needs this much beside its histograms.
pub const SPEED_FIXED_HEIGHT: f32 = 240.0;
/// "Speed" needs this much per language with a histogram.
pub const HISTOGRAM_HEIGHT: f32 = 85.0;
/// A panel of one time chart: padding, title, plot and legend.
pub const CHART_PANEL_HEIGHT: f32 = 306.0;
}
/// Drawings inside panels, in pixels.
pub mod drawing {
pub const CHART_HEIGHT: f32 = 240.0;
/// The trend line under a headline figure.
pub const SPARKLINE: f32 = 36.0;
pub const BUILD_HISTOGRAM: f32 = 44.0;
pub const BUILD_AXIS: f32 = 14.0;
pub const STACKED_BAR: f32 = 22.0;
pub const SPEED_BAR: f32 = 10.0;
pub const USAGE_BAR: f32 = 4.0;
pub const HIT_BAR: f32 = 72.0;
pub const HIT_BAR_HEIGHT: f32 = 6.0;
pub const LEGEND_SWATCH: f32 = 10.0;
pub const KEY_SWATCH: f32 = 14.0;
pub const SEVERITY_DOT: f32 = 8.0;
/// Share of the range's length left empty either side of a chart, so the
/// first and last time label sit inside the plot.
pub const CHART_SIDE_AIR: f64 = 0.035;
}
/// A hit rate is good from this share of compiles, and worth a look from the next.
pub mod state {
pub const HIT_RATE_GOOD: f64 = 0.7;
pub const HIT_RATE_WARN: f64 = 0.4;
/// A cache this full is shown in the bad colour.
pub const CACHE_FULL: f64 = 0.95;
}
// The font families, by name.
pub const REGULAR: &str = "inter-regular";
pub const MEDIUM: &str = "inter-medium";
pub const SEMIBOLD: &str = "inter-semibold";
pub const MONO: &str = "jetbrains-mono";
pub const MONO_MEDIUM: &str = "jetbrains-mono-medium";
// The text styles beyond egui's own, by name.
pub const TITLE_STYLE: &str = "title";
pub const CARD_STYLE: &str = "card-number";
pub const HEADLINE_STYLE: &str = "headline-number";
pub fn medium_family() -> FontFamily {
FontFamily::Name(MEDIUM.into())
}
pub fn semibold_family() -> FontFamily {
FontFamily::Name(SEMIBOLD.into())
}
pub fn mono_medium_family() -> FontFamily {
FontFamily::Name(MONO_MEDIUM.into())
}
/// Text of `size` in Inter Medium.
pub fn medium(size: f32) -> FontId {
FontId::new(size, medium_family())
}
/// Text of `size` in Inter SemiBold.
pub fn semibold(size: f32) -> FontId {
FontId::new(size, semibold_family())
}
/// A number of `size`: JetBrains Mono Medium.
pub fn number_font(size: f32) -> FontId {
FontId::new(size, mono_medium_family())
}
/// The font of panel titles and table heads.
pub fn title_font() -> FontId {
semibold(px::TITLE)
}
fn families() -> egui::FontDefinitions {
use std::sync::Arc;
let mut fonts = egui::FontDefinitions::default();
for (name, data) in [
(REGULAR, INTER_REGULAR_TTF),
(MEDIUM, INTER_MEDIUM_TTF),
(SEMIBOLD, INTER_SEMIBOLD_TTF),
(MONO, MONO_REGULAR_TTF),
(MONO_MEDIUM, MONO_MEDIUM_TTF),
] {
fonts
.font_data
.insert(name.to_owned(), Arc::new(egui::FontData::from_static(data)));
}
fonts
.families
.entry(FontFamily::Proportional)
.or_default()
.insert(0, REGULAR.to_owned());
fonts
.families
.entry(FontFamily::Monospace)
.or_default()
.insert(0, MONO.to_owned());
fonts
.families
.insert(medium_family(), vec![MEDIUM.to_owned()]);
fonts
.families
.insert(semibold_family(), vec![SEMIBOLD.to_owned()]);
fonts
.families
.insert(mono_medium_family(), vec![MONO_MEDIUM.to_owned()]);
fonts
}
fn text_styles() -> std::collections::BTreeMap<TextStyle, FontId> {
[
(TextStyle::Small, FontId::proportional(px::SMALL)),
(TextStyle::Body, FontId::proportional(px::BODY)),
(TextStyle::Button, medium(px::BODY)),
(TextStyle::Heading, semibold(px::BODY)),
(TextStyle::Monospace, FontId::monospace(px::BODY)),
(TextStyle::Name(TITLE_STYLE.into()), title_font()),
(
TextStyle::Name(CARD_STYLE.into()),
number_font(px::CARD_NUMBER),
),
(
TextStyle::Name(HEADLINE_STYLE.into()),
number_font(px::HEADLINE),
),
]
.into_iter()
.collect()
}
fn visuals(p: &Palette) -> egui::Visuals {
use egui::style::WidgetVisuals;
use egui::{CornerRadius, Stroke};
let mut visuals = if p.dark {
egui::Visuals::dark()
} else {
egui::Visuals::light()
};
visuals.override_text_color = Some(p.text);
visuals.panel_fill = p.page;
visuals.window_fill = p.panel;
visuals.window_stroke = Stroke::new(1.0, p.border);
visuals.extreme_bg_color = p.track;
visuals.faint_bg_color = p.hover;
visuals.selection.bg_fill = tint(p.accent, 0.35);
visuals.selection.stroke = Stroke::new(1.0, p.accent);
visuals.hyperlink_color = p.accent;
visuals.warn_fg_color = p.warn;
visuals.error_fg_color = p.bad;
let control = |fill, stroke, text: Color32| WidgetVisuals {
corner_radius: CornerRadius::same(space::CONTROL_RADIUS as u8),
bg_fill: fill,
weak_bg_fill: fill,
bg_stroke: Stroke::new(1.0, stroke),
fg_stroke: Stroke::new(1.0, text),
expansion: 0.0,
};
visuals.widgets.noninteractive = control(p.track, p.border, p.muted);
visuals.widgets.inactive = control(Color32::TRANSPARENT, p.border, p.text);
visuals.widgets.hovered = control(p.hover, p.muted, p.text);
visuals.widgets.active = control(tint(p.accent, 0.25), p.accent, p.text);
visuals.widgets.open = control(p.hover, p.muted, p.text);
visuals
}
/// Put the fonts, text styles, spacing and both themes' colours on the page.
pub fn install(ctx: &egui::Context) {
ctx.set_fonts(families());
ctx.all_styles_mut(|style| {
style.text_styles = text_styles();
style.spacing.item_spacing = egui::vec2(space::ITEM, space::LINE);
style.spacing.button_padding = egui::vec2(8.0, 2.0);
style.spacing.interact_size.y = space::CONTROL_HEIGHT;
style.spacing.indent = 12.0;
style.visuals = visuals(of(style.visuals.dark_mode));
});
}
/// A panel title: 11 px, upper case, letter-spaced, muted.
pub fn title(scope: &egui::Ui, text: impl AsRef<str>) -> RichText {
RichText::new(text.as_ref().to_uppercase())
.font(title_font())
.color(ui(scope).muted)
.extra_letter_spacing(space::TITLE_SPACING)
}
/// Small print in the muted colour.
pub fn small(scope: &egui::Ui, text: impl Into<String>) -> RichText {
RichText::new(text.into())
.font(FontId::proportional(px::SMALL))
.color(ui(scope).muted)
}
/// Text in the body size.
pub fn body(text: impl Into<String>) -> RichText {
RichText::new(text.into()).font(FontId::proportional(px::BODY))
}
/// Text in the body size, a little heavier.
pub fn strong(text: impl Into<String>) -> RichText {
RichText::new(text.into()).font(semibold(px::BODY))
}
/// A number in the body size, in the mono font.
pub fn number(text: impl Into<String>) -> RichText {
RichText::new(text.into()).font(number_font(px::BODY))
}
/// The colour of a hit rate: good, worth a look, or bad.
pub fn hit_rate_color(rate: Option<f64>, p: &Palette) -> Color32 {
match rate {
Some(rate) if rate >= state::HIT_RATE_GOOD => p.good,
Some(rate) if rate >= state::HIT_RATE_WARN => p.warn,
Some(_) => p.bad,
None => p.muted,
}
}
/// How many columns of panels the page has at `width`.
pub fn columns(width: f32) -> usize {
if width >= layout::THREE_COLUMNS_FROM {
3
} else if width >= layout::TWO_COLUMNS_FROM {
2
} else {
1
}
}
+258
View File
@@ -0,0 +1,258 @@
//! Where compiles went: one bar split by outcome, with a legend of counts and
//! shares; what happened inside the built share; and why some could not be
//! cached. How each language fared is its own panel ([`languages`]).
use std::sync::Arc;
use eframe::egui::{self, Color32, Sense, Stroke, Ui};
use eframe::epaint::text::Galley;
use sccache_dash_api::{NotCached, View};
use crate::disclosure;
use crate::fmt;
use crate::style::{self, Cell};
use crate::theme;
pub fn section(ui: &mut Ui, view: &View) {
let totals = &view.totals;
let p = theme::ui(ui);
// Five shares of every compiler call; timeouts, cache errors and forced
// recaches are inside the built share, as sccache counts them.
let parts: [(&'static str, u64, Color32); 5] = [
("From cache", totals.hits, p.from_cache),
("Built", totals.misses, p.built),
("Not cacheable", totals.not_cacheable, p.not_cacheable),
("Unsupported compiler", totals.unsupported_compiler, p.unsupported),
("Not a compile", totals.not_compile, p.not_compile),
];
let all: u64 = parts.iter().map(|(_, count, _)| count).sum();
let percents = fmt::shares(&parts.iter().map(|(_, count, _)| *count).collect::<Vec<_>>());
style::stacked_bar(ui, &parts, all);
ui.add_space(6.0);
let legend: Vec<Vec<Cell>> = parts
.iter()
.zip(&percents)
.map(|((name, count, color), percent)| {
vec![
Cell::Marked(*color, theme::body(*name)),
Cell::Text(theme::number(fmt::count(*count))),
Cell::Text(theme::number(format!("{percent}%"))),
]
})
.collect();
style::table(ui, &[], &legend);
ui.add_space(theme::space::ITEM);
ui.add(egui::Label::new(
theme::small(
ui,
format!(
"Of the built: {} timeouts, {} cache errors, {} forced recaches, {} failed to compile",
fmt::count(totals.timeouts),
fmt::count(totals.errors()),
fmt::count(totals.forced_recaches),
fmt::count(totals.compile_fails)
),
),
));
}
/// One reason laid out for a width: its line, and the two small paragraphs when it is open.
struct Block {
name: Arc<Galley>,
count: Arc<Galley>,
share: Arc<Galley>,
/// `None` while the reason is closed.
meaning: Option<Arc<Galley>>,
/// `None` when closed, or when sccache gives nothing to do.
action: Option<Arc<Galley>>,
/// The line: at least a control tall, taller when the name wraps.
row: f32,
open: bool,
}
impl Block {
fn entry(&self) -> disclosure::Entry {
disclosure::Entry {
row: self.row,
open: self.open,
meaning: self.meaning.as_ref().map_or(0.0, |g| g.size().y),
action: self.action.as_ref().map(|g| g.size().y),
}
}
}
/// How far the name is from the numbers, and from the dot.
const NAME_GAP: f32 = 8.0;
/// The side of the chevron's triangle box.
const CHEVRON: f32 = 8.0;
/// The hairline between two lines.
const SEPARATOR: f32 = 1.0;
/// Where a reason remembers whether it is open.
fn open_id(reason: &str) -> egui::Id {
egui::Id::new(("reason-open", reason))
}
fn is_open(ctx: &egui::Context, reason: &NotCached) -> bool {
let stored = ctx.data(|data| data.get_temp::<bool>(open_id(&reason.reason)));
disclosure::is_open(stored, reason.fixable)
}
/// Lay every reason out in `width`; counts and shares line up in columns, the name takes the rest.
fn blocks(ui: &Ui, view: &View, width: f32) -> Vec<Block> {
let number = |text: String| style::galley(ui, theme::number(text), false, f32::INFINITY);
let numbers: Vec<(Arc<Galley>, Arc<Galley>)> = view
.not_cached
.iter()
.map(|r| (number(fmt::count(r.count)), number(fmt::share(r.count, view.totals.not_cacheable))))
.collect();
let widest = |pick: fn(&(Arc<Galley>, Arc<Galley>)) -> &Arc<Galley>| {
numbers.iter().map(|n| pick(n).size().x).fold(0.0, f32::max)
};
let (count_width, share_width) = (widest(|n| &n.0), widest(|n| &n.1));
let indent = theme::drawing::SEVERITY_DOT + NAME_GAP;
let name_width = (width - indent - count_width - share_width - CHEVRON - 3.0 * NAME_GAP).max(40.0);
view.not_cached
.iter()
.zip(numbers)
.map(|(r, (count, share))| {
let name = style::galley(ui, theme::body(r.name.clone()), true, name_width);
let open = is_open(ui.ctx(), r);
let small = |text: &str| style::galley(ui, theme::small(ui, text), true, width - indent);
Block {
row: theme::space::CONTROL_HEIGHT.max(name.size().y + 2.0 * theme::space::ITEM),
name,
count,
share,
meaning: open.then(|| small(&r.meaning)),
action: (open && !r.action.is_empty()).then(|| small(&r.action)),
open,
}
})
.collect()
}
/// A triangle in the muted colour: pointing right when closed, down when open.
pub(crate) fn chevron(painter: &egui::Painter, center: egui::Pos2, open: bool, color: Color32) {
let h = CHEVRON / 2.0;
let points = if open {
vec![center + egui::vec2(-h, -h / 2.0), center + egui::vec2(h, -h / 2.0), center + egui::vec2(0.0, h / 2.0 + 1.0)]
} else {
vec![center + egui::vec2(-h / 2.0, -h), center + egui::vec2(-h / 2.0, h), center + egui::vec2(h / 2.0 + 1.0, 0.0)]
};
painter.add(egui::Shape::convex_polygon(points, color, Stroke::NONE));
}
/// "Why compiles were not cacheable": one line per reason, each with a dot (the warning
/// colour when a setting would fix it, the muted one when it is expected), its plain name,
/// its count and share, and a chevron. Clicking the line shows, in small print under it,
/// what it means and what to do; the reasons a setting would fix start open.
pub fn reasons(ui: &mut Ui, view: &View) {
if view.not_cached.is_empty() {
ui.label(theme::small(ui, "Every compile could be cached in this range."));
return;
}
let p = theme::ui(ui);
let width = ui.available_width();
let blocks = blocks(ui, view, width);
let indent = theme::drawing::SEVERITY_DOT + NAME_GAP;
// Every height is added by hand, so the list is as tall as `reasons_height` says.
ui.spacing_mut().item_spacing.y = 0.0;
for (index, (reason, block)) in view.not_cached.iter().zip(&blocks).enumerate() {
if index > 0 {
let (gap, _) = ui.allocate_exact_size(egui::vec2(width, SEPARATOR), Sense::hover());
ui.painter().rect_filled(gap, 0.0, p.grid);
}
let (row, response) = ui.allocate_exact_size(egui::vec2(width, block.row), Sense::click());
let response = response.on_hover_cursor(egui::CursorIcon::PointingHand);
response.widget_info(|| {
egui::WidgetInfo::labeled(egui::WidgetType::Button, true, reason.name.as_str())
});
if response.clicked() {
ui.ctx().data_mut(|data| data.insert_temp(open_id(&reason.reason), !block.open));
ui.ctx().request_repaint();
}
let painter = ui.painter();
if response.hovered() || response.has_focus() {
painter.rect_filled(row, theme::space::CONTROL_RADIUS, p.hover);
}
if response.has_focus() {
painter.rect_stroke(row, theme::space::CONTROL_RADIUS, Stroke::new(1.0, p.muted), egui::StrokeKind::Inside);
}
let side = theme::drawing::SEVERITY_DOT;
let dot = if reason.fixable { p.warn } else { p.not_cacheable };
let name_top = row.top() + (block.row - block.name.size().y) / 2.0;
painter.rect_filled(egui::Rect::from_center_size(egui::pos2(row.left() + side / 2.0, row.center().y), egui::vec2(side, side)), 0.0, dot);
painter.galley(egui::pos2(row.left() + indent, name_top), block.name.clone(), p.text);
let chevron_left = row.right() - CHEVRON;
chevron(painter, egui::pos2(chevron_left + CHEVRON / 2.0, row.center().y), block.open, p.muted);
let share_left = chevron_left - NAME_GAP - block.share.size().x;
let at = |galley: &Arc<Galley>, left: f32| {
egui::pos2(left, row.top() + (block.row - galley.size().y) / 2.0)
};
painter.galley(at(&block.share, share_left), block.share.clone(), p.text);
let count_left = share_left - NAME_GAP - block.count.size().x;
painter.galley(at(&block.count, count_left), block.count.clone(), p.text);
let mut opened = false;
for galley in block.meaning.iter().chain(block.action.as_ref()) {
ui.add_space(theme::space::LINE);
let (place, _) = ui.allocate_exact_size(egui::vec2(width, galley.size().y), Sense::hover());
ui.painter().galley(egui::pos2(place.left() + indent, place.top()), galley.clone(), p.muted);
opened = true;
}
if opened {
ui.add_space(theme::space::ITEM);
}
}
}
/// How tall "Why compiles were not cacheable" is in a panel `panel_width` wide.
pub fn reasons_height(ui: &Ui, view: &View, panel_width: f32) -> f32 {
let inner = panel_width - 2.0 * theme::space::PANEL_PADDING;
let entries: Vec<_> = blocks(ui, view, inner).iter().map(Block::entry).collect();
let list = disclosure::list_height(&entries, theme::space::LINE, theme::space::ITEM, SEPARATOR);
theme::layout::REASONS_FIXED_HEIGHT + list.max(theme::space::ROW)
}
/// "By language": one row per language, with hits, misses, errors, the hit rate
/// in its state colour, and a bar of hits against misses.
pub fn languages(ui: &mut Ui, view: &View) {
if view.languages.is_empty() {
ui.label(theme::small(ui, "No compiles were counted in this range."));
return;
}
let p = theme::ui(ui);
// The bar is the first thing to go where the columns are too tight to leave it room.
let with_bars = ui.available_rect_before_wrap().width() >= theme::layout::LANGUAGE_BARS_FROM;
let mut head = vec!["", "Hits", "Misses", "Errors", "Hit rate"];
if with_bars {
head.push("");
}
let mut rows: Vec<Vec<Cell>> = view
.languages
.iter()
.map(|language| {
let rate = crate::overtime::hit_rate(language.hits, language.misses);
vec![
Cell::Text(theme::strong(language.name.clone())),
Cell::Text(theme::number(fmt::count(language.hits))),
Cell::Text(theme::number(fmt::count(language.misses))),
Cell::Text(
theme::number(fmt::count(language.errors))
.color(if language.errors > 0 { p.bad } else { p.text }),
),
Cell::Text(
theme::number(fmt::percent(rate)).color(theme::hit_rate_color(rate, p)),
),
]
})
.collect();
if with_bars {
for (row, language) in rows.iter_mut().zip(&view.languages) {
row.push(Cell::Bar(language.hits, language.misses));
}
}
style::table(ui, &head, &rows);
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 253 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 226 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

+1
View File
@@ -0,0 +1 @@
{"stats":{"compile_requests":820,"requests_unsupported_compiler":0,"requests_not_compile":2,"requests_not_cacheable":18,"requests_executed":800,"cache_errors":{"counts":{},"adv_counts":{}},"cache_hits":{"counts":{"C/C++":3},"adv_counts":{"c [gcc]":3}},"cache_misses":{"counts":{"C/C++":797},"adv_counts":{"c [gcc]":797}},"cache_timeouts":0,"cache_read_errors":0,"non_cacheable_compilations":0,"forced_recaches":0,"cache_write_errors":0,"cache_writes":797,"cache_write_duration":{"secs":9,"nanos":0},"cache_read_hit_duration":{"secs":0,"nanos":3000000},"compilations":797,"compiler_write_duration":{"secs":1200,"nanos":0},"compile_fails":0,"not_cached":{},"dist_compiles":{"10.0.0.12:4226":379,"buildbox.local:4228":9,"10.0.0.11:4226":402},"dist_errors":7,"multi_level":null},"cache_location":"Local disk: \"/home/me/.cache/sccache\"","cache_size":107374182,"max_cache_size":1073741824,"use_preprocessor_cache_mode":false,"version":"0.18.0","basedirs":[]}
+1
View File
@@ -0,0 +1 @@
{"stats":{"compile_requests":5000,"requests_unsupported_compiler":0,"requests_not_compile":12,"requests_not_cacheable":150,"requests_executed":4838,"cache_errors":{"counts":{},"adv_counts":{}},"cache_hits":{"counts":{"C/C++":2100,"Rust":400},"adv_counts":{"c [gcc]":2100,"rust":400}},"cache_misses":{"counts":{"Rust":2300,"C/C++":38},"adv_counts":{"rust":2300,"c [gcc]":38}},"cache_timeouts":12,"cache_read_errors":0,"non_cacheable_compilations":0,"forced_recaches":0,"cache_write_errors":5,"cache_writes":2338,"cache_write_duration":{"secs":40,"nanos":0},"cache_read_hit_duration":{"secs":0,"nanos":600000000},"compilations":2338,"compiler_write_duration":{"secs":18000,"nanos":0},"compile_fails":0,"not_cached":{"crate-type":150},"dist_compiles":{},"dist_errors":0,"multi_level":[{"name":"L0 (disk)","location":"Local disk: \"/home/me/.cache/sccache\"","hits":1500,"misses":1000,"writes":1400,"write_failures":2,"backfills_from":300,"backfills_to":0,"hit_duration":{"secs":1,"nanos":500000000},"write_duration":{"secs":2,"nanos":500000000}},{"name":"L1 (s3)","location":"s3, name: bucket, prefix: /p/","hits":1000,"misses":1800,"writes":900,"write_failures":0,"backfills_from":0,"backfills_to":300,"hit_duration":{"secs":6,"nanos":0},"write_duration":{"secs":36,"nanos":500000000}}]},"cache_location":"Multi-level: \"L0 (disk)\" + \"L1 (s3)\"","cache_size":1234567890,"max_cache_size":10737418240,"use_preprocessor_cache_mode":true,"version":"0.18.0","basedirs":[]}
+14
View File
@@ -0,0 +1,14 @@
# Build the page first, then the server with the page inside it.
build:
cd crates/ui && trunk build --release
cargo build --release -p sccache-dash
test:
cargo test -p sccache-dash -p sccache-dash-api
run:
cargo run -p sccache-dash
# Screenshots of the whole page at the 3, 2 and 1 column widths; read them before merging a page change.
shots url="http://127.0.0.1:8226/" out="target/shots":
prlimit --core=1:1 -- node scripts/shots.js {{url}} {{out}}
+5
View File
@@ -0,0 +1,5 @@
# Tools for building and running sccache-dash.
[tools]
# Builds the dashboard page (crates/ui) to WebAssembly. The release binary is
# downloaded; building trunk from source takes half an hour.
"ubi:trunk-rs/trunk" = "0.22.2"
+24
View File
@@ -0,0 +1,24 @@
// Screenshots of the whole page at each layout width (3, 2 and 1 column), read
// before any page change is merged. Usage: just shots [url] [out-dir]
const path = require('path');
const { execSync } = require('child_process');
const root = execSync('mise where npm:playwright 2>/dev/null || mise where playwright', { encoding: 'utf8' }).trim();
const { chromium } = require(path.join(root, 'node_modules/playwright'));
const [, , url = 'http://127.0.0.1:8226/', out = 'target/shots'] = process.argv;
(async () => {
require('fs').mkdirSync(out, { recursive: true });
const browser = await chromium.launch({
args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist'],
});
for (const [width, height] of [[1400, 2600], [900, 3600], [390, 5600]]) {
// The page scrolls inside its canvas, so a tall window shows all of it.
const page = await browser.newPage({ viewport: { width, height }, colorScheme: 'dark' });
await page.goto(url);
await page.waitForTimeout(5000);
const file = path.join(out, `page-${width}.png`);
await page.screenshot({ path: file });
console.log(file);
await page.close();
}
await browser.close();
})().catch((error) => { console.error(error); process.exit(1); });