Sign in

Search issue titles and bodies, change requests and comments. Private repositories you cannot read are not included.

vole
Site
Clone

Read only, no credentials:

https://rodent.software/vole.git

Write over SSH with a registered key:

git clone ssh://git@rodent.software/vole.git

Self-hosted forge that lives in your Git repo.

Refresh run status on focus and show one clock per job

aa38f6b2428795995009fbe14a0b5a82b83006c6 · Keenan Nemetz · 9d ago · parent 8ca8bbe0

Refresh run status on focus and show one clock per job

A page in an unfocused window kept its durations moving while its status
stopped changing. The clock is arithmetic from a start timestamp, so it jumps
to the right value when the reader returns; the status is server-rendered HTML
that only moves when something re-fetches it. The result was a page minutes
behind that looked current.

Hidden and unfocused windows are not being read, so the answer is not to keep
polling them. The polls now skip a tick while the window is unfocused and mark
their region stale; the repository header says how old the last answer is, and
queued or running dots go hollow and stop pulsing. Returning to the window
dispatches vole-refresh, which every poll answers immediately instead of
waiting out its interval. The stale mark is cleared only by a refresh that
succeeded. Finished statuses are never marked, because they cannot change.

The overview's recent runs and the runs tab now poll too, and the run page
keeps itself current while a run is queued as well as running, so a queued
page picks up the start it was waiting for. A run row shows one clock: the
queue wait while queued, the run time while running, and the total it took once
finished. The run page keeps its separate duration and queue-wait cards, which
is where both numbers belong.

A running job's status dot pulses while the page is live.

Fixes #367.

server/web/static/app.js +174−77

