feat(flags): add @Memoize and @Unmemoize decorators for declarative caching (#27063)

* feat(flags): add @Memoize and @Unmemoize decorators for declarative caching

- Add @Memoize decorator for caching method results with Zod validation
- Add @Unmemoize decorator for cache invalidation on mutations
- Create UserFeatureRepository using decorators as example implementation
- Add comprehensive tests with 80%+ coverage (19 tests)
- Add DI module and tokens for UserFeatureRepository
- Enable experimentalDecorators in packages/features/tsconfig.json

Co-Authored-By: [email protected] <[email protected]>

* refactor(cache): use lazy Redis lookup in decorators

- Decorators now access Redis via getRedisService() instead of this.redis
- UserFeatureRepository no longer has redis property or direct redis calls
- findByUserIdAndFeatureIds now uses decorated findByUserIdAndFeatureId
- DI module simplified to only pass prisma dependency
- Tests updated to call setRedisService() in beforeEach

This ensures the repository only knows about Prisma, with all caching
handled transparently by the decorators.

Co-Authored-By: [email protected] <[email protected]>

* feat(flags): add FeatureRepository and TeamFeatureRepository with decorator-based caching

- Add FeatureRepository with @Memoize decorators for findAll, findBySlug, getFeatureFlagMap
- Add TeamFeatureRepository with @Memoize/@Unmemoize decorators for all CRUD operations
- Add comprehensive Zod schemas for Feature, TeamFeatures, and AppFlags validation
- Add DI modules and tokens for both repositories
- Add comprehensive test coverage (33 tests) for both repositories
- Maintain backward compatibility with existing FEATURES_REPOSITORY tokens

Co-Authored-By: [email protected] <[email protected]>

* refactor(cache): use DI container pattern for Redis service

- Create packages/features/di/containers/Redis.ts with getRedisService()
- Update Memoize and Unmemoize decorators to import from DI container
- Remove setRedisService() and IRedisService from types.ts exports
- Update all tests to mock the container's getRedisService
- Fix import ordering issues from biome

Co-Authored-By: [email protected] <[email protected]>

* refactor(cache): remove barrel import and add root-level cache export

- Remove packages/features/cache/decorators/index.ts barrel file
- Add packages/features/cache/index.ts as root-level export for cache feature
- Update repository imports to use direct imports from source files
- Follows the pattern: avoid barrel imports at nested levels, keep at feature root

Co-Authored-By: [email protected] <[email protected]>

* refactor(flags): minimize repository methods and address PR feedback

- Remove unnecessary methods from FeatureRepository, TeamFeatureRepository, and UserFeatureRepository
- Keep only methods needed by FeatureOptInService
- Update imports to use @calcom/features/cache public API instead of relative paths
- Handle redis.del() errors gracefully in Unmemoize decorator
- Update tests to match simplified repositories

Co-Authored-By: [email protected] <[email protected]>

* refactor(cache): use Promise.allSettled for cache invalidation

Cleaner approach than Promise.all with individual .catch() handlers

Co-Authored-By: [email protected] <[email protected]>

* feat(flags): add setAutoOptIn methods and replace featuresRepository usage in _router.ts

- Add setAutoOptIn method to TeamFeatureRepository with @Unmemoize decorator
- Add setAutoOptIn method to UserFeatureRepository with @Unmemoize decorator
- Replace featuresRepository usage in featureOptIn/_router.ts with new repositories
- TeamFeatureRepository.setAutoOptIn unmemoizes KEY.autoOptInByTeamId(teamId)
- UserFeatureRepository.setAutoOptIn unmemoizes KEY.autoOptInByUserId(userId)

Co-Authored-By: [email protected] <[email protected]>

* refactor(flags): use DI containers for TeamFeatureRepository and UserFeatureRepository

- Create TeamFeatureRepository.ts container with getTeamFeatureRepository()
- Create UserFeatureRepository.ts container with getUserFeatureRepository()
- Update _router.ts to use DI containers instead of direct instantiation

Co-Authored-By: [email protected] <[email protected]>

* refactor(feature-opt-in): use DI containers for FeatureOptInService dependencies

- Update FeatureOptInService to use IFeatureOptInServiceDeps with 3 repositories
- Add helper functions teamFeatureToState() and userFeatureToState()
- Update DI module to use depsMap pattern with featureRepo, teamFeatureRepo, userFeatureRepo
- Create FeatureRepository container file
- Replace all FeaturesRepository method calls with new repository methods

Co-Authored-By: [email protected] <[email protected]>

* test(feature-opt-in): update FeatureOptInService tests for new IFeatureOptInServiceDeps interface

- Update mock structure to use featureRepo, teamFeatureRepo, userFeatureRepo
- Add helper functions createMockTeamFeature and createMockUserFeature
- Update all test cases to use new repository method names
- Add explicit types to satisfy biome lint rules

Co-Authored-By: [email protected] <[email protected]>

* refactor(flags): use DTOs at repository boundaries to prevent Prisma type leakage

- Create FeatureDto, TeamFeaturesDto, UserFeaturesDto in packages/lib/dto/
- Update repository interfaces to return DTOs instead of Prisma types
- Add toDto() transformation methods in repository implementations
- Update FeatureOptInService to use DTOs instead of Prisma types
- Follow data-dto-boundaries.md guidelines for architectural boundaries

Co-Authored-By: [email protected] <[email protected]>

* fix(flags): update TeamFeatureRepository tests to match DTO structure

Remove assignedAt from test mock data since TeamFeaturesDto only includes:
teamId, featureId, enabled, assignedBy, and updatedAt

Co-Authored-By: unknown <>

* fix(cache): make Redis failures non-blocking in @Memoize decorator

Wrap Redis get and set operations in try-catch blocks to ensure
Redis failures don't break the application flow. If cache read fails,
proceed to fetch from source. If cache write fails, silently ignore
and return the result.

Co-Authored-By: unknown <>

* fix(cache): add logging for Redis failures and remove barrel import

- Add warning logs for Redis failures in @Memoize and @Unmemoize decorators
- Remove packages/lib/dto/index.ts barrel import file
- Update all imports to use direct file paths instead of barrel imports

Co-Authored-By: unknown <>

* fix(cache): sanitize log messages to avoid exposing sensitive data

- Remove cacheKey from log messages (may contain PII like user/team IDs)
- Log only error.message instead of raw error objects
- Addresses Cubic AI feedback (confidence 9/10)

Co-Authored-By: unknown <>

* sanitize log

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Volnei Munhoz <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-01-22 16:26:27 +01:00
1 parent a2a4ca41ec
commit aa8804e498
29 files changed
+2080 -166

No files matched your search

@@ -0,0 +1,290 @@
# Memoize/Unmemoize Decorator Implementation Plan
## Overview
This plan outlines the implementation of `@Memoize` and `@Unmemoize` decorators to replace the current CachedXXRepository + PrismaXXRepository + RedisXXRepository pattern (9 classes per 3 entities) with a more declarative approach.
## Current State
The current implementation uses three layers per entity:
- `PrismaUserFeatureRepository` - Database access
- `RedisUserFeatureRepository` - Cache operations (get/set/invalidate)
- `CachedUserFeatureRepository` - Orchestrates cache-aside pattern
This results in 9 repository classes for 3 entities (Feature, TeamFeature, UserFeature), with repetitive cache-aside logic in each CachedXXRepository.
## Target State
A single repository class per entity with decorators handling caching:
```typescript
class UserFeatureRepository {
@Memoize({ key: (userId, featureId) => `features:user:${userId}:${featureId}`, schema: userFeaturesSchema })
async findByUserIdAndFeatureId(userId: number, featureId: FeatureId): Promise<UserFeatures | null> {
return this.prisma.userFeatures.findUnique({ where: { userId_featureId: { userId, featureId } } });
}
@Unmemoize({ keys: (userId, featureId) => [`features:user:${userId}:${featureId}`] })
async upsert(userId: number, featureId: FeatureId, enabled: boolean, assignedBy: string): Promise<UserFeatures> {
return this.prisma.userFeatures.upsert({ ... });
}
}
```
## Implementation Steps
### Step 1: Enable Decorators in tsconfig (if needed)
The `packages/features/tsconfig.json` extends `@calcom/tsconfig/react-library.json`. We need to add `experimentalDecorators: true` to enable legacy decorators.
**Note**: Many packages already have `experimentalDecorators: true` (apps/web, apps/api/v2, packages/trpc, etc.), so this is consistent with the codebase.
### Step 2: Create Decorator Infrastructure
Create new files in `packages/features/cache/`:
1. **`packages/features/cache/decorators/Memoize.ts`**
- Decorator that wraps methods with cache-aside logic
- Accepts configuration: `key`, `ttl`, `schema` (Zod)
- Uses `IRedisService` for cache operations
- Validates cached data with Zod schema before returning
2. **`packages/features/cache/decorators/Unmemoize.ts`**
- Decorator that invalidates cache keys after method execution
- Accepts configuration: `keys` (function returning array of cache keys)
- Invalidates specified keys after the wrapped method completes
3. **`packages/features/cache/decorators/index.ts`**
- Re-exports both decorators
4. **`packages/features/cache/decorators/types.ts`**
- Shared types for decorator configuration
### Step 3: Implement @Memoize Decorator
```typescript
interface MemoizeConfig<TArgs extends unknown[]> {
key: (...args: TArgs) => string;
ttl?: number;
schema?: ZodSchema;
}
function Memoize<TArgs extends unknown[]>(config: MemoizeConfig<TArgs>) {
return function <T extends { redis: IRedisService }>(
target: (this: T, ...args: TArgs) => Promise<unknown>,
context: ClassMethodDecoratorContext
) {
return async function (this: T, ...args: TArgs) {
const cacheKey = config.key(...args);
const cached = await this.redis.get<unknown>(cacheKey);
if (cached !== null) {
if (config.schema) {
const parsed = config.schema.safeParse(cached);
if (parsed.success) return parsed.data;
} else {
return cached;
}
}
const result = await target.call(this, ...args);
if (result !== null) {
await this.redis.set(cacheKey, result, { ttl: config.ttl ?? DEFAULT_TTL });
}
return result;
};
};
}
```
### Step 4: Implement @Unmemoize Decorator
```typescript
interface UnmemoizeConfig<TArgs extends unknown[]> {
keys: (...args: TArgs) => string[];
}
function Unmemoize<TArgs extends unknown[]>(config: UnmemoizeConfig<TArgs>) {
return function <T extends { redis: IRedisService }>(
target: (this: T, ...args: TArgs) => Promise<unknown>,
context: ClassMethodDecoratorContext
) {
return async function (this: T, ...args: TArgs) {
const result = await target.call(this, ...args);
const keysToInvalidate = config.keys(...args);
await Promise.all(keysToInvalidate.map((key) => this.redis.del(key)));
return result;
};
};
}
```
### Step 5: Refactor UserFeatureRepository
Create a new unified `UserFeatureRepository` that uses decorators:
```typescript
export class UserFeatureRepository implements IUserFeatureRepository {
constructor(
private prisma: PrismaClient,
private redis: IRedisService
) {}
async findByUserId(userId: number): Promise<UserFeatures[]> {
return this.prisma.userFeatures.findMany({ where: { userId } });
}
@Memoize({
key: (userId: number, featureId: FeatureId) => `features:user:${userId}:${featureId}`,
schema: userFeaturesSchema,
})
async findByUserIdAndFeatureId(userId: number, featureId: FeatureId): Promise<UserFeatures | null> {
return this.prisma.userFeatures.findUnique({
where: { userId_featureId: { userId, featureId } },
});
}
@Memoize({
key: (userId: number) => `features:user:autoOptIn:${userId}`,
schema: booleanSchema,
})
async findAutoOptInByUserId(userId: number): Promise<boolean> {
const user = await this.prisma.user.findUnique({
where: { id: userId },
select: { autoOptInFeatures: true },
});
return user?.autoOptInFeatures ?? false;
}
@Unmemoize({
keys: (userId: number, featureId: FeatureId) => [`features:user:${userId}:${featureId}`],
})
async upsert(userId: number, featureId: FeatureId, enabled: boolean, assignedBy: string): Promise<UserFeatures> {
return this.prisma.userFeatures.upsert({
where: { userId_featureId: { userId, featureId } },
create: { userId, featureId, enabled, assignedBy },
update: { enabled, assignedBy },
});
}
@Unmemoize({
keys: (userId: number, featureId: FeatureId) => [`features:user:${userId}:${featureId}`],
})
async delete(userId: number, featureId: FeatureId): Promise<void> {
await this.prisma.userFeatures.delete({
where: { userId_featureId: { userId, featureId } },
});
}
@Unmemoize({
keys: (userId: number) => [`features:user:autoOptIn:${userId}`],
})
async updateAutoOptIn(userId: number, enabled: boolean): Promise<void> {
await this.prisma.user.update({
where: { id: userId },
data: { autoOptInFeatures: enabled },
});
}
// Methods without caching (complex queries)
async checkIfUserBelongsToTeamWithFeature(userId: number, slug: string): Promise<boolean> {
// ... existing implementation
}
async checkIfUserBelongsToTeamWithFeatureNonHierarchical(userId: number, slug: string): Promise<boolean> {
// ... existing implementation
}
}
```
### Step 6: Update DI Configuration
Update the DI module to use the new unified repository:
```typescript
// packages/features/flags/di/UserFeatureRepository.module.ts
const loadModule = bindModuleToClassOnToken({
module: thisModule,
moduleToken,
token,
classs: UserFeatureRepository,
depsMap: {
prisma: prismaModuleLoader,
redis: redisModuleLoader,
},
});
```
### Step 7: Write Tests
Create comprehensive tests for the decorators:
1. **`packages/features/cache/decorators/__tests__/Memoize.test.ts`**
- Test cache hit returns cached value
- Test cache miss fetches from source and caches
- Test Zod validation on cached data
- Test null results are not cached
- Test TTL is respected
2. **`packages/features/cache/decorators/__tests__/Unmemoize.test.ts`**
- Test cache keys are invalidated after method execution
- Test multiple keys can be invalidated
- Test method result is returned correctly
## File Structure
```
packages/features/
cache/
decorators/
__tests__/
Memoize.test.ts
Unmemoize.test.ts
Memoize.ts
Unmemoize.ts
types.ts
index.ts
flags/
repositories/
UserFeatureRepository.ts (new unified repository)
# Keep existing files for backward compatibility during migration
di/
UserFeatureRepository.module.ts (new module)
tokens.ts (add new token)
```
## Migration Strategy
1. Create the new decorator infrastructure alongside existing code
2. Create the new unified `UserFeatureRepository` with decorators
3. Add new DI module for the unified repository
4. Update consumers to use the new repository
5. Remove old CachedXXRepository, RedisXXRepository files after migration is complete
## Benefits
1. **Reduced boilerplate**: 1 class instead of 3 per entity
2. **Declarative caching**: Cache behavior is visible at method level
3. **Co-located logic**: Caching and invalidation rules are next to the methods they affect
4. **Type-safe**: Full TypeScript support with proper typing
5. **Testable**: Decorators can be tested independently
6. **Consistent**: Same pattern for all repositories
## Considerations
1. **Decorator limitations**: Legacy decorators (experimentalDecorators) are used since TC39 decorators have different semantics
2. **Redis dependency**: Repository classes must have `redis: IRedisService` property for decorators to work
3. **Zod validation**: Optional but recommended for cached data integrity
4. **TTL**: Default 5 minutes, configurable per method
## Timeline
1. Step 1-2: Create decorator infrastructure (~30 min)
2. Step 3-4: Implement decorators (~30 min)
3. Step 5: Refactor UserFeatureRepository (~30 min)
4. Step 6: Update DI configuration (~15 min)
5. Step 7: Write tests (~45 min)
6. Type checks and lint (~15 min)
7. Create PR (~10 min)
Total estimated time: ~3 hours
@@ -0,0 +1,23 @@
import { createModule, type ModuleLoader } from "@calcom/features/di/di";
import { moduleLoader as prismaModuleLoader } from "@calcom/features/di/modules/Prisma";
import type { Module } from "@evyweb/ioctopus";
import { FeatureRepository } from "../repositories/FeatureRepository";
import { FLAGS_DI_TOKENS } from "./tokens";
const thisModule: Module = createModule();
const token: symbol = FLAGS_DI_TOKENS.FEATURE_REPOSITORY;
const moduleToken: symbol = FLAGS_DI_TOKENS.FEATURE_REPOSITORY_MODULE;
thisModule.bind(token).toClass(FeatureRepository, [prismaModuleLoader.token]);
const loadModule = (container: ReturnType<typeof import("@calcom/features/di/di").createContainer>): void => {
container.load(moduleToken, thisModule);
prismaModuleLoader.loadModule(container);
};
export const moduleLoader: ModuleLoader = {
token,
loadModule,
};
export type { FeatureRepository };
@@ -0,0 +1,23 @@
import { createModule, type ModuleLoader } from "@calcom/features/di/di";
import { moduleLoader as prismaModuleLoader } from "@calcom/features/di/modules/Prisma";
import type { Module } from "@evyweb/ioctopus";
import { TeamFeatureRepository } from "../repositories/TeamFeatureRepository";
import { FLAGS_DI_TOKENS } from "./tokens";
const thisModule: Module = createModule();
const token: symbol = FLAGS_DI_TOKENS.TEAM_FEATURE_REPOSITORY;
const moduleToken: symbol = FLAGS_DI_TOKENS.TEAM_FEATURE_REPOSITORY_MODULE;
thisModule.bind(token).toClass(TeamFeatureRepository, [prismaModuleLoader.token]);
const loadModule = (container: ReturnType<typeof import("@calcom/features/di/di").createContainer>): void => {
container.load(moduleToken, thisModule);
prismaModuleLoader.loadModule(container);
};
export const moduleLoader: ModuleLoader = {
token,
loadModule,
};
export type { TeamFeatureRepository };
@@ -0,0 +1,25 @@
import type { Module } from "@evyweb/ioctopus";
import { createModule, type ModuleLoader } from "@calcom/features/di/di";
import { moduleLoader as prismaModuleLoader } from "@calcom/features/di/modules/Prisma";
import { UserFeatureRepository } from "../repositories/UserFeatureRepository";
import { FLAGS_DI_TOKENS } from "./tokens";
const thisModule: Module = createModule();
const token: symbol = FLAGS_DI_TOKENS.USER_FEATURE_REPOSITORY;
const moduleToken: symbol = FLAGS_DI_TOKENS.USER_FEATURE_REPOSITORY_MODULE;
thisModule.bind(token).toClass(UserFeatureRepository, [prismaModuleLoader.token]);
const loadModule = (container: ReturnType<typeof import("@calcom/features/di/di").createContainer>): void => {
container.load(moduleToken, thisModule);
prismaModuleLoader.loadModule(container);
};
export const moduleLoader: ModuleLoader = {
token,
loadModule,
};
export type { UserFeatureRepository };
+19 -1
View File
@@ -1,4 +1,22 @@
export const FLAGS_DI_TOKENS = {
export const FLAGS_DI_TOKENS: {
FEATURES_REPOSITORY: symbol;
FEATURES_REPOSITORY_MODULE: symbol;
FEATURE_REPOSITORY: symbol;
FEATURE_REPOSITORY_MODULE: symbol;
TEAM_FEATURE_REPOSITORY: symbol;
TEAM_FEATURE_REPOSITORY_MODULE: symbol;
USER_FEATURE_REPOSITORY: symbol;
USER_FEATURE_REPOSITORY_MODULE: symbol;
} = {
FEATURES_REPOSITORY: Symbol("FeaturesRepository"),
FEATURES_REPOSITORY_MODULE: Symbol("FeaturesRepositoryModule"),
FEATURE_REPOSITORY: Symbol("FeatureRepository"),
FEATURE_REPOSITORY_MODULE: Symbol("FeatureRepositoryModule"),
TEAM_FEATURE_REPOSITORY: Symbol("TeamFeatureRepository"),
TEAM_FEATURE_REPOSITORY_MODULE: Symbol("TeamFeatureRepositoryModule"),
USER_FEATURE_REPOSITORY: Symbol("UserFeatureRepository"),
USER_FEATURE_REPOSITORY_MODULE: Symbol("UserFeatureRepositoryModule"),
};
@@ -0,0 +1,42 @@
import { Memoize } from "@calcom/features/cache";
import type { FeatureDto } from "@calcom/lib/dto/FeatureDto";
import { FeatureDtoArraySchema } from "@calcom/lib/dto/FeatureDto";
import type { PrismaClient } from "@calcom/prisma/client";
const CACHE_PREFIX = "features:global";
const KEY = {
all: (): string => `${CACHE_PREFIX}:all`,
};
export interface IFeatureRepository {
findAll(): Promise<FeatureDto[]>;
}
export class FeatureRepository implements IFeatureRepository {
private prisma: PrismaClient;
constructor(prisma: PrismaClient) {
this.prisma = prisma;
}
@Memoize({
key: () => KEY.all(),
schema: FeatureDtoArraySchema,
})
async findAll(): Promise<FeatureDto[]> {
const features = await this.prisma.feature.findMany({
orderBy: { slug: "asc" },
});
return features.map((f) => ({
slug: f.slug,
enabled: f.enabled,
description: f.description,
type: f.type,
stale: f.stale,
lastUsedAt: f.lastUsedAt,
createdAt: f.createdAt,
updatedAt: f.updatedAt,
updatedBy: f.updatedBy,
}));
}
}
@@ -0,0 +1,190 @@
import { Memoize, Unmemoize } from "@calcom/features/cache";
import type { TeamFeaturesDto } from "@calcom/lib/dto/TeamFeaturesDto";
import { TeamFeaturesDtoSchema } from "@calcom/lib/dto/TeamFeaturesDto";
import type { PrismaClient } from "@calcom/prisma/client";
import type { FeatureId } from "../config";
import { booleanSchema } from "./schemas";
const CACHE_PREFIX = "features:team";
const KEY = {
byTeamIdAndFeatureId: (teamId: number, featureId: string): string =>
`${CACHE_PREFIX}:${teamId}:${featureId}`,
autoOptInByTeamId: (teamId: number): string => `${CACHE_PREFIX}:autoOptIn:${teamId}`,
};
export interface ITeamFeatureRepository {
findByTeamIdAndFeatureId(teamId: number, featureId: FeatureId): Promise<TeamFeaturesDto | null>;
findByTeamIdsAndFeatureIds(
teamIds: number[],
featureIds: FeatureId[]
): Promise<Partial<Record<FeatureId, Record<number, TeamFeaturesDto>>>>;
upsert(
teamId: number,
featureId: FeatureId,
enabled: boolean,
assignedBy: string
): Promise<TeamFeaturesDto>;
delete(teamId: number, featureId: FeatureId): Promise<void>;
findAutoOptInByTeamId(teamId: number): Promise<boolean>;
findAutoOptInByTeamIds(teamIds: number[]): Promise<Record<number, boolean>>;
setAutoOptIn(teamId: number, enabled: boolean): Promise<void>;
}
export class TeamFeatureRepository implements ITeamFeatureRepository {
private prisma: PrismaClient;
constructor(prisma: PrismaClient) {
this.prisma = prisma;
}
@Memoize({
key: (teamId: number, featureId: FeatureId) => KEY.byTeamIdAndFeatureId(teamId, featureId),
schema: TeamFeaturesDtoSchema,
})
async findByTeamIdAndFeatureId(teamId: number, featureId: FeatureId): Promise<TeamFeaturesDto | null> {
const result = await this.prisma.teamFeatures.findUnique({
where: {
teamId_featureId: {
teamId,
featureId,
},
},
});
if (!result) return null;
return this.toDto(result);
}
async findByTeamIdsAndFeatureIds(
teamIds: number[],
featureIds: FeatureId[]
): Promise<Partial<Record<FeatureId, Record<number, TeamFeaturesDto>>>> {
if (teamIds.length === 0 || featureIds.length === 0) {
return {};
}
const results = await Promise.all(
teamIds.flatMap((teamId) =>
featureIds.map(async (featureId) => {
const teamFeature = await this.findByTeamIdAndFeatureId(teamId, featureId);
return { teamId, featureId, teamFeature };
})
)
);
const result: Partial<Record<FeatureId, Record<number, TeamFeaturesDto>>> = {};
for (const { teamId, featureId, teamFeature } of results) {
if (teamFeature !== null) {
if (!result[featureId]) {
result[featureId] = {};
}
const featureRecord = result[featureId];
if (featureRecord) {
featureRecord[teamId] = teamFeature;
}
}
}
return result;
}
@Unmemoize({
keys: (teamId: number, featureId: FeatureId) => [KEY.byTeamIdAndFeatureId(teamId, featureId)],
})
async upsert(
teamId: number,
featureId: FeatureId,
enabled: boolean,
assignedBy: string
): Promise<TeamFeaturesDto> {
const result = await this.prisma.teamFeatures.upsert({
where: {
teamId_featureId: {
teamId,
featureId,
},
},
create: {
teamId,
featureId,
enabled,
assignedBy,
},
update: {
enabled,
assignedBy,
},
});
return this.toDto(result);
}
private toDto(teamFeature: {
teamId: number;
featureId: string;
enabled: boolean;
assignedBy: string;
updatedAt: Date;
}): TeamFeaturesDto {
return {
teamId: teamFeature.teamId,
featureId: teamFeature.featureId,
enabled: teamFeature.enabled,
assignedBy: teamFeature.assignedBy,
updatedAt: teamFeature.updatedAt,
};
}
@Unmemoize({
keys: (teamId: number, featureId: FeatureId) => [KEY.byTeamIdAndFeatureId(teamId, featureId)],
})
async delete(teamId: number, featureId: FeatureId): Promise<void> {
await this.prisma.teamFeatures.delete({
where: {
teamId_featureId: {
teamId,
featureId,
},
},
});
}
@Memoize({
key: (teamId: number) => KEY.autoOptInByTeamId(teamId),
schema: booleanSchema,
})
async findAutoOptInByTeamId(teamId: number): Promise<boolean> {
const team = await this.prisma.team.findUnique({
where: { id: teamId },
select: { autoOptInFeatures: true },
});
return team?.autoOptInFeatures ?? false;
}
async findAutoOptInByTeamIds(teamIds: number[]): Promise<Record<number, boolean>> {
if (teamIds.length === 0) {
return {};
}
const results = await Promise.all(
teamIds.map(async (teamId) => {
const autoOptIn = await this.findAutoOptInByTeamId(teamId);
return { teamId, autoOptIn };
})
);
const result: Record<number, boolean> = {};
for (const { teamId, autoOptIn } of results) {
result[teamId] = autoOptIn;
}
return result;
}
@Unmemoize({
keys: (teamId: number) => [KEY.autoOptInByTeamId(teamId)],
})
async setAutoOptIn(teamId: number, enabled: boolean): Promise<void> {
await this.prisma.team.update({
where: { id: teamId },
data: { autoOptInFeatures: enabled },
});
}
}
@@ -0,0 +1,158 @@
import { Memoize, Unmemoize } from "@calcom/features/cache";
import type { UserFeaturesDto } from "@calcom/lib/dto/UserFeaturesDto";
import { UserFeaturesDtoSchema } from "@calcom/lib/dto/UserFeaturesDto";
import type { PrismaClient } from "@calcom/prisma/client";
import type { FeatureId } from "../config";
import { booleanSchema } from "./schemas";
const CACHE_PREFIX = "features:user";
const KEY = {
byUserIdAndFeatureId: (userId: number, featureId: string): string =>
`${CACHE_PREFIX}:${userId}:${featureId}`,
autoOptInByUserId: (userId: number): string => `${CACHE_PREFIX}:autoOptIn:${userId}`,
};
export interface IUserFeatureRepository {
findByUserIdAndFeatureId(userId: number, featureId: FeatureId): Promise<UserFeaturesDto | null>;
findByUserIdAndFeatureIds(
userId: number,
featureIds: FeatureId[]
): Promise<Partial<Record<FeatureId, UserFeaturesDto>>>;
upsert(
userId: number,
featureId: FeatureId,
enabled: boolean,
assignedBy: string
): Promise<UserFeaturesDto>;
delete(userId: number, featureId: FeatureId): Promise<void>;
findAutoOptInByUserId(userId: number): Promise<boolean>;
setAutoOptIn(userId: number, enabled: boolean): Promise<void>;
}
export class UserFeatureRepository implements IUserFeatureRepository {
private prisma: PrismaClient;
constructor(prisma: PrismaClient) {
this.prisma = prisma;
}
@Memoize({
key: (userId: number, featureId: FeatureId) => KEY.byUserIdAndFeatureId(userId, featureId),
schema: UserFeaturesDtoSchema,
})
async findByUserIdAndFeatureId(userId: number, featureId: FeatureId): Promise<UserFeaturesDto | null> {
const result = await this.prisma.userFeatures.findUnique({
where: {
userId_featureId: {
userId,
featureId,
},
},
});
if (!result) return null;
return this.toDto(result);
}
async findByUserIdAndFeatureIds(
userId: number,
featureIds: FeatureId[]
): Promise<Partial<Record<FeatureId, UserFeaturesDto>>> {
const results = await Promise.all(
featureIds.map(async (featureId) => {
const userFeature = await this.findByUserIdAndFeatureId(userId, featureId);
return { featureId, userFeature };
})
);
const result: Partial<Record<FeatureId, UserFeaturesDto>> = {};
for (const { featureId, userFeature } of results) {
if (userFeature !== null) {
result[featureId] = userFeature;
}
}
return result;
}
@Unmemoize({
keys: (userId: number, featureId: FeatureId) => [KEY.byUserIdAndFeatureId(userId, featureId)],
})
async upsert(
userId: number,
featureId: FeatureId,
enabled: boolean,
assignedBy: string
): Promise<UserFeaturesDto> {
const result = await this.prisma.userFeatures.upsert({
where: {
userId_featureId: {
userId,
featureId,
},
},
create: {
userId,
featureId,
enabled,
assignedBy,
},
update: {
enabled,
assignedBy,
},
});
return this.toDto(result);
}
private toDto(userFeature: {
userId: number;
featureId: string;
enabled: boolean;
assignedBy: string;
updatedAt: Date;
}): UserFeaturesDto {
return {
userId: userFeature.userId,
featureId: userFeature.featureId,
enabled: userFeature.enabled,
assignedBy: userFeature.assignedBy,
updatedAt: userFeature.updatedAt,
};
}
@Unmemoize({
keys: (userId: number, featureId: FeatureId) => [KEY.byUserIdAndFeatureId(userId, featureId)],
})
async delete(userId: number, featureId: FeatureId): Promise<void> {
await this.prisma.userFeatures.delete({
where: {
userId_featureId: {
userId,
featureId,
},
},
});
}
@Memoize({
key: (userId: number) => KEY.autoOptInByUserId(userId),
schema: booleanSchema,
})
async findAutoOptInByUserId(userId: number): Promise<boolean> {
const user = await this.prisma.user.findUnique({
where: { id: userId },
select: { autoOptInFeatures: true },
});
return user?.autoOptInFeatures ?? false;
}
@Unmemoize({
keys: (userId: number) => [KEY.autoOptInByUserId(userId)],
})
async setAutoOptIn(userId: number, enabled: boolean): Promise<void> {
await this.prisma.user.update({
where: { id: userId },
data: { autoOptInFeatures: enabled },
});
}
}
@@ -0,0 +1,100 @@
import type { IRedisService } from "@calcom/features/redis/IRedisService";
import type { PrismaClient } from "@calcom/prisma/client";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { FeatureRepository } from "../FeatureRepository";
interface MockPrisma {
feature: {
findMany: ReturnType<typeof vi.fn>;
};
}
function createMockRedis(): IRedisService {
return {
get: vi.fn(),
set: vi.fn(),
del: vi.fn(),
expire: vi.fn(),
lrange: vi.fn(),
lpush: vi.fn(),
};
}
function createMockPrisma(): MockPrisma {
return {
feature: {
findMany: vi.fn(),
},
};
}
let mockRedis: IRedisService;
vi.mock("@calcom/features/di/containers/Redis", () => ({
getRedisService: () => mockRedis,
}));
describe("FeatureRepository", () => {
let mockPrisma: MockPrisma;
let repository: FeatureRepository;
beforeEach(() => {
mockRedis = createMockRedis();
mockPrisma = createMockPrisma();
repository = new FeatureRepository(mockPrisma as unknown as PrismaClient);
vi.clearAllMocks();
});
describe("findAll", () => {
it("should return cached features on cache hit", async () => {
const cachedFeatures = [
{
slug: "feature-1",
enabled: true,
description: "Test feature",
type: "RELEASE",
stale: false,
lastUsedAt: null,
createdAt: new Date("2024-01-01"),
updatedAt: new Date("2024-01-01"),
updatedBy: null,
},
];
vi.mocked(mockRedis.get).mockResolvedValue(cachedFeatures);
const result = await repository.findAll();
expect(result).toEqual(cachedFeatures);
expect(mockRedis.get).toHaveBeenCalledWith("features:global:all");
expect(mockPrisma.feature.findMany).not.toHaveBeenCalled();
});
it("should fetch from database and cache on cache miss", async () => {
const dbFeatures = [
{
slug: "feature-1",
enabled: true,
description: "Test feature",
type: "RELEASE",
stale: false,
lastUsedAt: null,
createdAt: new Date("2024-01-01"),
updatedAt: new Date("2024-01-01"),
updatedBy: null,
},
];
vi.mocked(mockRedis.get).mockResolvedValue(null);
vi.mocked(mockPrisma.feature.findMany).mockResolvedValue(dbFeatures);
vi.mocked(mockRedis.set).mockResolvedValue("OK");
const result = await repository.findAll();
expect(result).toEqual(dbFeatures);
expect(mockRedis.get).toHaveBeenCalledWith("features:global:all");
expect(mockPrisma.feature.findMany).toHaveBeenCalledWith({
orderBy: { slug: "asc" },
});
expect(mockRedis.set).toHaveBeenCalled();
});
});
});
@@ -0,0 +1,271 @@
import type { IRedisService } from "@calcom/features/redis/IRedisService";
import type { PrismaClient } from "@calcom/prisma/client";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { TeamFeatureRepository } from "../TeamFeatureRepository";
interface MockPrisma {
teamFeatures: {
findUnique: ReturnType<typeof vi.fn>;
upsert: ReturnType<typeof vi.fn>;
delete: ReturnType<typeof vi.fn>;
};
team: {
findUnique: ReturnType<typeof vi.fn>;
};
}
function createMockRedis(): IRedisService {
return {
get: vi.fn(),
set: vi.fn(),
del: vi.fn(),
expire: vi.fn(),
lrange: vi.fn(),
lpush: vi.fn(),
};
}
function createMockPrisma(): MockPrisma {
return {
teamFeatures: {
findUnique: vi.fn(),
upsert: vi.fn(),
delete: vi.fn(),
},
team: {
findUnique: vi.fn(),
},
};
}
let mockRedis: IRedisService;
vi.mock("@calcom/features/di/containers/Redis", () => ({
getRedisService: () => mockRedis,
}));
describe("TeamFeatureRepository", () => {
let mockPrisma: MockPrisma;
let repository: TeamFeatureRepository;
beforeEach(() => {
mockRedis = createMockRedis();
mockPrisma = createMockPrisma();
repository = new TeamFeatureRepository(mockPrisma as unknown as PrismaClient);
vi.clearAllMocks();
});
describe("findByTeamIdAndFeatureId", () => {
it("should return cached team feature on cache hit", async () => {
const cachedFeature = {
teamId: 1,
featureId: "feature-1",
enabled: true,
assignedBy: "admin",
updatedAt: new Date("2024-01-01"),
};
vi.mocked(mockRedis.get).mockResolvedValue(cachedFeature);
const result = await repository.findByTeamIdAndFeatureId(1, "feature-1");
expect(result).toEqual(cachedFeature);
expect(mockRedis.get).toHaveBeenCalledWith("features:team:1:feature-1");
expect(mockPrisma.teamFeatures.findUnique).not.toHaveBeenCalled();
});
it("should fetch from database and cache on cache miss", async () => {
const dbFeature = {
teamId: 1,
featureId: "feature-1",
enabled: true,
assignedBy: "admin",
updatedAt: new Date("2024-01-01"),
};
vi.mocked(mockRedis.get).mockResolvedValue(null);
vi.mocked(mockPrisma.teamFeatures.findUnique).mockResolvedValue(dbFeature);
vi.mocked(mockRedis.set).mockResolvedValue("OK");
const result = await repository.findByTeamIdAndFeatureId(1, "feature-1");
expect(result).toEqual(dbFeature);
expect(mockPrisma.teamFeatures.findUnique).toHaveBeenCalledWith({
where: {
teamId_featureId: {
teamId: 1,
featureId: "feature-1",
},
},
});
expect(mockRedis.set).toHaveBeenCalled();
});
it("should return null when team feature not found", async () => {
vi.mocked(mockRedis.get).mockResolvedValue(null);
vi.mocked(mockPrisma.teamFeatures.findUnique).mockResolvedValue(null);
const result = await repository.findByTeamIdAndFeatureId(1, "non-existent");
expect(result).toBeNull();
expect(mockRedis.set).not.toHaveBeenCalled();
});
});
describe("findByTeamIdsAndFeatureIds", () => {
it("should return empty object when teamIds is empty", async () => {
const result = await repository.findByTeamIdsAndFeatureIds([], ["feature-1"]);
expect(result).toEqual({});
});
it("should return empty object when featureIds is empty", async () => {
const result = await repository.findByTeamIdsAndFeatureIds([1, 2], []);
expect(result).toEqual({});
});
it("should return features grouped by featureId and teamId", async () => {
const cachedFeature1 = {
teamId: 1,
featureId: "feature-1",
enabled: true,
assignedBy: "admin",
updatedAt: new Date("2024-01-01"),
};
const cachedFeature2 = {
teamId: 2,
featureId: "feature-1",
enabled: false,
assignedBy: "admin",
updatedAt: new Date("2024-01-01"),
};
vi.mocked(mockRedis.get).mockResolvedValueOnce(cachedFeature1).mockResolvedValueOnce(cachedFeature2);
const result = await repository.findByTeamIdsAndFeatureIds([1, 2], ["feature-1"]);
expect(result).toEqual({
"feature-1": {
1: cachedFeature1,
2: cachedFeature2,
},
});
});
});
describe("upsert", () => {
it("should upsert team feature and invalidate cache", async () => {
const upsertedFeature = {
teamId: 1,
featureId: "feature-1",
enabled: true,
assignedBy: "admin",
updatedAt: new Date("2024-01-01"),
};
vi.mocked(mockPrisma.teamFeatures.upsert).mockResolvedValue(upsertedFeature);
vi.mocked(mockRedis.del).mockResolvedValue(1);
const result = await repository.upsert(1, "feature-1", true, "admin");
expect(result).toEqual(upsertedFeature);
expect(mockPrisma.teamFeatures.upsert).toHaveBeenCalledWith({
where: {
teamId_featureId: {
teamId: 1,
featureId: "feature-1",
},
},
create: {
teamId: 1,
featureId: "feature-1",
enabled: true,
assignedBy: "admin",
},
update: {
enabled: true,
assignedBy: "admin",
},
});
expect(mockRedis.del).toHaveBeenCalledWith("features:team:1:feature-1");
});
});
describe("delete", () => {
it("should delete team feature and invalidate cache", async () => {
vi.mocked(mockPrisma.teamFeatures.delete).mockResolvedValue({
teamId: 1,
featureId: "feature-1",
enabled: true,
assignedBy: "admin",
updatedAt: new Date("2024-01-01"),
});
vi.mocked(mockRedis.del).mockResolvedValue(1);
await repository.delete(1, "feature-1");
expect(mockPrisma.teamFeatures.delete).toHaveBeenCalledWith({
where: {
teamId_featureId: {
teamId: 1,
featureId: "feature-1",
},
},
});
expect(mockRedis.del).toHaveBeenCalledWith("features:team:1:feature-1");
});
});
describe("findAutoOptInByTeamId", () => {
it("should return cached auto opt-in value on cache hit", async () => {
vi.mocked(mockRedis.get).mockResolvedValue(true);
const result = await repository.findAutoOptInByTeamId(1);
expect(result).toBe(true);
expect(mockRedis.get).toHaveBeenCalledWith("features:team:autoOptIn:1");
expect(mockPrisma.team.findUnique).not.toHaveBeenCalled();
});
it("should fetch from database and cache on cache miss", async () => {
vi.mocked(mockRedis.get).mockResolvedValue(null);
vi.mocked(mockPrisma.team.findUnique).mockResolvedValue({ id: 1, autoOptInFeatures: true });
vi.mocked(mockRedis.set).mockResolvedValue("OK");
const result = await repository.findAutoOptInByTeamId(1);
expect(result).toBe(true);
expect(mockPrisma.team.findUnique).toHaveBeenCalledWith({
where: { id: 1 },
select: { autoOptInFeatures: true },
});
expect(mockRedis.set).toHaveBeenCalled();
});
it("should return false when team not found", async () => {
vi.mocked(mockRedis.get).mockResolvedValue(null);
vi.mocked(mockPrisma.team.findUnique).mockResolvedValue(null);
const result = await repository.findAutoOptInByTeamId(1);
expect(result).toBe(false);
});
});
describe("findAutoOptInByTeamIds", () => {
it("should return empty object when teamIds is empty", async () => {
const result = await repository.findAutoOptInByTeamIds([]);
expect(result).toEqual({});
});
it("should return auto opt-in values for multiple teams", async () => {
vi.mocked(mockRedis.get).mockResolvedValueOnce(true).mockResolvedValueOnce(false);
const result = await repository.findAutoOptInByTeamIds([1, 2]);
expect(result).toEqual({
1: true,
2: false,
});
});
});
});
@@ -0,0 +1,63 @@
import type { ZodObject } from "zod";
import { z } from "zod";
const dateSchema: z.ZodDate = z.coerce.date();
const optionalDateSchema: z.ZodNullable<z.ZodDate> = z.coerce.date().nullable();
export const featureSchema: ZodObject<{
slug: z.ZodString;
enabled: z.ZodBoolean;
description: z.ZodNullable<z.ZodString>;
type: z.ZodNullable<z.ZodEnum<["RELEASE", "EXPERIMENT", "OPERATIONAL", "PERMISSION", "KILL_SWITCH"]>>;
stale: z.ZodNullable<z.ZodBoolean>;
lastUsedAt: z.ZodNullable<z.ZodDate>;
createdAt: z.ZodNullable<z.ZodDate>;
updatedAt: z.ZodNullable<z.ZodDate>;
updatedBy: z.ZodNullable<z.ZodNumber>;
}> = z.object({
slug: z.string(),
enabled: z.boolean(),
description: z.string().nullable(),
type: z.enum(["RELEASE", "EXPERIMENT", "OPERATIONAL", "PERMISSION", "KILL_SWITCH"]).nullable(),
stale: z.boolean().nullable(),
lastUsedAt: optionalDateSchema,
createdAt: optionalDateSchema,
updatedAt: optionalDateSchema,
updatedBy: z.number().nullable(),
});
export type CachedFeature = z.infer<typeof featureSchema>;
export const featureArraySchema = z.array(featureSchema);
export const appFlagsSchema = z.record(z.string(), z.boolean());
export type CachedAppFlags = z.infer<typeof appFlagsSchema>;
export const teamFeaturesMapSchema = z.record(z.string(), z.boolean());
export type CachedTeamFeaturesMap = z.infer<typeof teamFeaturesMapSchema>;
export const teamFeaturesSchema = z.object({
teamId: z.number(),
featureId: z.string(),
enabled: z.boolean(),
assignedBy: z.string(),
assignedAt: dateSchema,
updatedAt: dateSchema,
});
export type CachedTeamFeatures = z.infer<typeof teamFeaturesSchema>;
export const userFeaturesSchema = z.object({
userId: z.number(),
featureId: z.string(),
enabled: z.boolean(),
assignedBy: z.string(),
assignedAt: dateSchema,
updatedAt: dateSchema,
});
export type CachedUserFeatures = z.infer<typeof userFeaturesSchema>;
export const booleanSchema = z.boolean();