mirror of
https://github.com/n8n-io/n8n.git
synced 2026-12-04 00:30:34 +00:00
fix(core): Fix cache get for Redis missing key placeholders and set for falsy values (#26502)
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
71cec8bffe
commit
cf90a202ae
5 files changed
+94
-87
No files matched your search
@@ -1,7 +0,0 @@
|
||||
import { UnexpectedError } from 'n8n-workflow';
|
||||
|
||||
export class MalformedRefreshValueError extends UnexpectedError {
|
||||
constructor() {
|
||||
super('Refresh value must have the same number of values as keys');
|
||||
}
|
||||
}
|
||||
@@ -19,14 +19,6 @@ describe('CacheService (Mock)', () => {
|
||||
expect(store.get).toHaveBeenCalledWith('key');
|
||||
});
|
||||
|
||||
test('getMany', async () => {
|
||||
await cacheService.getMany([]);
|
||||
expect(store.mget).not.toHaveBeenCalled();
|
||||
|
||||
await cacheService.getMany(['key1', 'key2']);
|
||||
expect(store.mget).toHaveBeenCalledWith('key1', 'key2');
|
||||
});
|
||||
|
||||
test('set', async () => {
|
||||
await cacheService.set('', '');
|
||||
expect(store.set).not.toHaveBeenCalled();
|
||||
@@ -36,6 +28,15 @@ describe('CacheService (Mock)', () => {
|
||||
|
||||
await cacheService.set('key', 'value', 123);
|
||||
expect(store.set).toHaveBeenCalledWith('key', 'value', 123);
|
||||
|
||||
await cacheService.set('false-key', false);
|
||||
expect(store.set).toHaveBeenCalledWith('false-key', false, undefined);
|
||||
|
||||
await cacheService.set('zero-key', 0);
|
||||
expect(store.set).toHaveBeenCalledWith('zero-key', 0, undefined);
|
||||
|
||||
await cacheService.set('empty-string-key', '');
|
||||
expect(store.set).toHaveBeenCalledWith('empty-string-key', '', undefined);
|
||||
});
|
||||
|
||||
test('setMany', async () => {
|
||||
|
||||
+62
-23
@@ -1,5 +1,6 @@
|
||||
import { GlobalConfig } from '@n8n/config';
|
||||
import { Container } from '@n8n/di';
|
||||
import random from 'lodash/random';
|
||||
import { sleep } from 'n8n-workflow';
|
||||
|
||||
import config from '@/config';
|
||||
@@ -37,12 +38,14 @@ for (const backend of ['memory', 'redis'] as const) {
|
||||
});
|
||||
|
||||
if (backend === 'redis') {
|
||||
test('with auto backend and queue mode, should select redis', async () => {
|
||||
globalConfig.executions.mode = 'queue';
|
||||
describe('when backend is redis', () => {
|
||||
test('with auto backend and queue mode, should select redis', async () => {
|
||||
globalConfig.executions.mode = 'queue';
|
||||
|
||||
await cacheService.init();
|
||||
await cacheService.init();
|
||||
|
||||
expect(cacheService.isRedis()).toBe(true);
|
||||
expect(cacheService.isRedis()).toBe(true);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -101,10 +104,16 @@ for (const backend of ['memory', 'redis'] as const) {
|
||||
await cacheService.set('key1', null);
|
||||
await cacheService.set('key2', undefined);
|
||||
await cacheService.set('key3', 'value');
|
||||
await cacheService.set('key4', false);
|
||||
await cacheService.set('key5', 0);
|
||||
await cacheService.set('key6', '');
|
||||
|
||||
await expect(cacheService.get('key1')).resolves.toBeUndefined();
|
||||
await expect(cacheService.get('key2')).resolves.toBeUndefined();
|
||||
await expect(cacheService.get('key3')).resolves.toBe('value');
|
||||
await expect(cacheService.get('key4')).resolves.toBe(false);
|
||||
await expect(cacheService.get('key5')).resolves.toBe(0);
|
||||
await expect(cacheService.get('key6')).resolves.toBe('');
|
||||
});
|
||||
|
||||
test('should disregard zero-length keys', async () => {
|
||||
@@ -125,15 +134,16 @@ for (const backend of ['memory', 'redis'] as const) {
|
||||
});
|
||||
|
||||
describe('get', () => {
|
||||
const createRefreshFn = () => jest.fn(async () => await Promise.resolve('refreshValue'));
|
||||
|
||||
test('should fall back to fallback value', async () => {
|
||||
const promise = cacheService.get('key', { fallbackValue: 'fallback' });
|
||||
await expect(promise).resolves.toBe('fallback');
|
||||
});
|
||||
|
||||
test('should refresh value', async () => {
|
||||
const promise = cacheService.get('testString', {
|
||||
refreshFn: async () => 'refreshValue',
|
||||
});
|
||||
const refreshFn = createRefreshFn();
|
||||
const promise = cacheService.get('testString', { refreshFn });
|
||||
|
||||
await expect(promise).resolves.toBe('refreshValue');
|
||||
});
|
||||
@@ -144,6 +154,47 @@ for (const backend of ['memory', 'redis'] as const) {
|
||||
|
||||
await expect(cacheService.get(nonAsciiKey)).resolves.toBe('value');
|
||||
});
|
||||
|
||||
test('should treat empty array placeholder as cache hit when key is present', async () => {
|
||||
const refreshFn = createRefreshFn();
|
||||
|
||||
await cacheService.set('testString', []);
|
||||
const value = await cacheService.get('testString', { refreshFn });
|
||||
expect(value).toEqual([]);
|
||||
expect(refreshFn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
if (backend === 'redis') {
|
||||
describe('when backend is redis', () => {
|
||||
test('should treat empty array placeholder as cache miss when key is missing', async () => {
|
||||
const refreshFn = createRefreshFn();
|
||||
|
||||
const value = await cacheService.get('testString', { refreshFn });
|
||||
expect(value).toBe('refreshValue');
|
||||
expect(refreshFn).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test.each([
|
||||
['an empty array', []],
|
||||
['an array with items', ['item1', 'item2']],
|
||||
['a string', 'value'],
|
||||
['an empty string', ''],
|
||||
['a number', random(1, 1000)],
|
||||
['a zero', 0],
|
||||
['"true"', true],
|
||||
['"false"', false],
|
||||
['an object', { foo: 'bar' }],
|
||||
['an empty object', {}],
|
||||
])('should treat a key as cache hit when value is %s', async (_type, valueToSet) => {
|
||||
const refreshFn = createRefreshFn();
|
||||
|
||||
await cacheService.set('testString', valueToSet);
|
||||
const value = await cacheService.get('testString', { refreshFn });
|
||||
expect(value).toEqual(valueToSet);
|
||||
expect(refreshFn).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
describe('delete', () => {
|
||||
@@ -163,8 +214,8 @@ for (const backend of ['memory', 'redis'] as const) {
|
||||
['key2', 'value2'],
|
||||
]);
|
||||
|
||||
const promise = cacheService.getMany(['key1', 'key2']);
|
||||
await expect(promise).resolves.toStrictEqual(['value1', 'value2']);
|
||||
await expect(cacheService.get('key1')).resolves.toBe('value1');
|
||||
await expect(cacheService.get('key2')).resolves.toBe('value2');
|
||||
});
|
||||
|
||||
test('should set multiple number values', async () => {
|
||||
@@ -173,8 +224,8 @@ for (const backend of ['memory', 'redis'] as const) {
|
||||
['key2', 456],
|
||||
]);
|
||||
|
||||
const promise = cacheService.getMany(['key1', 'key2']);
|
||||
await expect(promise).resolves.toStrictEqual([123, 456]);
|
||||
await expect(cacheService.get('key1')).resolves.toBe(123);
|
||||
await expect(cacheService.get('key2')).resolves.toBe(456);
|
||||
});
|
||||
|
||||
test('should disregard zero-length keys', async () => {
|
||||
@@ -184,18 +235,6 @@ for (const backend of ['memory', 'redis'] as const) {
|
||||
});
|
||||
});
|
||||
|
||||
describe('getMany', () => {
|
||||
test('should return undefined on missing result', async () => {
|
||||
await cacheService.setMany([
|
||||
['key1', 123],
|
||||
['key2', 456],
|
||||
]);
|
||||
|
||||
const promise = cacheService.getMany(['key2', 'key3']);
|
||||
await expect(promise).resolves.toStrictEqual([456, undefined]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete', () => {
|
||||
test('should handle non-ASCII key', async () => {
|
||||
const nonAsciiKey = 'ԱԲԳ';
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
export const REDIS_TTL_KEY_MISSING = -2;
|
||||
+22
-49
@@ -4,8 +4,8 @@ import { Container, Service } from '@n8n/di';
|
||||
import { caching } from 'cache-manager';
|
||||
import { jsonStringify, UserError } from 'n8n-workflow';
|
||||
|
||||
import { MalformedRefreshValueError } from '@/errors/cache-errors/malformed-refresh-value.error';
|
||||
import { UncacheableValueError } from '@/errors/cache-errors/uncacheable-value.error';
|
||||
import { REDIS_TTL_KEY_MISSING } from '@/services/cache/cache.constants';
|
||||
import type {
|
||||
TaggedRedisCache,
|
||||
TaggedMemoryCache,
|
||||
@@ -102,7 +102,7 @@ export class CacheService extends TypedEmitter<CacheEvents> {
|
||||
async set(key: string, value: unknown, ttl?: number) {
|
||||
if (!this.cache) await this.init();
|
||||
|
||||
if (!key || !value) return;
|
||||
if (!key || value === undefined || value === null) return;
|
||||
|
||||
if (this.cache.kind === 'redis' && !this.cache.store.isCacheable(value)) {
|
||||
throw new UncacheableValueError(key);
|
||||
@@ -189,7 +189,9 @@ export class CacheService extends TypedEmitter<CacheEvents> {
|
||||
|
||||
const value = await this.cache.store.get<T>(key);
|
||||
|
||||
if (value !== undefined) {
|
||||
const hasValue = value !== undefined;
|
||||
const cacheHit = hasValue && !(await this.isValueAMissingKeyPlaceholder(key, value));
|
||||
if (cacheHit) {
|
||||
this.emit('metrics.cache.hit');
|
||||
|
||||
return value;
|
||||
@@ -209,52 +211,6 @@ export class CacheService extends TypedEmitter<CacheEvents> {
|
||||
return fallbackValue;
|
||||
}
|
||||
|
||||
async getMany<T = unknown[]>(
|
||||
keys: string[],
|
||||
{
|
||||
fallbackValue,
|
||||
refreshFn,
|
||||
}: {
|
||||
fallbackValue?: T[];
|
||||
refreshFn?: (keys: string[]) => Promise<T[]>;
|
||||
} = {},
|
||||
) {
|
||||
if (!this.cache) await this.init();
|
||||
|
||||
if (keys.length === 0) return [];
|
||||
|
||||
const values = await this.cache.store.mget(...keys);
|
||||
|
||||
if (values !== undefined) {
|
||||
this.emit('metrics.cache.hit');
|
||||
|
||||
return values as T[];
|
||||
}
|
||||
|
||||
this.emit('metrics.cache.miss');
|
||||
|
||||
if (refreshFn) {
|
||||
this.emit('metrics.cache.update');
|
||||
|
||||
const refreshValue: T[] = await refreshFn(keys);
|
||||
|
||||
if (keys.length !== refreshValue.length) {
|
||||
throw new MalformedRefreshValueError();
|
||||
}
|
||||
|
||||
const newValue: Array<[key: string, value: unknown]> = keys.map((key, i) => [
|
||||
key,
|
||||
refreshValue[i],
|
||||
]);
|
||||
|
||||
await this.setMany(newValue);
|
||||
|
||||
return refreshValue;
|
||||
}
|
||||
|
||||
return fallbackValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a [Redis hash](https://redis.io/docs/data-types/hashes/) under a key.
|
||||
* If in-memory, the hash is a regular JS object. To retrieve a primitive value
|
||||
@@ -379,4 +335,21 @@ export class CacheService extends TypedEmitter<CacheEvents> {
|
||||
|
||||
await this.cache.store.set(cacheKey, hashObject);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a value is a Redis missing key placeholder.
|
||||
* After a cache loss (e.g. Redis restart), some adapters may return [] for a missing key.
|
||||
* @param key - The key to check.
|
||||
* @param value - The value to check.
|
||||
* @returns True if the value is a Redis missing key placeholder, false otherwise.
|
||||
*/
|
||||
private async isValueAMissingKeyPlaceholder(key: string, value: unknown): Promise<boolean> {
|
||||
// Memory cache uses `undefined` for misses and [] can be a valid cached value, so this check is only needed for Redis cache.
|
||||
if (this.isRedis() && Array.isArray(value) && value.length === 0) {
|
||||
const ttl = await this.cache.store.ttl(key);
|
||||
return ttl === REDIS_TTL_KEY_MISSING;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user