Skip to content

Commit db501c7

Browse files
allensquareSquirtle Squadclaude
committed
fix(github): retry a failed media renewal a few times
When a renewal read fails, or the renewed signed link fails too, media that still has no newer link to try now reads again after 30 seconds, at most three times until a signed link loads. Issue panels do not poll, so before this they stayed broken until reopened. One read and one timer at most; a link a poll delivers is tried first; unmount clears the timer. Public media and media whose own link loads are unchanged. Co-authored-by: Squirtle Squad <ec57954349ef49ce554b9cda062c34933dd3a085cf82278bb0e955efea492c7e@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Allen Tsai <[email protected]>
1 parent f4de506 commit db501c7

2 files changed

Lines changed: 257 additions & 15 deletions

File tree

‎src/bundled/github/GitHubBody.test.tsx‎

Lines changed: 182 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ const metadata = `<details><summary>before.mp4</summary><video src="${signedBefo
3131

3232
afterEach(() => {
3333
cleanup();
34+
vi.useRealTimers();
3435
vi.unstubAllGlobals();
3536
vi.restoreAllMocks();
3637
});
@@ -271,7 +272,7 @@ it("takes a signed link only when media's own link fails, renewing it when that
271272
expect(container.querySelector("video")).toBe(video);
272273
expect(video).toHaveAttribute("src", before);
273274
await act(async () => read.resolve());
274-
// A renewed link that fails before loading does not read again.
275+
// A renewed link that fails before loading does not read again at once.
275276
fireEvent.error(screen.getByAltText("Screenshot"));
276277
expect(refresh).toHaveBeenCalledOnce();
277278
});
@@ -312,6 +313,186 @@ it("reads again after a failed renewal, one read at a time", async () => {
312313
expect(refresh).toHaveBeenCalledTimes(2);
313314
});
314315

316+
const privateImage = (jwt: string) =>
317+
`<img src="${signedImage(jwt)}" alt="Screenshot">`;
318+
const privateBody = `![Screenshot](${image})`;
319+
const settle = () => act(async () => {});
320+
const wait = (ms: number) =>
321+
act(async () => {
322+
await vi.advanceTimersByTimeAsync(ms);
323+
});
324+
// Its own link fails, then its signed link: one read.
325+
const failTwice = () => {
326+
fireEvent.error(screen.getByAltText("Screenshot"));
327+
fireEvent.error(screen.getByAltText("Screenshot"));
328+
};
329+
330+
it("reads again 30 seconds after a failed renewal, three times at most", async () => {
331+
vi.useFakeTimers();
332+
const refresh = vi.fn(() => Promise.reject(new Error("Not Found")));
333+
render(
334+
<GitHubBody
335+
url={url}
336+
body={privateBody}
337+
bodyHtml={privateImage("1")}
338+
refresh={refresh}
339+
/>,
340+
);
341+
failTwice();
342+
expect(refresh).toHaveBeenCalledOnce();
343+
await settle();
344+
await wait(29_999);
345+
expect(refresh).toHaveBeenCalledOnce();
346+
await wait(1);
347+
expect(refresh).toHaveBeenCalledTimes(2);
348+
await wait(30_000);
349+
await wait(30_000);
350+
expect(refresh).toHaveBeenCalledTimes(4);
351+
// Then it stops, leaving the original link.
352+
await wait(5 * 60_000);
353+
expect(refresh).toHaveBeenCalledTimes(4);
354+
expect(vi.getTimerCount()).toBe(0);
355+
expect(screen.getByRole("link", { name: "Screenshot" })).toHaveAttribute(
356+
"href",
357+
image,
358+
);
359+
});
360+
361+
it("stops retrying once a renewed link loads, and retries afresh after", async () => {
362+
vi.useFakeTimers();
363+
let reads = 0;
364+
const refresh = vi.fn(async () => {
365+
reads += 1;
366+
if (reads !== 2) throw new Error("Not Found");
367+
view.rerender(
368+
<GitHubBody
369+
url={url}
370+
body={privateBody}
371+
bodyHtml={privateImage("2")}
372+
refresh={refresh}
373+
/>,
374+
);
375+
});
376+
const view = render(
377+
<GitHubBody
378+
url={url}
379+
body={privateBody}
380+
bodyHtml={privateImage("1")}
381+
refresh={refresh}
382+
/>,
383+
);
384+
failTwice();
385+
await settle();
386+
await wait(30_000);
387+
expect(refresh).toHaveBeenCalledTimes(2);
388+
expect(screen.getByAltText("Screenshot")).toHaveAttribute(
389+
"src",
390+
signedImage("2"),
391+
);
392+
fireEvent.load(screen.getByAltText("Screenshot"));
393+
await wait(5 * 60_000);
394+
expect(refresh).toHaveBeenCalledTimes(2);
395+
// When it expires later it reads at once, then has three retries again.
396+
fireEvent.error(screen.getByAltText("Screenshot"));
397+
expect(refresh).toHaveBeenCalledTimes(3);
398+
await settle();
399+
await wait(5 * 60_000);
400+
expect(refresh).toHaveBeenCalledTimes(6);
401+
});
402+
403+
it("cancels a pending retry on unmount, and schedules none after it", async () => {
404+
vi.useFakeTimers();
405+
const refresh = vi.fn(() => Promise.reject(new Error("Not Found")));
406+
const first = render(
407+
<GitHubBody
408+
url={url}
409+
body={privateBody}
410+
bodyHtml={privateImage("1")}
411+
refresh={refresh}
412+
/>,
413+
);
414+
failTwice();
415+
await settle();
416+
expect(vi.getTimerCount()).toBe(1);
417+
first.unmount();
418+
expect(vi.getTimerCount()).toBe(0);
419+
await wait(60_000);
420+
expect(refresh).toHaveBeenCalledOnce();
421+
422+
const read = deferred<void>();
423+
const pending = vi.fn(() => read.promise);
424+
const second = render(
425+
<GitHubBody
426+
url={url}
427+
body={privateBody}
428+
bodyHtml={privateImage("1")}
429+
refresh={pending}
430+
/>,
431+
);
432+
failTwice();
433+
second.unmount();
434+
await act(async () => read.reject(new Error("Not Found")));
435+
expect(vi.getTimerCount()).toBe(0);
436+
await wait(60_000);
437+
expect(pending).toHaveBeenCalledOnce();
438+
});
439+
440+
it("never schedules a retry for public media or media whose own link loads", async () => {
441+
vi.useFakeTimers();
442+
const refresh = vi.fn(() => Promise.reject(new Error("Not Found")));
443+
render(
444+
<GitHubBody
445+
url={url}
446+
body={`![Asset](${image})\n\n![Screenshot](${after})`}
447+
bodyHtml={`<img src="${image}" alt="Asset"><img src="https://private-user-images.githubusercontent.com/1888043/2-dd1f7e4f-e2a4-4aec-b661-cb45032f29c5.png?jwt=1" alt="Screenshot">`}
448+
refresh={refresh}
449+
/>,
450+
);
451+
fireEvent.error(screen.getByAltText("Asset"));
452+
fireEvent.load(screen.getByAltText("Screenshot"));
453+
expect(screen.getByAltText("Screenshot")).toHaveAttribute("src", after);
454+
await settle();
455+
expect(vi.getTimerCount()).toBe(0);
456+
await wait(5 * 60_000);
457+
expect(refresh).not.toHaveBeenCalled();
458+
});
459+
460+
it("tries a link a poll delivers before the retry instead of reading again", async () => {
461+
vi.useFakeTimers();
462+
const refresh = vi.fn(() => Promise.reject(new Error("Not Found")));
463+
const { rerender } = render(
464+
<GitHubBody
465+
url={url}
466+
body={privateBody}
467+
bodyHtml={privateImage("1")}
468+
refresh={refresh}
469+
/>,
470+
);
471+
failTwice();
472+
await settle();
473+
await wait(10_000);
474+
// A PR poll brings a newer link; the failed image takes it.
475+
rerender(
476+
<GitHubBody
477+
url={url}
478+
body={privateBody}
479+
bodyHtml={privateImage("2")}
480+
refresh={refresh}
481+
/>,
482+
);
483+
expect(screen.getByAltText("Screenshot")).toHaveAttribute(
484+
"src",
485+
signedImage("2"),
486+
);
487+
// Still loading when the retry is due: nothing is read.
488+
await wait(20_000);
489+
expect(refresh).toHaveBeenCalledOnce();
490+
fireEvent.load(screen.getByAltText("Screenshot"));
491+
await wait(5 * 60_000);
492+
expect(refresh).toHaveBeenCalledOnce();
493+
expect(vi.getTimerCount()).toBe(0);
494+
});
495+
315496
it("keeps public and raw media on their own links without reading again", () => {
316497
const raw = "https://raw.githubusercontent.com/block/buzz-app/main/icon.png";
317498
const refresh = vi.fn();

‎src/bundled/github/GitHubBody.tsx‎

Lines changed: 75 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
isValidElement,
66
memo,
77
useContext,
8+
useEffect,
89
useMemo,
910
useRef,
1011
useState,
@@ -191,8 +192,8 @@ function EmbeddedAttachment({
191192
children(src: string): ReactNode;
192193
fallback: ReactNode;
193194
caption: ReactNode;
194-
/** A signed link loaded, or failed. */
195-
onMedia?: ((loaded: boolean) => void) | undefined;
195+
/** The signed link `src` loaded, or failed. */
196+
onMedia?: ((loaded: boolean, src: string) => void) | undefined;
196197
}) {
197198
const [loaded, setLoaded] = useState(false);
198199
// Media loads its own link first. When that fails it takes the signed link,
@@ -207,7 +208,7 @@ function EmbeddedAttachment({
207208
const show = (next: boolean) => {
208209
setLoaded(next);
209210
setFailed(!next);
210-
if (shown !== source) onMedia?.(next);
211+
if (shown !== source) onMedia?.(next, shown);
211212
};
212213
return (
213214
<div
@@ -260,10 +261,15 @@ const components: Components = {
260261
),
261262
};
262263

264+
const RETRY_DELAY = 30_000;
265+
const MAX_RETRIES = 3;
266+
263267
/** A private repository's media links need a GitHub sign-in; `bodyHtml` has
264268
* signed links for them that expire within minutes and change on every read.
265269
* Media whose own link fails takes its signed link, and when that fails reads
266-
* GitHub again with `refresh` and takes the link read. */
270+
* GitHub again with `refresh` and takes the link read. When a read leaves
271+
* media failed with no newer link to try, it reads again after 30 seconds, at
272+
* most three times until a signed link loads. */
267273
export const GitHubBody = memo(function GitHubBody({
268274
body,
269275
bodyHtml,
@@ -283,22 +289,76 @@ export const GitHubBody = memo(function GitHubBody({
283289
() => (bounded ? attachmentMetadata(bodyHtml) : new Map()),
284290
[bounded, bodyHtml],
285291
);
286-
// One read at a time; media that failed since it last loaded does not
287-
// read again.
288-
const failed = useRef(new Set<string>());
292+
// One read at a time. Media whose signed link failed since it last loaded
293+
// (kept with that link) does not read again at once; it waits for a retry.
294+
const failed = useRef(new Map<string, string>());
289295
const reading = useRef(false);
296+
const retry = useRef<{
297+
timer?: ReturnType<typeof setTimeout> | undefined;
298+
count: number;
299+
stopped?: boolean;
300+
}>({ count: 0 });
301+
// A retry reads with the latest body's links and refresh.
302+
const latest = useRef({ metadata, refresh });
303+
useEffect(() => {
304+
latest.current = { metadata, refresh };
305+
}, [metadata, refresh]);
306+
useEffect(() => {
307+
const state = retry.current;
308+
state.stopped = false;
309+
return () => {
310+
state.stopped = true;
311+
clearTimeout(state.timer);
312+
state.timer = undefined;
313+
};
314+
}, []);
290315
if (!bounded) return <div className={styles.plainBody}>{body}</div>;
291316

292-
const renew = (source: string, loaded: boolean) => {
293-
if (loaded) failed.current.delete(source);
294-
if (loaded || !refresh || failed.current.has(source)) return;
295-
failed.current.add(source);
296-
if (reading.current) return;
317+
// Failed media whose latest signed link is the one that failed.
318+
const stuck = () =>
319+
[...failed.current].some(
320+
([source, link]) => signedUrl(source, latest.current.metadata) === link,
321+
);
322+
const read = () => {
323+
const current = latest.current.refresh;
324+
if (!current) return;
297325
reading.current = true;
298326
const done = () => {
299327
reading.current = false;
328+
later();
300329
};
301-
refresh().then(done, done);
330+
current().then(done, done);
331+
};
332+
const later = () => {
333+
const state = retry.current;
334+
if (
335+
state.stopped ||
336+
state.timer ||
337+
reading.current ||
338+
state.count >= MAX_RETRIES ||
339+
!stuck()
340+
)
341+
return;
342+
state.timer = setTimeout(() => {
343+
state.timer = undefined;
344+
// A read in flight retries when it settles; links read meanwhile are
345+
// tried first.
346+
if (reading.current || !stuck()) return;
347+
state.count += 1;
348+
read();
349+
}, RETRY_DELAY);
350+
};
351+
const renew = (source: string, loaded: boolean, link: string) => {
352+
if (!refresh) return;
353+
if (loaded) {
354+
failed.current.delete(source);
355+
retry.current.count = 0;
356+
return;
357+
}
358+
const known = failed.current.has(source);
359+
failed.current.set(source, link);
360+
if (known || reading.current) later();
361+
else read();
302362
};
303363

304364
const media: Media = (source, label, image = false, description) => {
@@ -316,7 +376,8 @@ export const GitHubBody = memo(function GitHubBody({
316376
source={source}
317377
{...(signed && {
318378
signed,
319-
onMedia: (loaded: boolean) => renew(source, loaded),
379+
onMedia: (loaded: boolean, link: string) =>
380+
renew(source, loaded, link),
320381
})}
321382
fallback={link}
322383
caption={

0 commit comments

Comments
 (0)