Skip to content

Commit 966d63f

Browse files
committed
fix: lazy-load redis connection
1 parent cba7399 commit 966d63f

8 files changed

Lines changed: 32 additions & 24 deletions

File tree

apps/api/src/app/authorization.service.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { Workspace, Subscription } from "@prisma/client";
2-
import { redisConnection } from "../bull-mq/redis-connection";
2+
import { getRedisConnection } from "../bull-mq/redis-connection";
33
import { getRandomString } from "../lib/crypto";
44
import { isAppSelfHosted } from "../lib/self-host";
55
import { getPrisma } from "../prisma";
@@ -31,21 +31,21 @@ export const isActiveCustomer = (
3131
};
3232

3333
export const preventCSRFAttack = async (nonce: string) => {
34-
const keyValue = await redisConnection.get(`oauth:state:${nonce}`);
34+
const keyValue = await getRedisConnection().get(`oauth:state:${nonce}`);
3535

3636
if (!keyValue) {
3737
throw new BusinessRuleException("Could not validate state", {
3838
severity: "info",
3939
});
4040
}
4141

42-
redisConnection.del(`oauth:state:${nonce}`);
42+
getRedisConnection().del(`oauth:state:${nonce}`);
4343
};
4444

4545
export const getTemporaryNonce = () => {
4646
const nonce = getRandomString(16);
4747

48-
redisConnection.setex(`oauth:state:${nonce}`, 60 * 5, nonce);
48+
getRedisConnection().setex(`oauth:state:${nonce}`, 60 * 5, nonce);
4949

5050
return nonce;
5151
};

apps/api/src/app/email/services/send-email.service.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { InitialSyncCompleteEmail } from "@sweetr/email-templates";
22
import { addJob, SweetQueue } from "../../../bull-mq/queues";
3-
import { redisConnection } from "../../../bull-mq/redis-connection";
3+
import { getRedisConnection } from "../../../bull-mq/redis-connection";
44
import { env, isProduction } from "../../../env";
55
import { EmailOptions, EmailPayload, getEmailClient } from "../../../lib/email";
66
import { logger } from "../../../lib/logger";
@@ -54,9 +54,9 @@ export const sendEmail = async (
5454
};
5555

5656
export const markEmailAsSent = (key: string, expireInSeconds: number) => {
57-
return redisConnection.setex(key, expireInSeconds, 1);
57+
return getRedisConnection().setex(key, expireInSeconds, 1);
5858
};
5959

6060
export const hasSentEmail = (key: string) => {
61-
return redisConnection.exists(key);
61+
return getRedisConnection().exists(key);
6262
};

apps/api/src/app/github/services/github-rate-limit.service.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { DelayedError, Job } from "bullmq";
22
import { logger } from "../../../lib/logger";
3-
import { redisConnection } from "../../../bull-mq/redis-connection";
3+
import { getRedisConnection } from "../../../bull-mq/redis-connection";
44
import { BusinessRuleException } from "../../errors/exceptions/business-rule.exception";
55
import { addSeconds, getTime, isPast, fromUnixTime } from "date-fns";
66

