Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(javascript): add cache layer #274

Merged
merged 7 commits into from
Mar 23, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .github/actions/cache/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ runs:
key: |
${{ env.CACHE_VERSION }}-${{
hashFiles(
'clients/algoliasearch-client-javascript/packages/client-common/**'
'clients/algoliasearch-client-javascript/packages/client-common/src/**'
)}}

- name: Restore built JavaScript node requester
Expand All @@ -164,7 +164,7 @@ runs:
key: |
${{ env.CACHE_VERSION }}-${{
hashFiles(
'clients/algoliasearch-client-javascript/packages/requester-node-http/**'
'clients/algoliasearch-client-javascript/packages/requester-node-http/src/**'
)}}

- name: Restore built JavaScript browser requester
Expand All @@ -175,7 +175,7 @@ runs:
key: |
${{ env.CACHE_VERSION }}-${{
hashFiles(
'clients/algoliasearch-client-javascript/packages/requester-browser-xhr/**'
'clients/algoliasearch-client-javascript/packages/requester-browser-xhr/src/**'
)}}

# Restore JavaScript clients: used during 'cts' or 'codegen'
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ jobs:
key: |
${{ env.CACHE_VERSION }}-${{
hashFiles(
format('clients/algoliasearch-client-javascript/packages/{0}/**', matrix.client)
format('clients/algoliasearch-client-javascript/packages/{0}/src/**', matrix.client)
)}}

