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

fix: cache the result conditionally (SimpleCache) #286

Merged
merged 3 commits into from
Jan 31, 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
6 changes: 6 additions & 0 deletions .changeset/thin-toes-smile.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@hyperdx/api': patch
'@hyperdx/app': patch
---

fix: cache the result conditionally (SimpleCache)
89 changes: 50 additions & 39 deletions packages/api/src/routers/api/chart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,45 +49,56 @@ router.get('/services', async (req, res, next) => {

const simpleCache = new SimpleCache<
Awaited<ReturnType<typeof clickhouse.getMultiSeriesChart>>[]
>(`chart-services-${teamId}`, ms('10m'), () =>
Promise.all([
clickhouse.getMultiSeriesChart({
series: [
{
aggFn: clickhouse.AggFn.Count,
groupBy: targetGroupByFields,
table: 'logs',
type: 'table',
where: '',
},
],
endTime,
granularity: undefined,
maxNumGroups: MAX_NUM_GROUPS,
startTime,
tableVersion: team.logStreamTableVersion,
teamId: teamId.toString(),
seriesReturnType: clickhouse.SeriesReturnType.Column,
}),
clickhouse.getMultiSeriesChart({
series: [
{
aggFn: clickhouse.AggFn.Count,
groupBy: ['service'],
table: 'logs',
type: 'table',
where: '',
},
],
endTime,
granularity: undefined,
maxNumGroups: MAX_NUM_GROUPS,
startTime,
tableVersion: team.logStreamTableVersion,
teamId: teamId.toString(),
seriesReturnType: clickhouse.SeriesReturnType.Column,
}),
]),
>(
`chart-services-${teamId}`,
ms('10m'),
() =>
Promise.all([
clickhouse.getMultiSeriesChart({
series: [
{
aggFn: clickhouse.AggFn.Count,
groupBy: targetGroupByFields,
table: 'logs',
type: 'table',
where: '',
},
],
endTime,
granularity: undefined,
maxNumGroups: MAX_NUM_GROUPS,
startTime,
tableVersion: team.logStreamTableVersion,
teamId: teamId.toString(),
seriesReturnType: clickhouse.SeriesReturnType.Column,
}),
clickhouse.getMultiSeriesChart({
series: [
{
aggFn: clickhouse.AggFn.Count,
groupBy: ['service'],
table: 'logs',
type: 'table',
where: '',
},
],
endTime,
granularity: undefined,
maxNumGroups: MAX_NUM_GROUPS,
startTime,
tableVersion: team.logStreamTableVersion,
teamId: teamId.toString(),
seriesReturnType: clickhouse.SeriesReturnType.Column,
}),
]),
results => {
for (const result of results) {
if (result.rows != null && result.rows > 0) {
return true;
}
}
return false;
},
);

const [customAttrsResults, servicesResults] = await simpleCache.get();
Expand Down
23 changes: 16 additions & 7 deletions packages/api/src/routers/api/metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,22 @@ router.get('/tags', async (req, res, next) => {
const nowInMs = Date.now();
const simpleCache = new SimpleCache<
Awaited<ReturnType<typeof clickhouse.getMetricsTags>>
>(`metrics-tags-${teamId}`, ms('10m'), () =>
clickhouse.getMetricsTags({
// FIXME: fix it 5 days ago for now
startTime: nowInMs - ms('5d'),
endTime: nowInMs,
teamId: teamId.toString(),
}),
>(
`metrics-tags-${teamId}`,
ms('10m'),
() =>
clickhouse.getMetricsTags({
// FIXME: fix it 5 days ago for now
startTime: nowInMs - ms('5d'),
endTime: nowInMs,
teamId: teamId.toString(),
}),
result => {
if (result.rows != null) {
return result.rows > 0;
}
return false;
},
);
res.json(await simpleCache.get());
} catch (e) {
Expand Down
23 changes: 16 additions & 7 deletions packages/api/src/routers/external-api/v1/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,13 +195,22 @@ router.get(
const nowInMs = Date.now();
const simpleCache = new SimpleCache<
Awaited<ReturnType<typeof clickhouse.getMetricsTags>>
>(`metrics-tags-${teamId}`, ms('10m'), () =>
clickhouse.getMetricsTags({
// FIXME: fix it 5 days ago for now
startTime: nowInMs - ms('5d'),
endTime: nowInMs,
teamId: teamId.toString(),
}),
>(
`metrics-tags-${teamId}`,
ms('10m'),
() =>
clickhouse.getMetricsTags({
// FIXME: fix it 5 days ago for now
startTime: nowInMs - ms('5d'),
endTime: nowInMs,
teamId: teamId.toString(),
}),
result => {
if (result.rows != null) {
return result.rows > 0;
}
return false;
},
);
const tags = await simpleCache.get();
res.json({
Expand Down
23 changes: 19 additions & 4 deletions packages/api/src/utils/redis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,31 @@ client.on('error', (err: any) => {
logger.error('Redis error: ', serializeError(err));
});

// TODO: add tests
class SimpleCache<T> {
constructor(
private readonly key: string,
private readonly ttlInMs: number,
private readonly fetcher: () => Promise<T>,
private readonly shouldRefreshOnResult: (result: T) => boolean = () => true,
) {}

async refresh() {
const dt = Date.now();
const result = await this.fetcher();
if (this.shouldRefreshOnResult(result)) {
logger.info({
message: 'SimpleCache: refresh',
key: this.key,
duration: Date.now() - dt,
});
await client.set(this.key, JSON.stringify(result), {
PX: this.ttlInMs,
});
}
return result;
}

async get(): Promise<T> {
const cached = await client.get(this.key);
if (cached != null) {
Expand All @@ -32,10 +50,7 @@ class SimpleCache<T> {
message: 'SimpleCache: cache miss',
key: this.key,
});
const result = await this.fetcher();
await client.set(this.key, JSON.stringify(result), {
PX: this.ttlInMs,
});
const result = await this.refresh();
return result;
}
}
Expand Down
Loading