Invites and fixed image caching
This commit is contained in:
1 parent
1706a906f0
commit
693a30f437
7 files changed
+193
-5
No files matched your search
+5
-2
@@ -1,3 +1,4 @@
|
|||||||
|
import { photoCacheControl } from './storage/photoCache.js';
|
||||||
import { canUpdateWorkspaceSettings, subscriptionAllowsWrite } from './workspaceAccess.js';
|
import { canUpdateWorkspaceSettings, subscriptionAllowsWrite } from './workspaceAccess.js';
|
||||||
import { buildWorkspaceInviteEmail } from './emails/workspaceInviteEmail.js';
|
import { buildWorkspaceInviteEmail } from './emails/workspaceInviteEmail.js';
|
||||||
import { exportFlock } from './repositories/flockExportRepository.js';
|
import { exportFlock } from './repositories/flockExportRepository.js';
|
||||||
@@ -3496,6 +3497,8 @@ app.post(
|
|||||||
);
|
);
|
||||||
|
|
||||||
app.get('/api/birds/:birdId/photo', async (req: Request, res: Response, next: NextFunction) => {
|
app.get('/api/birds/:birdId/photo', async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
// Invalid tokens, missing photos and upstream failures must never be cached.
|
||||||
|
res.setHeader('Cache-Control', 'no-store');
|
||||||
try {
|
try {
|
||||||
const token = typeof req.query.token === 'string' ? req.query.token : '';
|
const token = typeof req.query.token === 'string' ? req.query.token : '';
|
||||||
const photoAccess = verifyBirdPhotoAccessToken(token);
|
const photoAccess = verifyBirdPhotoAccessToken(token);
|
||||||
@@ -3525,9 +3528,8 @@ app.get('/api/birds/:birdId/photo', async (req: Request, res: Response, next: Ne
|
|||||||
expiresInSeconds: 5 * 60,
|
expiresInSeconds: 5 * 60,
|
||||||
});
|
});
|
||||||
|
|
||||||
res.setHeader('Cache-Control', 'private, max-age=900');
|
|
||||||
|
|
||||||
if (photoDeliveryMode === 'redirect') {
|
if (photoDeliveryMode === 'redirect') {
|
||||||
|
res.setHeader('Cache-Control', photoCacheControl('redirect', photoAccess.expiresAt));
|
||||||
res.redirect(302, signedUrl);
|
res.redirect(302, signedUrl);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -3543,6 +3545,7 @@ app.get('/api/birds/:birdId/photo', async (req: Request, res: Response, next: Ne
|
|||||||
const contentLength = imageResponse.headers.get('content-length');
|
const contentLength = imageResponse.headers.get('content-length');
|
||||||
const imageBuffer = Buffer.from(await imageResponse.arrayBuffer());
|
const imageBuffer = Buffer.from(await imageResponse.arrayBuffer());
|
||||||
|
|
||||||
|
res.setHeader('Cache-Control', photoCacheControl('proxy', photoAccess.expiresAt));
|
||||||
res.setHeader('Content-Type', contentType);
|
res.setHeader('Content-Type', contentType);
|
||||||
|
|
||||||
if (contentLength) {
|
if (contentLength) {
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import test from 'node:test';
|
||||||
|
import { photoCacheControl } from './photoCache.js';
|
||||||
|
|
||||||
|
test('storage redirects cannot be cached beyond the signed destination lifetime', () => {
|
||||||
|
assert.equal(photoCacheControl('redirect', 1900, 1000), 'no-store');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('proxy caching is bounded by the remaining app token lifetime', () => {
|
||||||
|
assert.equal(photoCacheControl('proxy', 1900, 1000), 'private, max-age=900, must-revalidate');
|
||||||
|
assert.equal(photoCacheControl('proxy', 1050, 1000), 'private, max-age=50, must-revalidate');
|
||||||
|
assert.equal(photoCacheControl('proxy', 999, 1000), 'private, max-age=0, must-revalidate');
|
||||||
|
});
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
// Never cache a redirect to a signed storage URL: its lifetime is independent of
|
||||||
|
// the app token. Successful proxy responses cannot outlive the app token.
|
||||||
|
export const photoCacheControl = (mode: 'proxy' | 'redirect', expiresAt: number, now = Math.floor(Date.now() / 1000)) =>
|
||||||
|
mode === 'redirect' ? 'no-store' : `private, max-age=${Math.max(0, Math.min(900, expiresAt - now))}, must-revalidate`;
|
||||||
+25
-3
@@ -1,3 +1,4 @@
|
|||||||
|
import { usePhotoRefresh } from './usePhotoRefresh';
|
||||||
import { FlockSwitcher } from './FlockSwitcher';
|
import { FlockSwitcher } from './FlockSwitcher';
|
||||||
import { combineLocationOwnerMarkers } from './birdTimeline';
|
import { combineLocationOwnerMarkers } from './birdTimeline';
|
||||||
import { BehaviorJournal } from './BehaviorJournal';
|
import { BehaviorJournal } from './BehaviorJournal';
|
||||||
@@ -2284,6 +2285,27 @@ function App() {
|
|||||||
const [expandedSettingsSection, setExpandedSettingsSection] = useState<SettingsSection | null>(null);
|
const [expandedSettingsSection, setExpandedSettingsSection] = useState<SettingsSection | null>(null);
|
||||||
|
|
||||||
const flockBirds = useMemo(() => sortBirdsByName([...birds, ...memorializedBirds]), [birds, memorializedBirds]);
|
const flockBirds = useMemo(() => sortBirdsByName([...birds, ...memorializedBirds]), [birds, memorializedBirds]);
|
||||||
|
const handlePhotoError = usePhotoRefresh({
|
||||||
|
apiBaseUrl, token: authToken, workspaceId: workspace?.id, publicProfileCode,
|
||||||
|
fallback: defaultBirdPhoto,
|
||||||
|
onPhotos: (photos) => {
|
||||||
|
const urls = new Map(photos.map((photo) => [photo.id, photo.photoDataUrl]));
|
||||||
|
const update = (current: Bird[]) => current.map((bird) => urls.has(bird.id)
|
||||||
|
? { ...bird, photoDataUrl: urls.get(bird.id) ?? null } : bird);
|
||||||
|
setBirds(update);
|
||||||
|
setMemorializedBirds(update);
|
||||||
|
setPublicProfile((current) => current && urls.has(current.id)
|
||||||
|
? { ...current, photoDataUrl: urls.get(current.id) ?? null } : current);
|
||||||
|
// Renew the editor preview only if it still matches the saved photo.
|
||||||
|
// Never replace an uploaded/cropped photo or a deliberate removal.
|
||||||
|
const editingBird = [...birds, ...memorializedBirds].find((bird) => bird.id === editingBirdId);
|
||||||
|
if (editingBird && urls.has(editingBirdId)) {
|
||||||
|
setBirdForm((current) => current.photoDataUrl === editingBird.photoDataUrl
|
||||||
|
? { ...current, photoDataUrl: urls.get(editingBirdId) ?? '' } : current);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
const selectedBird = useMemo(
|
const selectedBird = useMemo(
|
||||||
() => flockBirds.find((bird) => bird.id === selectedBirdId) ?? null,
|
() => flockBirds.find((bird) => bird.id === selectedBirdId) ?? null,
|
||||||
[flockBirds, selectedBirdId],
|
[flockBirds, selectedBirdId],
|
||||||
@@ -5698,7 +5720,7 @@ function App() {
|
|||||||
|
|
||||||
if (shouldShowPublicProfilePage) {
|
if (shouldShowPublicProfilePage) {
|
||||||
return (
|
return (
|
||||||
<main className="auth-shell public-profile-shell">
|
<main className="auth-shell public-profile-shell" onErrorCapture={handlePhotoError}>
|
||||||
<section className="panel public-profile-card">
|
<section className="panel public-profile-card">
|
||||||
<a className="public-profile-logo-link" href="/" aria-label="Go to FlockPal sign in">
|
<a className="public-profile-logo-link" href="/" aria-label="Go to FlockPal sign in">
|
||||||
<img className="public-profile-logo" src={flockPalLandingArt} alt="FlockPal" />
|
<img className="public-profile-logo" src={flockPalLandingArt} alt="FlockPal" />
|
||||||
@@ -5895,7 +5917,7 @@ function App() {
|
|||||||
|
|
||||||
if (loading) {
|
if (loading) {
|
||||||
return (
|
return (
|
||||||
<main className="app-shell">
|
<main className="app-shell" onErrorCapture={handlePhotoError}>
|
||||||
<section className="hero-card">
|
<section className="hero-card">
|
||||||
<p>Loading flock data...</p>
|
<p>Loading flock data...</p>
|
||||||
</section>
|
</section>
|
||||||
@@ -6006,7 +6028,7 @@ function App() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="app-shell">
|
<main className="app-shell" onErrorCapture={handlePhotoError}>
|
||||||
<div className="side-rail">
|
<div className="side-rail">
|
||||||
<div className="brand-lockup">
|
<div className="brand-lockup">
|
||||||
<img className="side-nav-logo" src={flockPalLandingArt} alt="FlockPal" />
|
<img className="side-nav-logo" src={flockPalLandingArt} alt="FlockPal" />
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
export type PhotoRecord = { id: string; photoDataUrl: string | null };
|
||||||
|
export const PHOTO_REFRESH_INTERVAL_MS = 5 * 60_000;
|
||||||
|
|
||||||
|
// One request for all mounted photos; throttle failures without blocking later recovery.
|
||||||
|
export function createPhotoRefresher({ load, apply, now = Date.now }: {
|
||||||
|
load: (signal: AbortSignal) => Promise<PhotoRecord[]>;
|
||||||
|
apply: (photos: PhotoRecord[]) => void;
|
||||||
|
now?: () => number;
|
||||||
|
}) {
|
||||||
|
const controller = new AbortController();
|
||||||
|
let inFlight = false;
|
||||||
|
let lastAttempt = -Infinity;
|
||||||
|
return {
|
||||||
|
async refresh() {
|
||||||
|
if (controller.signal.aborted || inFlight || now() - lastAttempt < 30_000) return;
|
||||||
|
inFlight = true;
|
||||||
|
lastAttempt = now();
|
||||||
|
try {
|
||||||
|
const photos = await load(controller.signal);
|
||||||
|
if (!controller.signal.aborted) apply(photos);
|
||||||
|
} catch {
|
||||||
|
// Keep existing photos on transient failures; retry on the next focus/timer/error.
|
||||||
|
} finally {
|
||||||
|
inFlight = false;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
dispose() { controller.abort(); },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isExpiringPhotoUrl(src: string) {
|
||||||
|
try {
|
||||||
|
const url = new URL(src, window.location.href);
|
||||||
|
return /\/birds\/[^/]+\/photo$/.test(url.pathname) && url.searchParams.has('token');
|
||||||
|
} catch { return false; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { useEffect, useRef, type SyntheticEvent } from 'react';
|
||||||
|
import { createPhotoRefresher, isExpiringPhotoUrl, PHOTO_REFRESH_INTERVAL_MS, type PhotoRecord } from './photoRefresh';
|
||||||
|
|
||||||
|
export function usePhotoRefresh({ apiBaseUrl, token, workspaceId, publicProfileCode, onPhotos, fallback }: {
|
||||||
|
apiBaseUrl: string; token: string; workspaceId?: number; publicProfileCode: string;
|
||||||
|
onPhotos: (photos: PhotoRecord[]) => void; fallback: string;
|
||||||
|
}) {
|
||||||
|
const apply = useRef(onPhotos);
|
||||||
|
apply.current = onPhotos;
|
||||||
|
const refresh = useRef<(() => Promise<void>) | null>(null);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!publicProfileCode && (!token || !workspaceId)) return;
|
||||||
|
const refresher = createPhotoRefresher({
|
||||||
|
load: async (signal) => {
|
||||||
|
const path = publicProfileCode ? `/public/birds/${encodeURIComponent(publicProfileCode)}` : '/birds';
|
||||||
|
const response = await fetch(`${apiBaseUrl}${path}`, {
|
||||||
|
signal, cache: 'no-store',
|
||||||
|
headers: publicProfileCode ? {} : { Authorization: `Bearer ${token}` },
|
||||||
|
});
|
||||||
|
if (!response.ok) throw new Error('Unable to refresh photos.');
|
||||||
|
const data = await response.json();
|
||||||
|
return publicProfileCode ? (data.bird ? [data.bird] : []) : [...(data.birds ?? []), ...(data.memorializedBirds ?? [])];
|
||||||
|
},
|
||||||
|
apply: (photos) => apply.current(photos),
|
||||||
|
});
|
||||||
|
refresh.current = refresher.refresh;
|
||||||
|
const onResume = () => { if (document.visibilityState === 'visible') void refresher.refresh(); };
|
||||||
|
const timer = window.setInterval(onResume, PHOTO_REFRESH_INTERVAL_MS);
|
||||||
|
window.addEventListener('focus', onResume);
|
||||||
|
window.addEventListener('online', onResume);
|
||||||
|
document.addEventListener('visibilitychange', onResume);
|
||||||
|
return () => {
|
||||||
|
refresher.dispose();
|
||||||
|
refresh.current = null;
|
||||||
|
window.clearInterval(timer);
|
||||||
|
window.removeEventListener('focus', onResume);
|
||||||
|
window.removeEventListener('online', onResume);
|
||||||
|
document.removeEventListener('visibilitychange', onResume);
|
||||||
|
};
|
||||||
|
}, [apiBaseUrl, token, workspaceId, publicProfileCode]);
|
||||||
|
|
||||||
|
return (event: SyntheticEvent) => {
|
||||||
|
const image = event.target;
|
||||||
|
if (!(image instanceof Element)) return;
|
||||||
|
const attribute = image.localName === 'img' ? 'src' : image.localName === 'image' ? 'href' : null;
|
||||||
|
if (!attribute || !isExpiringPhotoUrl(image.getAttribute(attribute) ?? '')) return;
|
||||||
|
image.setAttribute(attribute, fallback);
|
||||||
|
void refresh.current?.();
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import test from 'node:test';
|
||||||
|
import { createPhotoRefresher } from '../src/photoRefresh.ts';
|
||||||
|
|
||||||
|
test('simultaneous image errors share a refresh, then can renew again after cooldown', async () => {
|
||||||
|
let now = 0;
|
||||||
|
let calls = 0;
|
||||||
|
let finish!: (photos: { id: string; photoDataUrl: string }[]) => void;
|
||||||
|
const applied: unknown[] = [];
|
||||||
|
const refresher = createPhotoRefresher({
|
||||||
|
now: () => now,
|
||||||
|
load: async () => { calls++; return new Promise((resolve) => { finish = resolve; }); },
|
||||||
|
apply: (photos) => applied.push(photos),
|
||||||
|
});
|
||||||
|
const first = refresher.refresh();
|
||||||
|
await refresher.refresh();
|
||||||
|
assert.equal(calls, 1);
|
||||||
|
finish([{ id: 'bird', photoDataUrl: 'renewed' }]);
|
||||||
|
await first;
|
||||||
|
assert.equal(applied.length, 1);
|
||||||
|
await refresher.refresh();
|
||||||
|
assert.equal(calls, 1);
|
||||||
|
now = 30_000;
|
||||||
|
const next = refresher.refresh();
|
||||||
|
finish([]);
|
||||||
|
await next;
|
||||||
|
assert.equal(calls, 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('logout or flock switching aborts requests and discards stale photo responses', async () => {
|
||||||
|
let finish!: (photos: { id: string; photoDataUrl: string }[]) => void;
|
||||||
|
let signal!: AbortSignal;
|
||||||
|
let applied = false;
|
||||||
|
const refresher = createPhotoRefresher({
|
||||||
|
load: async (requestSignal) => { signal = requestSignal; return new Promise((resolve) => { finish = resolve; }); },
|
||||||
|
apply: () => { applied = true; },
|
||||||
|
});
|
||||||
|
const pending = refresher.refresh();
|
||||||
|
refresher.dispose();
|
||||||
|
finish([{ id: 'old-flock-bird', photoDataUrl: 'stale' }]);
|
||||||
|
await pending;
|
||||||
|
assert.equal(signal.aborted, true);
|
||||||
|
assert.equal(applied, false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a failed refresh can recover on a later timer, focus, or reconnect', async () => {
|
||||||
|
let now = 0;
|
||||||
|
let attempts = 0;
|
||||||
|
let applied = false;
|
||||||
|
const refresher = createPhotoRefresher({
|
||||||
|
now: () => now,
|
||||||
|
load: async () => { if (++attempts === 1) throw new Error('offline'); return []; },
|
||||||
|
apply: () => { applied = true; },
|
||||||
|
});
|
||||||
|
await refresher.refresh();
|
||||||
|
assert.equal(applied, false);
|
||||||
|
now = 30_000;
|
||||||
|
await refresher.refresh();
|
||||||
|
assert.equal(applied, true);
|
||||||
|
});
|
||||||
Reference in new issue
Block a user