@@ -95,7 +95,7 @@ export const withDelayedRetryOnRateLimit = async <T>(
9595
export const getGitInstallationRateLimitEpochInMs = async (
9696
installationId: number
9797
) => {
98-
const rateLimitResetString = await redisConnection.get(
98+
const rateLimitResetString = await getRedisConnection().get(
9999
`github:rate-limit-reset:${installationId}`
100100
);
101101

@@ -114,7 +114,7 @@ export const setGitInstallationRateLimitEpochInMs = async (
114114
installationId: number,
115115
rateLimitResetAtInMs: number
116116
) => {
117-
await redisConnection.set(
117+
await getRedisConnection().set(
118118
`github:rate-limit-reset:${installationId}`,
119119
rateLimitResetAtInMs,
120120
// Set key to expire

apps/api/src/app/sync-batch/services/sync-batch.service.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import {
1212
} from "../../email/services/send-email.service";
1313
import { BusinessRuleException } from "../../errors/exceptions/business-rule.exception";
1414
import { findWorkspaceUsers } from "../../workspaces/services/workspace.service";
15-
import { redisConnection } from "../../../bull-mq/redis-connection";
15+
import { getRedisConnection } from "../../../bull-mq/redis-connection";
1616
import { UnknownException } from "../../errors/exceptions/unknown.exception";
1717

1818
export const DEFAULT_SYNC_BATCH_SINCE_DAYS_AGO = 365; // TO-DO: Should be a workspace setting
@@ -45,7 +45,7 @@ export const setSyncBatchProgress = async (syncBatchId: number) => {
4545
const key = `sync-batch:${syncBatchId}:sync`;
4646
const sevenDaysInSeconds = 60 * 60 * 24 * 7;
4747

48-
await redisConnection
48+
await getRedisConnection()
4949
.multi()
5050
.hset(key, { waiting: 0, done: 0 })
5151
.expire(key, sevenDaysInSeconds)
@@ -59,12 +59,12 @@ export const incrementSyncBatchProgress = async (
5959
) => {
6060
const key = `sync-batch:${syncBatchId}:sync`;
6161

62-
await redisConnection.hincrby(key, field, amount);
62+
await getRedisConnection().hincrby(key, field, amount);
6363
};
6464

6565
export const getSyncBatchProgress = async (syncBatchId: number) => {
6666
try {
67-
const progress = await redisConnection.hgetall(
67+
const progress = await getRedisConnection().hgetall(
6868
`sync-batch:${syncBatchId}:sync`
6969
);
7070

apps/api/src/bull-mq/queues.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { BulkJobOptions, JobsOptions, Queue } from "bullmq";
2-
import { redisConnection } from "./redis-connection";
2+
import { getRedisConnection } from "./redis-connection";
33
import { logger } from "../lib/logger";
44
import { bullMQErrorHandler } from "./error-handler";
55

@@ -71,7 +71,7 @@ export function initQueues(): Record<SweetQueue, Queue> {
7171

7272
for (const queueName of Object.values(SweetQueue)) {
7373
const queue = new Queue(queueName, {
74-
connection: redisConnection,
74+
connection: getRedisConnection(),
7575
defaultJobOptions: {
7676
attempts: 3,
7777
backoff: {
Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,14 @@
11
import IORedis from "ioredis";
22
import { env } from "../env";
33

4-
export const redisConnection = new IORedis(env.REDIS_CONNECTION_STRING, {
5-
maxRetriesPerRequest: null,
6-
});
4+
let redisConnection: IORedis | null = null;
5+
6+
export function getRedisConnection(): IORedis {
7+
if (!redisConnection) {
8+
redisConnection = new IORedis(env.REDIS_CONNECTION_STRING, {
9+
maxRetriesPerRequest: null,
10+
});
11+
}
12+
13+
return redisConnection;
14+
}

apps/api/src/bull-mq/workers.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { Processor, Worker, WorkerOptions } from "bullmq";
2-
import { redisConnection } from "./redis-connection";
2+
import { getRedisConnection } from "./redis-connection";
33
import { SweetQueue } from "./queues";
44
import {
55
bullMQErrorHandler,
@@ -23,7 +23,7 @@ export const createWorker = (
2323
return processor(job, token);
2424
},
2525
{
26-
connection: redisConnection,
26+
connection: getRedisConnection(),
2727
removeOnComplete: { age: 1 },
2828
removeOnFail: {
2929
age: 7 * 24 * 3600, // keep up to 7 days

apps/api/src/lib/octokit.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { createAppAuth, StrategyOptions } from "@octokit/auth-app";
22
import { Octokit } from "octokit";
33
import { graphql } from "@octokit/graphql";
44
import { config } from "../config";
5-
import { redisConnection } from "../bull-mq/redis-connection";
5+
import { getRedisConnection } from "../bull-mq/redis-connection";
66

77
export const octokit = new Octokit();
88

@@ -19,11 +19,11 @@ export const getAppOctoKit = () =>
1919

2020
const redisCaching: StrategyOptions["cache"] = {
2121
async get(key: string) {
22-
const cachedValue = await redisConnection.get(`github:token:${key}`);
22+
const cachedValue = await getRedisConnection().get(`github:token:${key}`);
2323
return cachedValue || "";
2424
},
2525
set(key: string, value: string) {
26-
redisConnection.setex(`github:token:${key}`, 3600, value);
26+
getRedisConnection().setex(`github:token:${key}`, 3600, value);
2727
},
2828
};
2929

0 commit comments

Comments
 (0)