forge
Explore
Log in

Don't you dare go Hollow

File ages load after the page instead of holding it

Browse files at this commit

37e985d7446f13ea8d71da4ff0e8d2d11d64a25fAhmet Kaan GümüşParent: ed35470
All checks have passed
Show checks
  • perf
    • file ages load after the page instead of holding it
    • the history walk moves to /{owner}/{repo}/ages and the last-commit cache is gone, so the code page renders in 5 ms
Show full message
⚡ perf: file ages load after the page instead of holding it; the history walk moves to /{owner}/{repo}/ages and the last-commit cache is gone, so the code page renders in 5 ms
crates/forge-web-pages/src/pages/repo.rsmodified+6 -17
@@ -23,7 +23,7 @@ use crate::pages::refs::{load_refs, ref_links};
2323 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo};
2424 use crate::pages::repo_side::{StripFacts, code_sub, commit_strip, run_pips, run_rows, tree_facts};
2525 use crate::pages::tree::{
26- entry_rows, last_commits, latest_bar, load_readme, read_dir, readme_sheet, tree_table,
26+ ages_url, entry_rows, latest_bar, load_readme, read_dir, readme_sheet, tree_table,
2727 };
2828 use crate::state::AppState;
2929 use crate::views::parts::{SubPart, head_sub};
@@ -383,6 +383,7 @@ async fn repo_page(cx: &Cx) -> Result<impl View> {
383383 let title = ctx.title();
384384
385385 let mut tree = None;
386+ let mut ages = String::new();
386387 let mut readme = None;
387388 let mut bar = None;
388389 let mut facts = None;
@@ -391,22 +392,10 @@ async fn repo_page(cx: &Cx) -> Result<impl View> {
391392 {
392393 let names: Vec<String> = entries.iter().map(|e| e.name.clone()).collect();
393394 facts = Some(tree_facts(state, repo, &ctx.path, commit, &names).await?);
394- let (last, latest) = tokio::join!(
395- last_commits(state, &ctx.path, commit, "", &names),
396- latest_bar(state, repo, &ctx.path, commit, lang, ctx.viewer_tz()),
397- );
398- bar = latest;
395+ bar = latest_bar(state, repo, &ctx.path, commit, lang, ctx.viewer_tz()).await;
396+ ages = ages_url(repo, commit, "");
399397 readme = load_readme(state, repo, &ctx.path, &branch, commit, "", &entries).await?;
400- tree = Some(entry_rows(
401- lang,
402- repo,
403- &branch,
404- "",
405- entries,
406- &last,
407- now_unix(),
408- ctx.viewer_tz(),
409- ));
398+ tree = Some(entry_rows(repo, &branch, "", entries));
410399 }
411400 let follows = follows_branch(&refs, &branch);
412401 let live = home_live_url(&repo.owner_name, &repo.name, &branch);
@@ -447,7 +436,7 @@ async fn repo_page(cx: &Cx) -> Result<impl View> {
447436 file_finder(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(),
448437 ref_name: branch.clone())
449438 </div>
450- tree_table(rows: rows, lang: lang, current: readme_file)
439+ tree_table(rows: rows, lang: lang, ages: ages.clone(), current: readme_file)
451440 </nav>
452441 readme_sheet(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), ref_name: branch.clone(), dir: String::new(), readme: readme,
453442 none: s(lang, "No README yet", "Henüz README yok"))
crates/forge-web-pages/src/pages/tree.rsmodified+46 -57
@@ -1,6 +1,5 @@
11 use std::collections::HashMap;
22 use std::path::{Path, PathBuf};
3-use std::sync::{Mutex, OnceLock};
43 use std::time::Duration;
54
65 use forge_core::Repo as RepoRow;
@@ -10,7 +9,8 @@ use forge_git::history;
109 use topcoat::Result;
1110 use topcoat::context::{Cx, context};
1211 use topcoat::router::error::not_found;
13-use topcoat::router::{page, path_param};
12+use topcoat::router::response::Response;
13+use topcoat::router::{Body, HeaderValue, page, path_param, route};
1414 use topcoat::view::{Unescaped, View, component, view};
1515
1616 use crate::i18n::code::{self as g, K};
@@ -67,13 +67,6 @@ pub async fn read_file(path: PathBuf, commit: String, file: String) -> Result<Op
6767 .await??)
6868 }
6969
70-type LastCommitCache = Mutex<HashMap<(PathBuf, String), (String, HashMap<String, CommitInfo>)>>;
71-
72-fn last_commit_cache() -> &'static LastCommitCache {
73- static CACHE: OnceLock<LastCommitCache> = OnceLock::new();
74- CACHE.get_or_init(|| Mutex::new(HashMap::new()))
75-}
76-
7770 pub async fn last_commits(
7871 state: &AppState,
7972 path: &Path,
@@ -81,22 +74,9 @@ pub async fn last_commits(
8174 dir: &str,
8275 names: &[String],
8376 ) -> HashMap<String, CommitInfo> {
84- let key = (path.to_path_buf(), dir.to_owned());
85- if let Some((at, map)) = last_commit_cache().lock().expect("last-commit cache").get(&key)
86- && at == commit
87- {
88- return map.clone();
89- }
9077 let walk = history::last_commits(&state.git, path, commit, dir, names, LAST_COMMIT_WALK);
9178 match tokio::time::timeout(LAST_COMMIT_TIMEOUT, walk).await {
92- Ok(Ok(map)) => {
93- let mut cache = last_commit_cache().lock().expect("last-commit cache");
94- if cache.len() >= 1024 {
95- cache.clear();
96- }
97- cache.insert(key, (commit.to_owned(), map.clone()));
98- map
99- }
79+ Ok(Ok(map)) => map,
10080 Ok(Err(e)) => {
10181 tracing::warn!(error = %e, "last-commit walk failed");
10282 HashMap::new()
@@ -172,20 +152,9 @@ pub struct EntryRow {
172152 pub name: String,
173153 pub href: Option<String>,
174154 pub short: String,
175- pub last: Option<LastCommit>,
176155 }
177156
178-#[allow(clippy::too_many_arguments)]
179-pub fn entry_rows(
180- lang: Lang,
181- repo: &RepoRow,
182- ref_name: &str,
183- dir: &str,
184- entries: Vec<TreeEntry>,
185- last: &HashMap<String, CommitInfo>,
186- now: i64,
187- tz: &str,
188-) -> Vec<EntryRow> {
157+pub fn entry_rows(repo: &RepoRow, ref_name: &str, dir: &str, entries: Vec<TreeEntry>) -> Vec<EntryRow> {
189158 entries
190159 .into_iter()
191160 .map(|entry| {
@@ -206,15 +175,11 @@ pub fn entry_rows(
206175 EntryKind::Symlink => ("link", blob_href(repo, ref_name, &rel), String::new()),
207176 EntryKind::Submodule => ("submodule", None, short_oid(&entry.oid).to_owned()),
208177 };
209- let last = last
210- .get(&entry.name)
211- .map(|c| last_commit_view(lang, repo, c, now, tz));
212178 EntryRow {
213179 kind,
214180 name: entry.name,
215181 href,
216182 short,
217- last,
218183 }
219184 })
220185 .collect()
@@ -266,6 +231,41 @@ fn blob_href(repo: &RepoRow, ref_name: &str, rel: &str) -> Option<String> {
266231 ))
267232 }
268233
234+pub fn ages_url(repo: &RepoRow, commit: &str, dir: &str) -> String {
235+ repo_href(&repo.owner_name, &repo.name, "ages", &child_path(commit, dir))
236+}
237+
238+#[route(GET "/{owner}/{repo}/ages/{*rest}")]
239+async fn tree_ages(cx: &Cx) -> Result<Response> {
240+ let ctx = load_repo(cx, owner(cx), repo(cx)).await?;
241+ let state = context::<AppState>(cx);
242+ let parts: Vec<String> = rest(cx).map(|part| part.to_string()).collect();
243+ let Some((commit, dir)) = parts.split_first() else {
244+ return Err(not_found().into());
245+ };
246+ let dir = dir.join("/");
247+ let Some(entries) = read_dir(ctx.path.clone(), commit.clone(), dir.clone()).await? else {
248+ return Err(not_found().into());
249+ };
250+ let names: Vec<String> = entries.into_iter().map(|entry| entry.name).collect();
251+ let last = last_commits(state, &ctx.path, commit, &dir, &names).await;
252+ let now = now_unix();
253+ let ages: serde_json::Map<String, serde_json::Value> = last
254+ .iter()
255+ .map(|(name, commit)| {
256+ let view = last_commit_view(ctx.lang, &ctx.repo, commit, now, ctx.viewer_tz());
257+ let age = serde_json::json!({ "iso": view.iso, "absolute": view.absolute, "age": view.age });
258+ (name.clone(), age)
259+ })
260+ .collect();
261+ let mut response = Response::new(Body::from(serde_json::Value::Object(ages).to_string().into_bytes()));
262+ response.headers_mut().insert(
263+ http::header::CONTENT_TYPE,
264+ HeaderValue::from_static("application/json; charset=utf-8"),
265+ );
266+ Ok(response)
267+}
268+
269269 pub fn link_context(state: &AppState, repo: &RepoRow, ref_name: &str, dir: &str) -> LinkContext {
270270 let at = |section: &str| {
271271 repo_href(
@@ -338,18 +338,16 @@ pub async fn tree_table(
338338 cx: &Cx,
339339 rows: Vec<EntryRow>,
340340 lang: Lang,
341+ ages: String,
341342 #[default] current: Option<String>,
342343 ) -> Result<impl View> {
343344 Ok(view! {
344- <div class="rail-list tree-list">
345+ <div class="rail-list tree-list" data-ages=(ages)>
345346 for row in rows.into_iter() {
346347 if let Some(href) = row.href {
347- <a class="rail-item tree-entry" href=(href) data-kb-row="" aria-current=((current.as_deref() == Some(row.name.as_str())).then_some("page"))>
348+ <a class="rail-item tree-entry" href=(href) data-kb-row="" data-name=(row.name.clone()) aria-current=((current.as_deref() == Some(row.name.as_str())).then_some("page"))>
348349 <span class="sr-only">(g::kind_label(lang, row.kind))</span>
349350 <span class="nm dir">(row.name)if row.kind == "dir" { "/" }</span>
350- if let Some(last) = row.last {
351- <time class="val" data-rel="true" datetime=(last.iso) title=(last.absolute)>(last.age)</time>
352- }
353351 </a>
354352 } else {
355353 <div class="rail-item tree-entry" data-kb-row="">
@@ -455,8 +453,7 @@ async fn tree_page(cx: &Cx) -> Result<impl View> {
455453 .map(|e| e.name)
456454 .collect()
457455 };
458- let (last, bar, strip, runs) = tokio::join!(
459- last_commits(state, &ctx.path, &commit, &dir, &names),
456+ let (bar, strip, runs) = tokio::join!(
460457 latest_bar(state, repo, &ctx.path, &commit, lang, ctx.viewer_tz()),
461458 commit_strip(state, repo, &ctx.path, &commit),
462459 run_rows(state, lang, repo),
@@ -467,16 +464,8 @@ async fn tree_page(cx: &Cx) -> Result<impl View> {
467464 let sub = code_sub(lang, bar, Some(facts), None, strip.total);
468465 let refs: Vec<RefInfo> = load_refs(ctx.path.clone()).await?;
469466 let readme = load_readme(state, repo, &ctx.path, &ref_name, &commit, &dir, &entries).await?;
470- let rows = entry_rows(
471- lang,
472- repo,
473- &ref_name,
474- &dir,
475- entries,
476- &last,
477- now_unix(),
478- ctx.viewer_tz(),
479- );
467+ let rows = entry_rows(repo, &ref_name, &dir, entries);
468+ let ages = ages_url(repo, &commit, &dir);
480469 let (branches, tags) = ref_links(&refs, &ref_name, &repo.default_branch, repo);
481470 let branches_href = repo_href(&repo.owner_name, &repo.name, "branches", "");
482471 let tags_href = repo_href(&repo.owner_name, &repo.name, "tags", "");
@@ -507,7 +496,7 @@ async fn tree_page(cx: &Cx) -> Result<impl View> {
507496 <a class="act code-search-act" href=(code_search_href)>(g::t(lang, K::SearchCodePlaceholder))</a>
508497 file_finder(lang: lang, owner: finder_owner, repo: finder_repo, ref_name: finder_ref)
509498 </div>
510- tree_table(rows: rows, lang: lang, current: readme_file)
499+ tree_table(rows: rows, lang: lang, ages: ages, current: readme_file)
511500 </nav>
512501 readme_sheet(lang: lang, owner: dock_owner, repo: dock_repo, ref_name: ref_name.clone(), dir: dir.clone(), readme: readme,
513502 none: s(lang, "No README in this folder", "Bu klasörde README yok"))
crates/forge-web-repo/src/pages/blob.rsmodified+6 -15
@@ -19,14 +19,14 @@ use crate::pages::repo::repo_head;
1919 use crate::pages::repo_ctx::load_repo;
2020 use crate::pages::repo_side::{code_sub, commit_strip, run_pips, run_rows, tree_facts};
2121 use crate::pages::tree::{
22- entry_rows, last_commits, latest_bar, link_context, read_dir, read_file, resolve, tree_table,
22+ ages_url, entry_rows, latest_bar, link_context, read_dir, read_file, resolve, tree_table,
2323 };
2424 use crate::raw::media::media_url;
2525 use crate::raw::raw_url;
2626 use crate::render::highlight::highlight_lines;
2727 use crate::render::markdown::render_markdown;
2828 use crate::state::AppState;
29-use crate::views::{human_size, now_unix, ref_selector, repo_href, shell};
29+use crate::views::{human_size, ref_selector, repo_href, shell};
3030
3131 const IMAGE_EXTS: [&str; 8] = ["png", "jpg", "jpeg", "gif", "webp", "avif", "svg", "ico"];
3232 const MARKDOWN_EXTS: [&str; 2] = ["md", "markdown"];
@@ -256,8 +256,7 @@ async fn blob_page(cx: &Cx) -> Result<impl View> {
256256 .map(|e| e.name)
257257 .collect()
258258 };
259- let (last, bar, strip, runs) = tokio::join!(
260- last_commits(state, &ctx.path, &commit, &dir, &names),
259+ let (bar, strip, runs) = tokio::join!(
261260 latest_bar(state, repo, &ctx.path, &commit, lang, ctx.viewer_tz()),
262261 commit_strip(state, repo, &ctx.path, &commit),
263262 run_rows(state, lang, repo),
@@ -269,16 +268,8 @@ async fn blob_page(cx: &Cx) -> Result<impl View> {
269268 let (branches, tags) = ref_links(&refs, &ref_name, &repo.default_branch, repo);
270269 let branches_href = repo_href(&repo.owner_name, &repo.name, "branches", "");
271270 let tags_href = repo_href(&repo.owner_name, &repo.name, "tags", "");
272- let rows = entry_rows(
273- lang,
274- repo,
275- &ref_name,
276- &dir,
277- siblings,
278- &last,
279- now_unix(),
280- ctx.viewer_tz(),
281- );
271+ let rows = entry_rows(repo, &ref_name, &dir, siblings);
272+ let ages = ages_url(repo, &commit, &dir);
282273 let mut header = ctx.head(state, "code").await?;
283274 header.live = live_url(&repo.owner_name, &repo.name, &refs, &ref_name);
284275 let size = human_size(lang, blob.size);
@@ -299,7 +290,7 @@ async fn blob_page(cx: &Cx) -> Result<impl View> {
299290 branches_href: branches_href, tags_href: tags_href)
300291 file_finder(lang: lang, owner: finder_owner, repo: finder_repo, ref_name: finder_ref)
301292 </div>
302- tree_table(rows: rows, lang: lang, current: Some(file_name.clone()))
293+ tree_table(rows: rows, lang: lang, ages: ages, current: Some(file_name.clone()))
303294 </nav>
304295 <div class="sheet">
305296 <div class="sheet-tools">
crates/forge-web-repo/src/pages/repo_scrub.rsmodified+3 -12
@@ -1,4 +1,4 @@
1-use std::collections::{HashMap, VecDeque};
1+use std::collections::VecDeque;
22 use std::path::PathBuf;
33 use std::sync::{Arc, Mutex};
44
@@ -16,7 +16,7 @@ use crate::pages::repo_ctx::{RepoCtx, load_repo};
1616 use crate::pages::tree::{entry_rows, load_readme, read_dir, readme_card};
1717 use crate::state::AppState;
1818 use crate::views::parts::{SubPart, head};
19-use crate::views::{now_unix, shell};
19+use crate::views::shell;
2020
2121 const CACHE_CAP: usize = 64;
2222
@@ -113,16 +113,7 @@ async fn scrub_parts(state: &AppState, ctx: &RepoCtx, oid: &str) -> Result<Optio
113113 return Ok(None);
114114 };
115115 let readme = load_readme(state, repo, &ctx.path, oid, oid, "", &entries).await?;
116- let rows = entry_rows(
117- ctx.lang,
118- repo,
119- oid,
120- "",
121- entries,
122- &HashMap::new(),
123- now_unix(),
124- ctx.viewer_tz(),
125- )
116+ let rows = entry_rows(repo, oid, "", entries)
126117 .into_iter()
127118 .map(|row| ScrubRow {
128119 kind: row.kind,
crates/forge-web/assets/nav.jsmodified+43 -0
@@ -6102,3 +6102,46 @@
61026102 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', init); }
61036103 else { init(); }
61046104 })();
6105+
6106+// File ages. A tree list names where its ages come from in data-ages (the commit and the folder), and
6107+// they are asked for after the page shows, so the walk through history never holds the page. A live
6108+// refresh at the same commit gets the same answer, so the last one is put back at once instead of
6109+// the column going blank until the new answer comes.
6110+(function () {
6111+ var last = null;
6112+
6113+ function fill(list, ages) {
6114+ Array.prototype.forEach.call(list.querySelectorAll('.tree-entry[data-name]'), function (row) {
6115+ var age = ages[row.getAttribute('data-name')];
6116+ if (!age || row.querySelector('time')) { return; }
6117+ var el = document.createElement('time');
6118+ el.className = 'val';
6119+ el.setAttribute('data-rel', 'true');
6120+ el.setAttribute('datetime', age.iso);
6121+ el.title = age.absolute;
6122+ el.textContent = age.age;
6123+ row.appendChild(el);
6124+ });
6125+ }
6126+
6127+ function sync() {
6128+ Array.prototype.forEach.call(document.querySelectorAll('.tree-list[data-ages]:not([data-ages-asked])'), function (list) {
6129+ var url = list.getAttribute('data-ages');
6130+ list.setAttribute('data-ages-asked', '');
6131+ if (last && last.url === url) { fill(list, last.ages); return; }
6132+ fetch(url, { credentials: 'same-origin' }).then(function (res) {
6133+ return res.ok ? res.json() : null;
6134+ }).then(function (ages) {
6135+ if (!ages) { return; }
6136+ last = { url: url, ages: ages };
6137+ Array.prototype.forEach.call(document.querySelectorAll('.tree-list[data-ages]'), function (shown) {
6138+ if (shown.getAttribute('data-ages') === url) { fill(shown, ages); }
6139+ });
6140+ }).catch(function () { });
6141+ });
6142+ }
6143+
6144+ document.addEventListener('forge:swapped', sync);
6145+ if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', sync); }
6146+ else { sync(); }
6147+})();
crates/forge-web/src/routes.snapmodified+1 -0
@@ -293,6 +293,7 @@ route /settings/tokens/delete Only([POST])
293293 route /theme/custom.css Only([GET])
294294 route /users/{username}/events Only([GET])
295295 route /{owner}/{repo} Any
296+route /{owner}/{repo}/ages/{*rest} Only([GET])
296297 route /{owner}/{repo}/archive/{*rest} Only([GET])
297298 route /{owner}/{repo}/attachments Only([POST])
298299 route /{owner}/{repo}/badge.svg Only([GET])