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(cache): Fallback to older decorator results on error #20795

Merged
merged 28 commits into from
Mar 23, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
4cf5299
feat(cache): Fallback for older decorator results on error
zharinov Mar 7, 2023
70eb18a
Merge branch 'main' into feat/cache-decorator-fallback
zharinov Mar 8, 2023
24cbb50
Add tests
zharinov Mar 8, 2023
f84f3ed
Merge branch 'main' into feat/cache-decorator-fallback
zharinov Mar 8, 2023
a0d3b44
Merge branch 'main' into feat/cache-decorator-fallback
zharinov Mar 8, 2023
5adec4e
Fixes
zharinov Mar 9, 2023
f36075c
Merge branch 'main' into feat/cache-decorator-fallback
zharinov Mar 9, 2023
7fb848d
Merge branch 'main' into feat/cache-decorator-fallback
zharinov Mar 9, 2023
0d2281b
Merge branch 'main' into feat/cache-decorator-fallback
zharinov Mar 10, 2023
92533bc
Merge branch 'main' into feat/cache-decorator-fallback
zharinov Mar 10, 2023
6b21315
Merge branch 'main' into feat/cache-decorator-fallback
zharinov Mar 12, 2023
3f65a80
Merge branch 'main' into feat/cache-decorator-fallback
zharinov Mar 15, 2023
4e3d7ee
Add `methodName` to the decorator inner API
zharinov Mar 15, 2023
a55eeb4
Some changes
zharinov Mar 15, 2023
7977bb1
Merge branch 'main' into feat/cache-decorator-fallback
zharinov Mar 16, 2023
08361af
Adjust behavior
zharinov Mar 16, 2023
1241058
Merge branch 'main' into feat/cache-decorator-fallback
zharinov Mar 16, 2023
f2f3b9e
Comment
zharinov Mar 16, 2023
6a37702
Fix timer advance
zharinov Mar 16, 2023
d0cbfef
Combine softTTL and hardTTL
zharinov Mar 16, 2023
124a128
Remove doc
zharinov Mar 17, 2023
8840dbb
Merge branch 'main' into feat/cache-decorator-fallback
zharinov Mar 17, 2023
25e4d19
Merge branch 'main' into feat/cache-decorator-fallback
zharinov Mar 19, 2023
9e1ad18
Merge branch 'main' into feat/cache-decorator-fallback
zharinov Mar 20, 2023
efc3966
Merge branch 'main' into feat/cache-decorator-fallback
zharinov Mar 21, 2023
a86212c
Fixes
zharinov Mar 21, 2023
65af01c
Merge branch 'main' into feat/cache-decorator-fallback
zharinov Mar 21, 2023
8d3b77b
Merge branch 'main' into feat/cache-decorator-fallback
zharinov Mar 23, 2023
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
63 changes: 62 additions & 1 deletion lib/util/cache/package/decorator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ jest.mock('./file');
describe('util/cache/package/decorator', () => {
const spy = jest.fn(() => Promise.resolve());

beforeAll(async () => {
beforeEach(async () => {
memCache.init();
await packageCache.init({ cacheDir: os.tmpdir() });
});
Expand Down Expand Up @@ -120,4 +120,65 @@ describe('util/cache/package/decorator', () => {

expect(await getNumber.value?.()).toBeNumber();
});

describe('Fallback', () => {
const inc = jest.fn();

class MyClass {
@cache({
namespace: (x: number) => x.toString(),
key: () => 'key',
ttlMinutes: 1,
})
public incNumber(x: number): Promise<number> {
return inc(x);
}
}

beforeEach(() => {
jest.useFakeTimers({ advanceTimers: false });
inc.mockImplementation((x: number) => Promise.resolve(x + 1));
});

afterEach(() => {
jest.useRealTimers();
inc.mockClear();
});

it('updates cached result', async () => {
const myInst = new MyClass();

expect(await myInst.incNumber(99)).toBe(100);

jest.advanceTimersByTime(60 * 1000 - 1);
expect(await myInst.incNumber(99)).toBe(100);
expect(inc).toHaveBeenCalledTimes(1);

jest.advanceTimersByTime(1);
expect(await myInst.incNumber(99)).toBe(100);
expect(inc).toHaveBeenCalledTimes(2);
});

it('returns obsolete result on error', async () => {
const myInst = new MyClass();

expect(await myInst.incNumber(99)).toBe(100);

jest.advanceTimersByTime(60 * 1000);
inc.mockRejectedValueOnce(new Error('test'));
expect(await myInst.incNumber(99)).toBe(100);
expect(inc).toHaveBeenCalledTimes(2);
});

it('re-throws if older result is too old', async () => {
const myInst = new MyClass();

expect(await myInst.incNumber(99)).toBe(100);

jest.advanceTimersByTime(10 * 60 * 1000);
inc.mockRejectedValueOnce(new Error('test'));
await expect(myInst.incNumber(99)).rejects.toThrow('test');
expect(inc).toHaveBeenCalledTimes(2);
});
});
});
56 changes: 48 additions & 8 deletions lib/util/cache/package/decorator.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import is from '@sindresorhus/is';
import { DateTime } from 'luxon';
import { Decorator, decorate } from '../../decorator';
import type { DecoratorCachedRecord } from './types';
import * as packageCache from '.';

type HashFunction<T extends any[] = any[]> = (...args: T) => string;
Expand Down Expand Up @@ -66,21 +68,59 @@ export function cache<T>({
return callback();
}

const cachedResult = await packageCache.get<unknown>(
finalKey = `cache-decorator:${finalKey}`;
zharinov marked this conversation as resolved.
Show resolved Hide resolved
const cacheRecord = await packageCache.get<DecoratorCachedRecord<T>>(
finalNamespace,
finalKey
);

if (cachedResult !== undefined) {
return cachedResult;
const now = DateTime.local();
const ttlHardMinutes = ttlMinutes * 10;

let oldData: T | undefined;
if (cacheRecord) {
const softDeadline = DateTime.fromISO(cacheRecord.cachedAt).plus({
zharinov marked this conversation as resolved.
Show resolved Hide resolved
minutes: ttlMinutes,
});
const hardDeadline = DateTime.fromISO(cacheRecord.cachedAt).plus({
minutes: ttlHardMinutes,
});

if (now < softDeadline) {
return cacheRecord.data;
}

if (now < hardDeadline) {
oldData = cacheRecord.data;
}
rarkins marked this conversation as resolved.
Show resolved Hide resolved
}

const result = await callback();
let newData: T | undefined;
if (oldData) {
try {
newData = (await callback()) as T | undefined;
} catch (err) {
return oldData;
zharinov marked this conversation as resolved.
Show resolved Hide resolved
}
} else {
newData = (await callback()) as T | undefined;
}
rarkins marked this conversation as resolved.
Show resolved Hide resolved

if (!is.undefined(newData)) {
const cachedAt = now.toISO();
const newCacheRecord: DecoratorCachedRecord<T> = {
cachedAt,
data: newData,
};

// only cache if we got a valid result
if (result !== undefined) {
await packageCache.set(finalNamespace, finalKey, result, ttlMinutes);
await packageCache.set(
finalNamespace,
finalKey,
newCacheRecord,
ttlHardMinutes
);
}
return result;

return newData;
});
}
5 changes: 5 additions & 0 deletions lib/util/cache/package/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,8 @@ export interface PackageCache {
ttlMinutes?: number
): Promise<void>;
}

export interface DecoratorCachedRecord<T> {
zharinov marked this conversation as resolved.
Show resolved Hide resolved
data: T;
cachedAt: string;
}