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 8 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
4 changes: 4 additions & 0 deletions docs/usage/self-hosted-experimental.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ We do not follow Semantic Versioning for any experimental variables.
These variables may be removed or have their behavior changed in **any** version.
We will try to keep breakage to a minimum, but make no guarantees that an experimental variable will keep working.

## `RENOVATE_CACHE_DECORATOR_MINUTES`
rarkins marked this conversation as resolved.
Show resolved Hide resolved

If set to any integer, Renovate will use this integer instead of the time explicitly defined via `ttlMinutes` in decorators.

## `RENOVATE_CACHE_NPM_MINUTES`

If set to any integer, Renovate will use this integer instead of the default npm cache time (15 minutes) for the npm datasource.
Expand Down
68 changes: 67 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,70 @@ 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();
delete process.env.RENOVATE_CACHE_DECORATOR_MINUTES;
});

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('cache TTL can be overriden with RENOVATE_CACHE_DECORATOR_MINUTES', async () => {
process.env.RENOVATE_CACHE_DECORATOR_MINUTES = '3';
const myInst = new MyClass();

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

jest.advanceTimersByTime(3 * 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);
});
});
});
50 changes: 42 additions & 8 deletions lib/util/cache/package/decorator.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import is from '@sindresorhus/is';
import { DateTime } from 'luxon';
import { GlobalConfig } from '../../../config/global';
import { logger } from '../../../logger';
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 +70,51 @@ 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 oldRecord = await packageCache.get<DecoratorCachedRecord>(
finalNamespace,
finalKey
);

if (cachedResult !== undefined) {
return cachedResult;
const softTTL = process.env.RENOVATE_CACHE_DECORATOR_MINUTES
? parseInt(process.env.RENOVATE_CACHE_DECORATOR_MINUTES, 10)
: ttlMinutes;

let oldData: unknown;
if (oldRecord) {
const now = DateTime.local();
const cachedAt = DateTime.fromISO(oldRecord.cachedAt);
viceice marked this conversation as resolved.
Show resolved Hide resolved
const deadline = cachedAt.plus({ minutes: softTTL });
if (now < deadline) {
return oldRecord.data;
}
rarkins marked this conversation as resolved.
Show resolved Hide resolved
oldData = oldRecord.data;
}

const result = await callback();
let newData: unknown;
if (oldData) {
try {
newData = (await callback()) as T | undefined;
} catch (err) {
logger.debug(
{ err },
'Package cache decorator: callback error, returning old data'
);
return oldData;
zharinov marked this conversation as resolved.
Show resolved Hide resolved
}
} else {
newData = (await callback()) as T | undefined;
}

// only cache if we got a valid result
if (result !== undefined) {
await packageCache.set(finalNamespace, finalKey, result, ttlMinutes);
if (!is.undefined(newData)) {
const newRecord: DecoratorCachedRecord = {
cachedAt: DateTime.local().toISO(),
data: newData,
};
const hardTTL = GlobalConfig.get().cacheHardTtlMinutes ?? softTTL;
await packageCache.set(finalNamespace, finalKey, newRecord, hardTTL);
}
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 {
data: unknown;
cachedAt: string;
}