Skip to content

feat(redis): Support mget command in caching functionality #12348

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

Merged
merged 15 commits into from
Jun 6, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ async function run() {
await redis.get('test-key');
await redis.get('ioredis-cache:test-key');
await redis.get('ioredis-cache:unavailable-data');

await redis.mget('test-key', 'ioredis-cache:test-key', 'ioredis-cache:unavailable-data');
} finally {
await redis.disconnect();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,40 +48,57 @@ describe('redis cache auto instrumentation', () => {
spans: expect.arrayContaining([
// SET
expect.objectContaining({
description: 'set ioredis-cache:test-key [1 other arguments]',
description: 'ioredis-cache:test-key',
op: 'cache.put',
origin: 'auto.db.otel.redis',
data: expect.objectContaining({
'sentry.origin': 'auto.db.otel.redis',
'db.statement': 'set ioredis-cache:test-key [1 other arguments]',
'cache.key': 'ioredis-cache:test-key',
'cache.key': ['ioredis-cache:test-key'],
'cache.item_size': 2,
'network.peer.address': 'localhost',
'network.peer.port': 6379,
}),
}),
// GET
expect.objectContaining({
description: 'get ioredis-cache:test-key',
op: 'cache.get_item', // todo: will be changed to cache.get
description: 'ioredis-cache:test-key',
op: 'cache.get',
origin: 'auto.db.otel.redis',
data: expect.objectContaining({
'sentry.origin': 'auto.db.otel.redis',
'db.statement': 'get ioredis-cache:test-key',
'cache.hit': true,
'cache.key': 'ioredis-cache:test-key',
'cache.key': ['ioredis-cache:test-key'],
'cache.item_size': 10,
'network.peer.address': 'localhost',
'network.peer.port': 6379,
}),
}),
// GET (unavailable)
// GET (unavailable - no cache hit)
expect.objectContaining({
description: 'get ioredis-cache:unavailable-data',
op: 'cache.get_item', // todo: will be changed to cache.get
description: 'ioredis-cache:unavailable-data',
op: 'cache.get',
origin: 'auto.db.otel.redis',
data: expect.objectContaining({
'sentry.origin': 'auto.db.otel.redis',
'db.statement': 'get ioredis-cache:unavailable-data',
'cache.hit': false,
'cache.key': 'ioredis-cache:unavailable-data',
'cache.key': ['ioredis-cache:unavailable-data'],
'network.peer.address': 'localhost',
'network.peer.port': 6379,
}),
}),
// MGET
expect.objectContaining({
description: 'test-key, ioredis-cache:test-key, ioredis-cache:unavailable-data',
op: 'cache.get',
origin: 'auto.db.otel.redis',
data: expect.objectContaining({
'sentry.origin': 'auto.db.otel.redis',
'db.statement': 'mget [3 other arguments]',
'cache.hit': true,
'cache.key': ['test-key', 'ioredis-cache:test-key', 'ioredis-cache:unavailable-data'],
'network.peer.address': 'localhost',
'network.peer.port': 6379,
}),
Expand Down
78 changes: 32 additions & 46 deletions packages/node/src/integrations/tracing/redis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,32 +10,13 @@ import {
} from '@sentry/core';
import type { IntegrationFn } from '@sentry/types';
import { generateInstrumentOnce } from '../../otel/instrument';

function keyHasPrefix(key: string, prefixes: string[]): boolean {
return prefixes.some(prefix => key.startsWith(prefix));
}

/** Currently, caching only supports 'get' and 'set' commands. More commands will be added (setex, mget, del, expire) */
function shouldConsiderForCache(
redisCommand: string,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
key: string | number | any[] | Buffer,
prefixes: string[],
): boolean {
return (redisCommand === 'get' || redisCommand === 'set') && typeof key === 'string' && keyHasPrefix(key, prefixes);
}

function calculateCacheItemSize(response: unknown): number | undefined {
try {
if (Buffer.isBuffer(response)) return response.byteLength;
else if (typeof response === 'string') return response.length;
else if (typeof response === 'number') return response.toString().length;
else if (response === null || response === undefined) return 0;
return JSON.stringify(response).length;
} catch (e) {
return undefined;
}
}
import {
GET_COMMANDS,
calculateCacheItemSize,
getCacheKeySafely,
getCacheOperation,
shouldConsiderForCache,
} from '../../utils/redisCache';

interface RedisOptions {
cachePrefixes?: string[];
Expand All @@ -48,11 +29,18 @@ let _redisOptions: RedisOptions = {};
export const instrumentRedis = generateInstrumentOnce(INTEGRATION_NAME, () => {
return new IORedisInstrumentation({
responseHook: (span, redisCommand, cmdArgs, response) => {
const key = cmdArgs[0];
const safeKey = getCacheKeySafely(redisCommand, cmdArgs);

span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, 'auto.db.otel.redis');

if (!_redisOptions?.cachePrefixes || !shouldConsiderForCache(redisCommand, key, _redisOptions.cachePrefixes)) {
const cacheOperation = getCacheOperation(redisCommand);

if (
!safeKey ||
!cacheOperation ||
!_redisOptions?.cachePrefixes ||
!shouldConsiderForCache(redisCommand, safeKey, _redisOptions.cachePrefixes)
) {
// not relevant for cache
return;
}
Expand All @@ -66,25 +54,23 @@ export const instrumentRedis = generateInstrumentOnce(INTEGRATION_NAME, () => {
}

const cacheItemSize = calculateCacheItemSize(response);
if (cacheItemSize) span.setAttribute(SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE, cacheItemSize);

if (typeof key === 'string') {
switch (redisCommand) {
case 'get':
span.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'cache.get_item', // todo: will be changed to cache.get
[SEMANTIC_ATTRIBUTE_CACHE_KEY]: key,
});
if (cacheItemSize !== undefined) span.setAttribute(SEMANTIC_ATTRIBUTE_CACHE_HIT, cacheItemSize > 0);
break;
case 'set':
span.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'cache.put',
[SEMANTIC_ATTRIBUTE_CACHE_KEY]: key,
});
break;
}

if (cacheItemSize) {
span.setAttribute(SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE, cacheItemSize);
}

if (GET_COMMANDS.includes(redisCommand) && cacheItemSize !== undefined) {
span.setAttribute(SEMANTIC_ATTRIBUTE_CACHE_HIT, cacheItemSize > 0);
}

span.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: cacheOperation,
[SEMANTIC_ATTRIBUTE_CACHE_KEY]: safeKey,
});

const spanDescription = safeKey.join(', ');

span.updateName(spanDescription.length > 1024 ? `${spanDescription.substring(0, 1024)}...` : spanDescription);
},
});
});
Expand Down
89 changes: 89 additions & 0 deletions packages/node/src/utils/redisCache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import type { CommandArgs as IORedisCommandArgs } from '@opentelemetry/instrumentation-ioredis';
import { flatten } from '@sentry/utils';

const SINGLE_ARG_COMMANDS = ['get', 'set', 'setex'];

export const GET_COMMANDS = ['get', 'mget'];
export const SET_COMMANDS = ['set' /* todo: 'setex' */];
// todo: del, expire

/** Determine cache operation based on redis statement */
export function getCacheOperation(
command: string,
): 'cache.get' | 'cache.put' | 'cache.remove' | 'cache.flush' | undefined {
const lowercaseStatement = command.toLowerCase();

if (GET_COMMANDS.includes(lowercaseStatement)) {
return 'cache.get';
} else if (SET_COMMANDS.includes(lowercaseStatement)) {
return 'cache.put';
} else {
return undefined;
}
}

function keyHasPrefix(key: string, prefixes: string[]): boolean {
return prefixes.some(prefix => key.startsWith(prefix));
}

/** Safely converts a redis key to a string (comma-separated if there are multiple keys) */
export function getCacheKeySafely(redisCommand: string, cmdArgs: IORedisCommandArgs): string[] | undefined {
try {
if (cmdArgs.length === 0) {
return undefined;
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const processArg = (arg: string | Buffer | number | any[]): string[] => {
if (typeof arg === 'string' || typeof arg === 'number' || Buffer.isBuffer(arg)) {
return [arg.toString()];
} else if (Array.isArray(arg)) {
return flatten(arg.map(arg => processArg(arg)));
} else {
return ['<unknown>'];
}
};

if (SINGLE_ARG_COMMANDS.includes(redisCommand) && cmdArgs.length > 0) {
return processArg(cmdArgs[0]);
}

return flatten(cmdArgs.map(arg => processArg(arg)));
} catch (e) {
return undefined;
}
}

/** Determines whether a redis operation should be considered as "cache operation" by checking if a key is prefixed.
* We only support certain commands (such as 'set', 'get', 'mget'). */
export function shouldConsiderForCache(redisCommand: string, key: string[], prefixes: string[]): boolean {
if (!getCacheOperation(redisCommand)) {
return false;
}

return key.reduce((prev, key) => {
Copy link
Member

Choose a reason for hiding this comment

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

This seems a bit excessive use of reduce :D I'd avoid it where not absolutely necessary, here an early return is easier to follow IMHO:

for (const k of key) {
  if (keyHasPrefix(key, prefixes) {
    return true;
  }
}
return false;

or something along this line?

return prev || keyHasPrefix(key, prefixes);
}, false);
}

/** Calculates size based on the cache response value */
export function calculateCacheItemSize(response: unknown): number | undefined {
const getSize = (value: unknown): number | undefined => {
try {
if (Buffer.isBuffer(value)) return value.byteLength;
else if (typeof value === 'string') return value.length;
else if (typeof value === 'number') return value.toString().length;
else if (value === null || value === undefined) return 0;
return JSON.stringify(value).length;
} catch (e) {
return undefined;
}
};

return Array.isArray(response)
? response.reduce((acc: number | undefined, curr) => {
const size = getSize(curr);
return typeof size === 'number' ? (acc !== undefined ? acc + size : size) : acc;
}, 0)
: getSize(response);
}
Loading
Loading