chore: Implement short-lived redis cache for slots (#22787)
* chore: Implement short-lived redis cache for slots * chore: adapt apiv2 redis service to match with upstash redis * chore: safer redis service and ms ttl * fixup! chore: safer redis service and ms ttl * Wrap with timeout, currently doesn't work yet * Updated @upstash/redis for better signal support * Fix type errors, remove ts value * Inject NoopRedisService for NODE_ENV test * chore: bump platform libs * chore: bump platform libs * Upstash Redis upgrade no longer resulted in expected hard crash on init, so updated factory and our Upstash Redis Adapter to mimick old behaviour * Add SLOTS_CACHE_TTL variable for configurable ttl on slots cache * Update parseInt to use right types * chore: bump platform libs * chore: bump platform libs * chore: bump platform libs * update e2e api v2 action * set SLOTS_CACHE_TTL env var api v2 e2e --------- Co-authored-by: cal.com <[email protected]>
This commit is contained in:
1 parent
a71d949a0c
commit
b71d8baccc
19 files changed
+276
-41
No files matched your search
+1
-1
@@ -1,7 +1,7 @@
|
||||
export interface IRedisService {
|
||||
get: <TData>(key: string) => Promise<TData | null>;
|
||||
|
||||
set: <TData>(key: string, value: TData) => Promise<"OK" | TData | null>;
|
||||
set: <TData>(key: string, value: TData, opts?: { ttl?: number }) => Promise<"OK" | TData | null>;
|
||||
|
||||
expire: (key: string, seconds: number) => Promise<0 | 1>;
|
||||
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { IRedisService } from "./IRedisService";
|
||||
|
||||
/**
|
||||
* Noop implementation of IRedisService for testing or fallback scenarios.
|
||||
*/
|
||||
|
||||
export class NoopRedisService implements IRedisService {
|
||||
async get<TData>(_key: string): Promise<TData | null> {
|
||||
return null;
|
||||
}
|
||||
|
||||
async del(_key: string): Promise<number> {
|
||||
return 0;
|
||||
}
|
||||
|
||||
async set<TData>(_key: string, _value: TData, _opts?: { ttl?: number }): Promise<"OK" | TData | null> {
|
||||
return "OK";
|
||||
}
|
||||
|
||||
async expire(_key: string, _seconds: number): Promise<0 | 1> {
|
||||
// Implementation for setting expiration time for key in Redis
|
||||
return 0;
|
||||
}
|
||||
|
||||
async lrange<TResult = string>(_key: string, _start: number, _end: number): Promise<TResult[]> {
|
||||
return [];
|
||||
}
|
||||
|
||||
async lpush<TData>(_key: string, ..._elements: TData[]): Promise<number> {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,13 @@ export class RedisService implements IRedisService {
|
||||
private redis: Redis;
|
||||
|
||||
constructor() {
|
||||
this.redis = Redis.fromEnv();
|
||||
// Ensure we throw an Error to mimick old behavior
|
||||
if (!process.env.UPSTASH_REDIS_REST_URL || !process.env.UPSTASH_REDIS_REST_TOKEN) {
|
||||
throw new Error("Attempted to initialize Upstash Redis client without url or token.");
|
||||
}
|
||||
this.redis = Redis.fromEnv({
|
||||
signal: () => AbortSignal.timeout(2000),
|
||||
});
|
||||
}
|
||||
|
||||
async get<TData>(key: string): Promise<TData | null> {
|
||||
@@ -17,9 +23,16 @@ export class RedisService implements IRedisService {
|
||||
return this.redis.del(key);
|
||||
}
|
||||
|
||||
async set<TData>(key: string, value: TData): Promise<"OK" | TData | null> {
|
||||
// Implementation for setting value in Redis
|
||||
return this.redis.set(key, value);
|
||||
async set<TData>(key: string, value: TData, opts?: { ttl?: number }): Promise<"OK" | TData | null> {
|
||||
return this.redis.set(
|
||||
key,
|
||||
value,
|
||||
opts?.ttl
|
||||
? {
|
||||
px: opts.ttl,
|
||||
}
|
||||
: undefined
|
||||
);
|
||||
}
|
||||
|
||||
async expire(key: string, seconds: number): Promise<0 | 1> {
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { createModule } from "@evyweb/ioctopus";
|
||||
|
||||
import { DI_TOKENS } from "@calcom/lib/di/tokens";
|
||||
|
||||
import { NoopRedisService } from "../NoopRedisService";
|
||||
import { RedisService } from "../RedisService";
|
||||
|
||||
const redisModule = createModule();
|
||||
|
||||
redisModule.bind(DI_TOKENS.REDIS_CLIENT).toFactory(() => {
|
||||
if (process.env.UPSTASH_REDIS_REST_URL && process.env.UPSTASH_REDIS_REST_TOKEN) {
|
||||
return new RedisService();
|
||||
}
|
||||
return new NoopRedisService();
|
||||
}, "singleton");
|
||||
|
||||
export { redisModule };
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createContainer } from "@evyweb/ioctopus";
|
||||
|
||||
import { redisModule } from "@calcom/features/redis/di/redisModule";
|
||||
import { DI_TOKENS } from "@calcom/lib/di/tokens";
|
||||
import { prismaModule } from "@calcom/prisma/prisma.module";
|
||||
import type { AvailableSlotsService } from "@calcom/trpc/server/routers/viewer/slots/util";
|
||||
@@ -19,6 +20,7 @@ import { userRepositoryModule } from "../modules/user";
|
||||
import { getUserAvailabilityModule } from "../modules/get-user-availability";
|
||||
|
||||
const container = createContainer();
|
||||
container.load(DI_TOKENS.REDIS_CLIENT, redisModule);
|
||||
container.load(DI_TOKENS.PRISMA_MODULE, prismaModule);
|
||||
container.load(DI_TOKENS.OOO_REPOSITORY_MODULE, oooRepositoryModule);
|
||||
container.load(DI_TOKENS.SCHEDULE_REPOSITORY_MODULE, scheduleRepositoryModule);
|
||||
|
||||
@@ -15,6 +15,7 @@ availableSlotsModule.bind(DI_TOKENS.AVAILABLE_SLOTS_SERVICE).toClass(AvailableSl
|
||||
bookingRepo: DI_TOKENS.BOOKING_REPOSITORY,
|
||||
eventTypeRepo: DI_TOKENS.EVENT_TYPE_REPOSITORY,
|
||||
routingFormResponseRepo: DI_TOKENS.ROUTING_FORM_RESPONSE_REPOSITORY,
|
||||
redisClient: DI_TOKENS.REDIS_CLIENT,
|
||||
cacheService: DI_TOKENS.CACHE_SERVICE,
|
||||
checkBookingLimitsService: DI_TOKENS.CHECK_BOOKING_LIMITS_SERVICE,
|
||||
userAvailabilityService: DI_TOKENS.GET_USER_AVAILABILITY_SERVICE
|
||||
|
||||
@@ -2,6 +2,7 @@ export const DI_TOKENS = {
|
||||
PRISMA_CLIENT: Symbol("PrismaClient"),
|
||||
READ_ONLY_PRISMA_CLIENT: Symbol("ReadOnlyPrismaClient"),
|
||||
PRISMA_MODULE: Symbol("PrismaModule"),
|
||||
REDIS_CLIENT: Symbol("RedisClient"),
|
||||
OOO_REPOSITORY: Symbol("OOORepository"),
|
||||
OOO_REPOSITORY_MODULE: Symbol("OOORepositoryModule"),
|
||||
SCHEDULE_REPOSITORY: Symbol("ScheduleRepository"),
|
||||
|
||||
@@ -154,10 +154,9 @@ type GetUsersAvailabilityProps = {
|
||||
};
|
||||
|
||||
export interface IUserAvailabilityService {
|
||||
eventTypeRepo: EventTypeRepository;
|
||||
eventTypeRepo: EventTypeRepository;
|
||||
oooRepo: PrismaOOORepository;
|
||||
bookingRepo: BookingRepository;
|
||||
|
||||
}
|
||||
|
||||
export class UserAvailabilityService {
|
||||
@@ -611,4 +610,4 @@ export class UserAvailabilityService {
|
||||
}
|
||||
|
||||
getUsersAvailability = withReporting(this._getUsersAvailability.bind(this), "getUsersAvailability");
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import { orgDomainConfig } from "@calcom/ee/organizations/lib/orgDomains";
|
||||
import { checkForConflicts } from "@calcom/features/bookings/lib/conflictChecker/checkForConflicts";
|
||||
import { isEventTypeLoggingEnabled } from "@calcom/features/bookings/lib/isEventTypeLoggingEnabled";
|
||||
import type { CacheService } from "@calcom/features/calendar-cache/lib/getShouldServeCache";
|
||||
import type { IRedisService } from "@calcom/features/redis/IRedisService";
|
||||
import { findQualifiedHostsWithDelegationCredentials } from "@calcom/lib/bookings/findQualifiedHostsWithDelegationCredentials";
|
||||
import { shouldIgnoreContactOwner } from "@calcom/lib/bookings/routing/utils";
|
||||
import { RESERVED_SUBDOMAINS } from "@calcom/lib/constants";
|
||||
@@ -64,6 +65,7 @@ import { handleNotificationWhenNoSlots } from "./handleNotificationWhenNoSlots";
|
||||
import type { GetScheduleOptions } from "./types";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["[slots/util]"] });
|
||||
const DEFAULT_SLOTS_CACHE_TTL = 2000;
|
||||
|
||||
type GetAvailabilityUserWithDelegationCredentials = Omit<GetAvailabilityUser, "credentials"> & {
|
||||
credentials: CredentialForCalendarService[];
|
||||
@@ -101,7 +103,47 @@ export interface IAvailableSlotsService {
|
||||
routingFormResponseRepo: RoutingFormResponseRepository;
|
||||
cacheService: CacheService;
|
||||
checkBookingLimitsService: CheckBookingLimitsService;
|
||||
userAvailabilityService: UserAvailabilityService
|
||||
userAvailabilityService: UserAvailabilityService;
|
||||
redisClient: IRedisService;
|
||||
}
|
||||
|
||||
function withSlotsCache(
|
||||
redisClient: IRedisService,
|
||||
func: (args: GetScheduleOptions) => Promise<IGetAvailableSlots>
|
||||
) {
|
||||
return async (args: GetScheduleOptions): Promise<IGetAvailableSlots> => {
|
||||
const cacheKey = `${JSON.stringify(args.input)}`;
|
||||
let success = false;
|
||||
let cachedResult: IGetAvailableSlots | null = null;
|
||||
const startTime = process.hrtime();
|
||||
try {
|
||||
cachedResult = await redisClient.get(cacheKey);
|
||||
success = true;
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof Error && err.name === "TimeoutError") {
|
||||
const endTime = process.hrtime(startTime);
|
||||
log.error(`Redis request timed out after ${endTime[0]}${endTime[1] / 1e6}ms`);
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
if (!success) {
|
||||
// If the cache request fails, we proceed to call the function directly
|
||||
return await func(args);
|
||||
}
|
||||
if (cachedResult) {
|
||||
log.info("[CACHE HIT] Available slots", { cacheKey });
|
||||
return cachedResult;
|
||||
}
|
||||
const result = await func(args);
|
||||
const ttl = parseInt(process.env.SLOTS_CACHE_TTL ?? "", 10) || DEFAULT_SLOTS_CACHE_TTL;
|
||||
// we do not wait for the cache to complete setting; we fire and forget, and hope it'll finish.
|
||||
// this is to already start responding to the client.
|
||||
redisClient.set(cacheKey, result, { ttl });
|
||||
log.info("[CACHE MISS] Available slots", { cacheKey, ttl });
|
||||
return result;
|
||||
};
|
||||
}
|
||||
|
||||
export class AvailableSlotsService {
|
||||
@@ -884,7 +926,10 @@ export class AvailableSlotsService {
|
||||
"getRegularOrDynamicEventType"
|
||||
);
|
||||
|
||||
getAvailableSlots = withReporting(this._getAvailableSlots.bind(this), "getAvailableSlots");
|
||||
getAvailableSlots = withReporting(
|
||||
withSlotsCache(this.dependencies.redisClient, this._getAvailableSlots.bind(this)),
|
||||
"getAvailableSlots"
|
||||
);
|
||||
|
||||
async _getAvailableSlots({ input, ctx }: GetScheduleOptions): Promise<IGetAvailableSlots> {
|
||||
const {
|
||||
|
||||
Reference in new issue
Block a user