@@ -591,13 +591,23 @@ const fitTextarea = (area) => {
591 591 });
592 592 });
593 593
594 // The page's own loop follows the same rule as the polls: no requests in an
595 // unfocused window, a stale mark while it is away, and an immediate tick on
596 // the vole-refresh that a refocus dispatches. Only a response clears the mark.
597 const stale = () => card.dispatchEvent(new CustomEvent('vole-stale', { bubbles: true }));
598 const fresh = () => card.dispatchEvent(new CustomEvent('vole-fresh', { bubbles: true }));
599 const focused = () => document.hasFocus();
600
594 601 const pane = document.querySelector('pre[data-live-step-log]');
595 602 if (!pane) {
596 603 // Between steps there is no range to follow yet. Reload until the next step
597 604 // starts or the run finishes, unless the reader is reading another step.
598 setTimeout(() => {
605 const later = () => {
599 606 if (!detached) location.reload();
600 }, 2000);
607 };
608 if (focused()) setTimeout(later, 2000);
609 else stale();
610 document.body.addEventListener('vole-refresh', later);
601 611 return;
602 612 }
603 613
@@ -610,88 +620,105 @@ const fitTextarea = (area) => {
610 620 // poll back to the step's start and replay its opening bytes.
611 621 let offset = Number(pane.dataset.logOffset || 0);
612 622 let stopped = false;
623 let inflight = false;
613 624
614 625 const schedule = () => {
615 if (!stopped) setTimeout(tick, 1000);
616 };
617
618 const tick = async () => {
619 626 if (stopped) return;
620 let res;
621 try {
622 res = await fetch(url + '&after=' + offset, {
623 cache: 'no-store',
624 credentials: 'same-origin',
625 });
626 } catch (_) {
627 schedule();
627 if (!focused()) {
628 stale();
628 629 return;
629 630 }
630 if (res.status === 404) {
631 schedule();
632 return;
633 }
634 if (!res.ok) {
635 schedule();
636 return;
637 }
638 let buf;
631 setTimeout(tick, 1000);
632 };
633
634 const tick = async () => {
635 if (stopped || inflight) return;
636 inflight = true;
639 637 try {
640 buf = await res.arrayBuffer();
641 } catch (_) {
638 let res;
639 try {
640 res = await fetch(url + '&after=' + offset, {
641 cache: 'no-store',
642 credentials: 'same-origin',
643 });
644 } catch (_) {
645 schedule();
646 return;
647 }
648 if (res.status === 404) {
649 fresh();
650 schedule();
651 return;
652 }
653 if (!res.ok) {
654 schedule();
655 return;
656 }
657 fresh();
658 let buf;
659 try {
660 buf = await res.arrayBuffer();
661 } catch (_) {
662 schedule();
663 return;
664 }
665 if (buf.byteLength) {
666 const stick = pane.scrollTop + pane.clientHeight >= pane.scrollHeight - 12;
667 pane.appendChild(document.createTextNode(decoder.decode(buf, { stream: true })));
668 offset += buf.byteLength;
669 if (stick) pane.scrollTop = pane.scrollHeight;
670 }
671 if (res.headers.get('X-Step-Final') === '1') {
672 pane.appendChild(document.createTextNode(decoder.decode()));
673 stopped = true;
674 if (!detached) setTimeout(() => location.reload(), 800);
675 return;
676 }
642 677 schedule();
643 return;
644 }
645 if (buf.byteLength) {
646 const stick = pane.scrollTop + pane.clientHeight >= pane.scrollHeight - 12;
647 pane.appendChild(document.createTextNode(decoder.decode(buf, { stream: true })));
648 offset += buf.byteLength;
649 if (stick) pane.scrollTop = pane.scrollHeight;
678 } finally {
679 inflight = false;
650 680 }
651 if (res.headers.get('X-Step-Final') === '1') {
652 pane.appendChild(document.createTextNode(decoder.decode()));
653 stopped = true;
654 if (!detached) setTimeout(() => location.reload(), 800);
655 return;
656 }
657 schedule();
658 681 };
659 682
660 683 tick();
684 document.body.addEventListener('vole-refresh', () => {
685 if (!stopped) tick();
686 });
661 687 })();
662 688
663 // Relative times and live durations. The server renders the same words, so a page
664 // without scripts still reads; this keeps the values moving between the polls
665 // that refresh the surrounding row. A run that is waiting or running would
666 // otherwise show a frozen duration until the next page load, and asking the
667 // server every second for a clock would be wasteful. The formatting matches
689 // The words for a duration and for an age. The server renders the same ones, so
690 // a page without scripts still reads; this keeps the values moving between the
691 // polls that refresh the surrounding row. The formatting matches
668 692 // internal/format.Duration and humanSince in server/web/ui.go.
669 (() => {
670 const duration = (ms) => {
671 if (!(ms > 0)) return '0s';
672 if (ms < 1000) return `${Math.floor(ms)}ms`;
673 let seconds = Math.round(ms / 1000);
674 const hours = Math.floor(seconds / 3600);
675 seconds -= hours * 3600;
676 const minutes = Math.floor(seconds / 60);
677 seconds -= minutes * 60;
678 if (hours > 0 && minutes === 0 && seconds === 0) return `${hours}h`;
679 if (hours > 0 && seconds === 0) return `${hours}h ${minutes}m`;
680 if (hours > 0) return `${hours}h ${minutes}m ${seconds}s`;
681 if (minutes > 0 && seconds === 0) return `${minutes}m`;
682 if (minutes > 0) return `${minutes}m ${seconds}s`;
683 return `${seconds}s`;
684 };
693 const duration = (ms) => {
694 if (!(ms > 0)) return '0s';
695 if (ms < 1000) return `${Math.floor(ms)}ms`;
696 let seconds = Math.round(ms / 1000);
697 const hours = Math.floor(seconds / 3600);
698 seconds -= hours * 3600;
699 const minutes = Math.floor(seconds / 60);
700 seconds -= minutes * 60;
701 if (hours > 0 && minutes === 0 && seconds === 0) return `${hours}h`;
702 if (hours > 0 && seconds === 0) return `${hours}h ${minutes}m`;
703 if (hours > 0) return `${hours}h ${minutes}m ${seconds}s`;
704 if (minutes > 0 && seconds === 0) return `${minutes}m`;
705 if (minutes > 0) return `${minutes}m ${seconds}s`;
706 return `${seconds}s`;
707 };
685 708
686 const since = (unix, now) => {
687 if (!unix) return '';
688 const age = now - unix * 1000;
689 if (age < 60000) return 'just now';
690 if (age < 3600000) return `${Math.floor(age / 60000)}m ago`;
691 if (age < 86400000) return `${Math.floor(age / 3600000)}h ago`;
692 return `${Math.floor(age / 86400000)}d ago`;
693 };
709 const since = (unix, now) => {
710 if (!unix) return '';
711 const age = now - unix * 1000;
712 if (age < 60000) return 'just now';
713 if (age < 3600000) return `${Math.floor(age / 60000)}m ago`;
714 if (age < 86400000) return `${Math.floor(age / 3600000)}h ago`;
715 return `${Math.floor(age / 86400000)}d ago`;
716 };
694 717
718 // Relative times and live durations. A run that is waiting or running would
719 // otherwise show a frozen duration until the next page load, and asking the
720 // server every second for a clock would be wasteful.
721 (() => {
695 722 const set = (element, value) => {
696 723 if (element.textContent !== value) element.textContent = value;
697 724 };
@@ -835,20 +862,90 @@ const fitTextarea = (area) => {
835 862 });
836 863 })();
837 864
865 // Live regions. A page in an unfocused window is not being watched, so its polls
866 // stop asking the server for an answer nobody reads. The last answer stays on
867 // screen with how old it is, because a duration that keeps counting beside a
868 // status that stopped moving is a lie. Returning to the window refreshes at once
869 // instead of waiting out the interval: htmx polls listen for vole-refresh, and
870 // the run page's own loop resumes on the same event. Only queued and running
871 // rows are marked; a finished run cannot change its word.
872 //
838 873 // HTMX compiles an hx-trigger filter with Function(), which the CSP forbids
839 // (script-src 'self'). The polling elements therefore say a plain "every Ns" and
840 // this guard skips a tick while the tab is hidden, which is the one thing their
841 // old [document.visibilityState === 'visible'] filters did. A later filter would
842 // be the CSP error again, so pages keep their triggers filter-free.
874 // (script-src 'self'), so the skip is here, on htmx:beforeRequest, and not in the
875 // trigger. An hx-trigger that grows a filter is the CSP error again.
843 876 (() => {
844 const polls = (elt) => {
845 const trigger = elt && elt.getAttribute && elt.getAttribute('hx-trigger');
846 return trigger != null && /(^|,)\s*every\s/.test(trigger);
877 const note = document.querySelector('[data-live-note]');
878 const regions = new Set();
879 // The markup was rendered just now, so the page's own time is the age of
880 // everything on it until a poll replaces part of it.
881 const pageTime = Date.now();
882
883 const regionOf = (element) => (element && element.closest ? element.closest('[data-live]') : null);
884
885 const sync = () => {
886 if (!note) return;
887 if (!regions.size) {
888 note.hidden = true;
889 document.body.classList.remove('is-stale');
890 return;
891 }
892 let oldest = Infinity;
893 regions.forEach((region) => {
894 oldest = Math.min(oldest, Number(region.dataset.refreshedAt) || pageTime);
895 });
896 document.body.classList.add('is-stale');
897 note.hidden = false;
898 note.textContent = `updates paused · last checked ${since(oldest / 1000, Date.now())}`;
899 };
900
901 const mark = (region) => {
902 if (!region || region.classList.contains('is-stale')) return;
903 if (!region.dataset.refreshedAt) region.dataset.refreshedAt = String(pageTime);
904 region.classList.add('is-stale');
905 regions.add(region);
906 sync();
847 907 };
908
909 const fresh = (region) => {
910 if (!region) return;
911 region.dataset.refreshedAt = String(Date.now());
912 if (!region.classList.contains('is-stale')) return;
913 region.classList.remove('is-stale');
914 regions.delete(region);
915 sync();
916 };
917
918 document.querySelectorAll('[data-live]').forEach((region) => {
919 region.dataset.refreshedAt = String(pageTime);
920 });
921 document.addEventListener('vole-stale', (event) => mark(regionOf(event.target)));
922 document.addEventListener('vole-fresh', (event) => fresh(regionOf(event.target)));
923
924 // A poll that comes due while the window is unfocused is skipped, and that is
925 // the moment its answer stops being current.
848 926 document.body.addEventListener('htmx:beforeRequest', (event) => {
849 if (document.visibilityState === 'visible') return;
850 if (polls(event.detail.elt)) event.preventDefault();
927 if (document.hasFocus()) return;
928 const element = event.detail.elt;
929 const trigger = element && element.getAttribute ? element.getAttribute('hx-trigger') : '';
930 if (!trigger || !/(^|,)\s*every\s/.test(trigger)) return;
931 event.preventDefault();
932 mark(regionOf(element));
933 });
934 document.body.addEventListener('htmx:afterRequest', (event) => {
935 if (event.detail.successful) fresh(regionOf(event.detail.elt));
851 936 });
937
938 const refresh = () => {
939 if (document.hasFocus()) document.body.dispatchEvent(new CustomEvent('vole-refresh'));
940 };
941 window.addEventListener('focus', refresh);
942 document.addEventListener('visibilitychange', () => {
943 if (document.visibilityState === 'visible') refresh();
944 });
945
946 setInterval(() => {
947 if (document.visibilityState === 'visible' && regions.size) sync();
948 }, 1000);
852 949 })();
853 950
854 951 // The repository tabs poll their open counts, and a number changing while the