- name: Build '${{ matrix.client }}' client
Expand Down
24 changes: 12 additions & 12 deletions clients/algoliasearch-client-javascript/bundlesize.config.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,51 +2,51 @@
"files": [
{
"path": "packages/algoliasearch/dist/algoliasearch.umd.browser.js",
"maxSize": "6.50KB"
"maxSize": "6.90KB"
},
{
"path": "packages/client-abtesting/dist/client-abtesting.umd.browser.js",
"maxSize": "3.25KB"
"maxSize": "3.65KB"
},
{
"path": "packages/client-analytics/dist/client-analytics.umd.browser.js",
"maxSize": "4.00KB"
"maxSize": "4.20KB"
},
{
"path": "packages/client-insights/dist/client-insights.umd.browser.js",
"maxSize": "3.25KB"
"maxSize": "3.45KB"
},
{
"path": "packages/client-personalization/dist/client-personalization.umd.browser.js",
"maxSize": "3.25KB"
"maxSize": "3.60KB"
},
{
"path": "packages/client-query-suggestions/dist/client-query-suggestions.umd.browser.js",
"maxSize": "3.25KB"
"maxSize": "3.65KB"
},
{
"path": "packages/client-search/dist/client-search.umd.browser.js",
"maxSize": "5.25KB"
"maxSize": "5.65KB"
},
{
"path": "packages/client-sources/dist/client-sources.umd.browser.js",
"maxSize": "3.25KB"
"maxSize": "3.50KB"
},
{
"path": "packages/recommend/dist/recommend.umd.browser.js",
"maxSize": "3.25KB"
"maxSize": "3.55KB"
},
{
"path": "packages/client-common/dist/client-common.esm.node.js",
"maxSize": "3.00KB"
"maxSize": "3.45KB"
},
{
"path": "packages/requester-browser-xhr/dist/requester-browser-xhr.esm.node.js",
"maxSize": "1.00KB"
"maxSize": "900B"
},
{
"path": "packages/requester-node-http/dist/requester-node-http.esm.node.js",
"maxSize": "1.00KB"
"maxSize": "1.10KB"
}
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,20 @@ import type {
Host,
Requester,
} from '@experimental-api-clients-automation/client-common';
import {
createMemoryCache,
createFallbackableCache,
createBrowserLocalStorageCache,
} from '@experimental-api-clients-automation/client-common';
import type {
PersonalizationApi,
Region as PersonalizationRegion,
} from '@experimental-api-clients-automation/client-personalization/src/personalizationApi';
import { createPersonalizationApi } from '@experimental-api-clients-automation/client-personalization/src/personalizationApi';
import { createSearchApi } from '@experimental-api-clients-automation/client-search/src/searchApi';
import {
createSearchApi,
apiClientVersion,
} from '@experimental-api-clients-automation/client-search/src/searchApi';
import { createXhrRequester } from '@experimental-api-clients-automation/requester-browser-xhr';

// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
Expand All @@ -39,6 +47,14 @@ export function algoliasearch(
requester: options?.requester ?? createXhrRequester(),
userAgents: [{ segment: 'Browser' }],
authMode: 'WithinQueryParameters',
responsesCache: createMemoryCache(),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure if memory cache should be the default value here. Probably null cache for all (response, request, host for both node and browser). What do you think?

What do we already have for the v4 js client?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's the same here as the v4 js client, which seems to work well but I don't know much about the limitations here

requestsCache: createMemoryCache({ serializable: false }),
hostsCache: createFallbackableCache({
caches: [
createBrowserLocalStorageCache({ key: `${apiClientVersion}-${appId}` }),
createMemoryCache(),
],
}),
...options,
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ import type {
Host,
Requester,
} from '@experimental-api-clients-automation/client-common';
import {
createMemoryCache,
createNullCache,
} from '@experimental-api-clients-automation/client-common';
import type {
PersonalizationApi,
Region as PersonalizationRegion,
Expand Down Expand Up @@ -38,6 +42,9 @@ export function algoliasearch(
},
requester: options?.requester ?? createHttpRequester(),
userAgents: [{ segment: 'Node.js', version: process.versions.node }],
responsesCache: createNullCache(),
requestsCache: createNullCache(),
hostsCache: createMemoryCache(),
...options,
};

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
export * from './src/createAuth';
export * from './src/createEchoRequester';
export * from './src/createBrowserLocalStorageCache';
export * from './src/createFallbackableCache';
export * from './src/createMemoryCache';
export * from './src/createNullCache';
export * from './src/createStatefulHost';
export * from './src/createTransporter';
export * from './src/createUserAgent';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import type { Config } from '@jest/types';

const config: Config.InitialOptions = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
shortcuts marked this conversation as resolved.
Show resolved Hide resolved
};

export default config;
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,16 @@
"module": "dist/client-common.esm.node.js",
"types": "dist/index.d.ts",
"scripts": {
"clean": "rm -rf dist/"
"clean": "rm -rf dist/",
"test": "jest"
},
"engines": {
"node": ">= 14.0.0"
},
"devDependencies": {
"@types/jest": "27.4.1",
"@types/node": "16.11.11",
"jest": "27.4.7",
"typescript": "4.5.4"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import { createBrowserLocalStorageCache } from '../createBrowserLocalStorageCache';

const version = 'foobar';
const notAvailableStorage = new Proxy(window.localStorage, {
get() {
return (): void => {
throw new Error('Component is not available');
};
},
});

type DefaultValue = Promise<{ bar: number }>;

describe('browser local storage cache', () => {
const missMock = jest.fn();
const events = {
miss: (): Promise<any> => Promise.resolve(missMock()),
};

beforeEach(() => {
window.localStorage.clear();
jest.clearAllMocks();
});

it('sets/gets values', async () => {
const cache = createBrowserLocalStorageCache({ key: version });
const defaultValue = (): DefaultValue => Promise.resolve({ bar: 1 });

expect(await cache.get({ key: 'foo' }, defaultValue, events)).toMatchObject(
{ bar: 1 }
);
expect(missMock.mock.calls.length).toBe(1);

await cache.set({ key: 'foo' }, { foo: 2 });

expect(await cache.get({ key: 'foo' }, defaultValue, events)).toMatchObject(
{ foo: 2 }
);
expect(missMock.mock.calls.length).toBe(1);
});

it('deletes keys', async () => {
const cache = createBrowserLocalStorageCache({ key: version });

await cache.set({ key: 'foo' }, { bar: 1 });
await cache.delete({ key: 'foo' });

const defaultValue = (): DefaultValue => Promise.resolve({ bar: 2 });

expect(await cache.get({ key: 'foo' }, defaultValue, events)).toMatchObject(
{ bar: 2 }
);
expect(missMock.mock.calls.length).toBe(1);
});

it('can be cleared', async () => {
const cache = createBrowserLocalStorageCache({ key: version });

await cache.set({ key: 'foo' }, { bar: 1 });
await cache.clear();

const defaultValue = (): DefaultValue => Promise.resolve({ bar: 2 });

expect(await cache.get({ key: 'foo' }, defaultValue, events)).toMatchObject(
{ bar: 2 }
);
expect(missMock.mock.calls.length).toBe(1);
expect(localStorage.length).toBe(0);
});

it('do throws localstorage exceptions on access', async () => {
const message =
"Failed to read the 'localStorage' property from 'Window': Access is denied for this document.";
const cache = createBrowserLocalStorageCache(
new Proxy(
{ key: 'foo' },
{
get(_, key): DOMException | string {
if (key === 'key') {
return 'foo';
}

// Simulates a window.localStorage access.
throw new DOMException(message);
},
}
)
);
const key = { foo: 'bar' };
const value = 'foo';
const fallback = 'bar';

await expect(cache.delete(key)).rejects.toEqual(new DOMException(message));
await expect(cache.set(key, value)).rejects.toEqual(
new DOMException(message)
);
await expect(
cache.get(key, () => Promise.resolve(fallback))
).rejects.toEqual(new DOMException(message));
});

it('do throws localstorage exceptions after access', async () => {
const cache = createBrowserLocalStorageCache({
key: version,
localStorage: notAvailableStorage,
});
const key = { foo: 'bar' };
const value = 'foo';
const fallback = 'bar';
const message = 'Component is not available';

await expect(cache.delete(key)).rejects.toEqual(new Error(message));
await expect(cache.set(key, value)).rejects.toEqual(new Error(message));
await expect(
cache.get(key, () => Promise.resolve(fallback))
).rejects.toEqual(new Error(message));
});

it('creates a namespace within local storage', async () => {
const cache = createBrowserLocalStorageCache({
key: version,
});
const key = { foo: 'bar' };
const value = 'foo';

expect(
localStorage.getItem(`algoliasearch-client-js-${version}`)
).toBeNull();

await cache.set(key, value);

expect(localStorage.getItem(`algoliasearch-client-js-${version}`)).toBe(
'{"{\\"foo\\":\\"bar\\"}":"foo"}'
);
});
});
Loading