diff --git a/README.md b/README.md index b6bd64c..09b997f 100644 --- a/README.md +++ b/README.md @@ -144,6 +144,13 @@ app.get('/api/opengraph', async (req, res) => { Add your own authentication and rate limiting to this endpoint; otherwise it just moves the open quota from your key to your server. +### How many requests a card makes +Cards that ask for the same site with the same options share one request, and a +successful answer is reused for 60 seconds. Showing one link several times on a +page, or re-mounting a card, therefore costs one API request, not one per mount. +A request is cancelled when the last card waiting for it leaves the page. +`forceCacheUpdate` always makes a new request. + ## OpenGraph.io API Parameters ### Below is a list of parameters and their descriptions, which can be passed to the OpenGraph.io API through the opengraph-react component. diff --git a/package-lock.json b/package-lock.json index ab16c93..c413855 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "opengraph-react", - "version": "2.4.2", + "version": "2.5.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "opengraph-react", - "version": "2.4.2", + "version": "2.5.1", "license": "ISC", "dependencies": { "psl": "^1.9.0" diff --git a/package.json b/package.json index 51bfc32..7298a3a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "opengraph-react", - "version": "2.4.2", + "version": "2.5.1", "description": "Handy React components for www.opengraph.io", "main": "build/index.js", "files": [ diff --git a/src/__tests__/components.test.js b/src/__tests__/components.test.js index 7f99f0e..fb34a82 100644 --- a/src/__tests__/components.test.js +++ b/src/__tests__/components.test.js @@ -6,6 +6,7 @@ import LinkedInComponent from '../components/linkedIn'; import ErrorBoundary from '../components/error'; import { getProductInfo } from '../util/getProductInfo'; import { buildRequestUrl } from '../util/buildRequestUrl'; +import { requestResults, clearResultsCache } from '../util/requestResults'; const ogResponse = { openGraph: { title: 'Example', url: 'https://example.com/', image: { url: 'https://example.com/og.png' } }, @@ -20,6 +21,7 @@ const mockFetch = (body) => { afterEach(() => { delete global.fetch; + clearResultsCache(); }); describe('default fetch path', () => { @@ -99,3 +101,112 @@ describe('video iframe', () => { } }); }); + +// OGR-005 follow-up (#46): every mount used to issue its own request, with no +// way to stop one whose card had already left the page. In direct mode each of +// those requests spends the site's API key from a visitor's browser. +describe('request sharing', () => { + const tick = () => new Promise((resolve) => setTimeout(resolve, 0)); + + it('makes one request when the same card is mounted several times', async () => { + const fetchMock = mockFetch(ogResponse); + const { container } = render( +
+ + + +
+ ); + + await waitFor(() => expect(container.querySelectorAll('img').length).toBeGreaterThanOrEqual(2)); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('makes one request under React.StrictMode', async () => { + const fetchMock = mockFetch(ogResponse); + const { container } = render( + + + + ); + + await waitFor(() => expect(container.querySelector('.wrapperLarge')).not.toBeNull()); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(fetchMock.mock.calls[0][1].signal.aborted).toBe(false); + }); + + it('reuses a recent answer for a later mount, and asks again for a different site', async () => { + const fetchMock = mockFetch(ogResponse); + const first = render(); + await waitFor(() => expect(first.container.querySelector('.wrapperLarge')).not.toBeNull()); + first.unmount(); + + const second = render(); + await waitFor(() => expect(second.container.querySelector('.wrapperLarge')).not.toBeNull()); + expect(fetchMock).toHaveBeenCalledTimes(1); + + const third = render(); + expect(fetchMock).toHaveBeenCalledTimes(2); + await waitFor(() => expect(third.container.querySelector('.wrapperLarge')).not.toBeNull()); + }); + + it('always asks again when forceCacheUpdate is set', async () => { + const fetchMock = mockFetch(ogResponse); + const first = render(); + await waitFor(() => expect(first.container.querySelector('.wrapperLarge')).not.toBeNull()); + first.unmount(); + + const second = render(); + expect(fetchMock).toHaveBeenCalledTimes(2); + await waitFor(() => expect(second.container.querySelector('.wrapperLarge')).not.toBeNull()); + }); + + it('aborts a request once the only card waiting for it unmounts', async () => { + global.fetch = jest.fn(() => new Promise(() => {})); + const { unmount } = render(); + const { signal } = global.fetch.mock.calls[0][1]; + expect(signal.aborted).toBe(false); + + unmount(); + await tick(); + expect(signal.aborted).toBe(true); + }); + + it('keeps a shared request alive while another card still waits for it', async () => { + global.fetch = jest.fn(() => new Promise(() => {})); + const first = render(); + render(); + expect(global.fetch).toHaveBeenCalledTimes(1); + + first.unmount(); + await tick(); + expect(global.fetch.mock.calls[0][1].signal.aborted).toBe(false); + }); + + it('does not remember an error response or a failed request', async () => { + mockFetch({ error: { code: 101, message: 'Invalid API key' } }); + await requestResults('https://opengraph.io/api/1.1/site/x?app_id=bad').promise; + mockFetch(ogResponse); + const body = await requestResults('https://opengraph.io/api/1.1/site/x?app_id=bad').promise; + expect(body).toEqual(ogResponse); + + global.fetch = jest.fn(() => Promise.reject(new Error('offline'))); + await expect(requestResults('https://opengraph.io/api/1.1/site/y').promise).rejects.toThrow('offline'); + mockFetch(ogResponse); + await expect(requestResults('https://opengraph.io/api/1.1/site/y').promise).resolves.toEqual(ogResponse); + }); + + it('does not update a card after it unmounted', async () => { + let resolveFetch; + global.fetch = jest.fn(() => new Promise((resolve) => { resolveFetch = resolve; })); + const errors = jest.spyOn(console, 'error').mockImplementation(() => {}); + const keep = render(); + const gone = render(); + + gone.unmount(); + resolveFetch({ json: () => Promise.resolve(ogResponse) }); + await waitFor(() => expect(keep.container.querySelector('.wrapperLarge')).not.toBeNull()); + expect(errors).not.toHaveBeenCalled(); + errors.mockRestore(); + }); +}); diff --git a/src/index.js b/src/index.js index fa60ac2..15afc43 100644 --- a/src/index.js +++ b/src/index.js @@ -5,6 +5,7 @@ import RenderSmall from './components/small'; import { getResultsToUse } from './util/getResultsToUse'; import { buildRequestUrl } from './util/buildRequestUrl'; +import { requestResults } from './util/requestResults'; import ErrorBoundary from './components/error'; import XComponent from './components/x'; import FacebookComponent from './components/facebook'; @@ -27,29 +28,41 @@ const OpenGraphReactComponent = (props) => { React.useEffect(() => { - const fetchResults = async (url) => { - try { - const response = await fetch(url); - const result = await response.json(); - if (result.error) { - setError(result.error); + if (dontMakeCall) { + setResult(getResultsToUse(results)); + return undefined; + } + + const url = buildRequestUrl({ + site, appId, proxyUrl, acceptLang, + useProxy, forceCacheUpdate, fullRender, + usePremium, useSuperior, disableAutoProxy, + }); + + // Identical requests are shared, and a request nobody is waiting for any + // more is aborted, so mounting the same card many times (a list, a + // re-render, StrictMode) costs one API request instead of one per mount. + let active = true; + const request = requestResults(url, { skipCache: Boolean(forceCacheUpdate) }); + + request.promise.then( + (body) => { + if (!active) return; + if (body && body.error) { + setError(body.error); } else { - setResult(prev => ({ ...prev, ...result })); + setResult(prev => ({ ...prev, ...body })); } - } catch (error) { - setError(error); + }, + (err) => { + if (active) setError(err); } - } + ); - if (dontMakeCall) { - setResult(getResultsToUse(results)); - } else { - fetchResults(buildRequestUrl({ - site, appId, proxyUrl, acceptLang, - useProxy, forceCacheUpdate, fullRender, - usePremium, useSuperior, disableAutoProxy, - })); - } + return () => { + active = false; + request.release(); + }; }, [ ]); // The fetch path only ever filled `result`, so cards got a null diff --git a/src/util/requestResults.js b/src/util/requestResults.js new file mode 100644 index 0000000..c4283f8 --- /dev/null +++ b/src/util/requestResults.js @@ -0,0 +1,85 @@ +// How long a successful response is reused. Short on purpose: it is there to +// collapse the burst of identical requests a page makes while it renders +// (several cards for one URL, a list re-mounting, React StrictMode's double +// mount), not to act as a long-lived cache. +const DEFAULT_TTL_MS = 60 * 1000; +const MAX_ENTRIES = 100; + +// url -> { promise, controller, subscribers, settled, expires } +const entries = new Map(); + +const forget = (url, entry) => { + if (entries.get(url) === entry) entries.delete(url); +}; + +const startRequest = (url, ttlMs) => { + const controller = typeof AbortController !== 'undefined' ? new AbortController() : null; + const entry = { controller, subscribers: 0, settled: false, expires: 0 }; + + entry.promise = fetch(url, controller ? { signal: controller.signal } : undefined) + .then((response) => response.json()) + .then( + (body) => { + entry.settled = true; + entry.expires = Date.now() + ttlMs; + // An error body (bad key, quota, unreachable site) is not worth + // remembering: the next mount should ask again. + if (!body || body.error) forget(url, entry); + return body; + }, + (err) => { + entry.settled = true; + forget(url, entry); + throw err; + } + ); + // Every subscriber may have gone by the time this settles. + entry.promise.catch(() => {}); + + if (entries.size >= MAX_ENTRIES) { + entries.delete(entries.keys().next().value); + } + entries.set(url, entry); + return entry; +}; + +/** + * Ask for an API response, sharing one network request between every caller + * that wants the same URL at the same time or shortly after. + * + * Returns the shared promise and a `release` function. Call `release` when the + * caller no longer wants the answer (the component unmounted): once nobody is + * waiting, the request is aborted instead of running on and spending a + * request against the API key for a card that is no longer on the page. + */ +export const requestResults = (url, { skipCache = false, ttlMs = DEFAULT_TTL_MS } = {}) => { + let entry = entries.get(url); + const fresh = entry && (!entry.settled || entry.expires > Date.now()); + if (!fresh || skipCache) { + entry = startRequest(url, ttlMs); + } + + entry.subscribers += 1; + let released = false; + + return { + promise: entry.promise, + release: () => { + if (released) return; + released = true; + entry.subscribers -= 1; + // Decided on the next tick, not now: React StrictMode (and a keyed + // re-render) unmounts and remounts straight away, and the remount should + // pick this request up rather than abort it and start a second one. + setTimeout(() => { + if (!entry.settled && entry.subscribers === 0) { + forget(url, entry); + if (entry.controller) entry.controller.abort(); + } + }, 0); + }, + }; +}; + +/** Drop every remembered response. */ +export const clearResultsCache = () => entries.clear(); diff --git a/webpack.config.js b/webpack.config.js index c5ef710..dd00da7 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -2,6 +2,8 @@ const path = require('path'); module.exports = { mode: 'production', + // Ship a source map so consumers can read what the published bundle was built from. + devtool: 'source-map', entry: './src/index.js', output: { path: path.resolve(__dirname, 'build'),