Skip to content

The open alternative to Salesforce, designed for AI.

feat(usage-limit) - rate-limit API requests from configured usage limits (#24709)

Etienne9961e1a13556
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index d67f939c789..2a0e10c675f 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -1792,6 +1792,7 @@ enum FeatureFlagKey {
IS_WORKFLOW_VERSION_IN_CORE_ENABLED
IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED
IS_WORKFLOW_DISPATCH_FROM_CORE_ENABLED
+ IS_API_RATE_LIMIT_V2_ENABLED
}
type WorkspaceUrls {
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index 1e3d31ad96e..9ec5f31c28f 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -1430,7 +1430,7 @@ export interface FeatureFlag {
__typename: 'FeatureFlag'
}
-export type FeatureFlagKey = 'IS_APP_CLAIMING_ENABLED' | 'IS_UNIQUE_INDEXES_ENABLED' | 'IS_JSON_FILTER_ENABLED' | 'IS_EMAIL_GROUP_ENABLED' | 'IS_JUNCTION_RELATIONS_ENABLED' | 'IS_LIST_VIEW_ENABLED' | 'IS_REST_METADATA_API_NEW_FORMAT_DIRECT' | 'IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED' | 'IS_WORKFLOW_VERSION_IN_CORE_ENABLED' | 'IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED' | 'IS_WORKFLOW_DISPATCH_FROM_CORE_ENABLED'
+export type FeatureFlagKey = 'IS_APP_CLAIMING_ENABLED' | 'IS_UNIQUE_INDEXES_ENABLED' | 'IS_JSON_FILTER_ENABLED' | 'IS_EMAIL_GROUP_ENABLED' | 'IS_JUNCTION_RELATIONS_ENABLED' | 'IS_LIST_VIEW_ENABLED' | 'IS_REST_METADATA_API_NEW_FORMAT_DIRECT' | 'IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED' | 'IS_WORKFLOW_VERSION_IN_CORE_ENABLED' | 'IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED' | 'IS_WORKFLOW_DISPATCH_FROM_CORE_ENABLED' | 'IS_API_RATE_LIMIT_V2_ENABLED'
export interface WorkspaceUrls {
customUrl?: Scalars['String']
@@ -10060,7 +10060,8 @@ export const enumFeatureFlagKey = {
IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED: 'IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED' as const,
IS_WORKFLOW_VERSION_IN_CORE_ENABLED: 'IS_WORKFLOW_VERSION_IN_CORE_ENABLED' as const,
IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED: 'IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED' as const,
- IS_WORKFLOW_DISPATCH_FROM_CORE_ENABLED: 'IS_WORKFLOW_DISPATCH_FROM_CORE_ENABLED' as const
+ IS_WORKFLOW_DISPATCH_FROM_CORE_ENABLED: 'IS_WORKFLOW_DISPATCH_FROM_CORE_ENABLED' as const,
+ IS_API_RATE_LIMIT_V2_ENABLED: 'IS_API_RATE_LIMIT_V2_ENABLED' as const
}
export const enumIdentityProviderType = {
diff --git a/packages/twenty-front/src/generated-admin/graphql.ts b/packages/twenty-front/src/generated-admin/graphql.ts
index 923e9cf0f7e..76477258a0f 100644
--- a/packages/twenty-front/src/generated-admin/graphql.ts
+++ b/packages/twenty-front/src/generated-admin/graphql.ts
@@ -392,6 +392,7 @@ export type FeatureFlag = {
};
export enum FeatureFlagKey {
+ IS_API_RATE_LIMIT_V2_ENABLED = 'IS_API_RATE_LIMIT_V2_ENABLED',
IS_APP_CLAIMING_ENABLED = 'IS_APP_CLAIMING_ENABLED',
IS_EMAIL_GROUP_ENABLED = 'IS_EMAIL_GROUP_ENABLED',
IS_JSON_FILTER_ENABLED = 'IS_JSON_FILTER_ENABLED',
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index 97794766efe..5634021f51e 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -1859,6 +1859,7 @@ export type FeatureFlag = {
};
export enum FeatureFlagKey {
+ IS_API_RATE_LIMIT_V2_ENABLED = 'IS_API_RATE_LIMIT_V2_ENABLED',
IS_APP_CLAIMING_ENABLED = 'IS_APP_CLAIMING_ENABLED',
IS_EMAIL_GROUP_ENABLED = 'IS_EMAIL_GROUP_ENABLED',
IS_JSON_FILTER_ENABLED = 'IS_JSON_FILTER_ENABLED',
diff --git a/packages/twenty-front/src/modules/apollo/services/apollo.factory.ts b/packages/twenty-front/src/modules/apollo/services/apollo.factory.ts
index 5f3fe8c6f00..e1c2d398acd 100644
--- a/packages/twenty-front/src/modules/apollo/services/apollo.factory.ts
+++ b/packages/twenty-front/src/modules/apollo/services/apollo.factory.ts
@@ -384,7 +384,9 @@ export class ApolloFactory implements ApolloManager {
case 'BAD_USER_INPUT':
case 'FORBIDDEN':
case 'CONFLICT':
- case 'METADATA_VALIDATION_FAILED': {
+ case 'METADATA_VALIDATION_FAILED':
+ case 'RATE_LIMITED':
+ case 'QUOTA_EXHAUSTED': {
return;
}
case 'USER_INPUT_ERROR': {
diff --git a/packages/twenty-server/src/engine/api/common/common-query-runners/common-base-query-runner.service.ts b/packages/twenty-server/src/engine/api/common/common-query-runners/common-base-query-runner.service.ts
index 4ed2c337242..12b78cee74b 100644
--- a/packages/twenty-server/src/engine/api/common/common-query-runners/common-base-query-runner.service.ts
+++ b/packages/twenty-server/src/engine/api/common/common-query-runners/common-base-query-runner.service.ts
@@ -1,7 +1,11 @@
import { Inject, Injectable } from '@nestjs/common';
import { type PermissionFlagType } from 'twenty-shared/constants';
-import { FieldMetadataType, type ObjectRecord } from 'twenty-shared/types';
+import {
+ FeatureFlagKey,
+ FieldMetadataType,
+ type ObjectRecord,
+} from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { type ObjectLiteral } from 'typeorm';
@@ -52,6 +56,11 @@ import { MetricsKeys } from 'src/engine/core-modules/metrics/types/metrics-keys.
import { ThrottlerException } from 'src/engine/core-modules/throttler/throttler.exception';
import { ThrottlerService } from 'src/engine/core-modules/throttler/throttler.service';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
+import { UsageLimitException } from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';
+import { UsageLimitSpeedService } from 'src/engine/core-modules/usage-limit/services/usage-limit-speed.service';
+import { type ExhaustedScope } from 'src/engine/core-modules/usage-limit/types/exhausted-scope.type';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
import { FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';
import { findFlatEntityByIdInFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps.util';
import { FlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/flat-field-metadata.type';
@@ -103,6 +112,8 @@ export abstract class CommonBaseQueryRunnerService<
@Inject()
protected readonly throttlerService: ThrottlerService;
@Inject()
+ protected readonly usageLimitSpeedService: UsageLimitSpeedService;
+ @Inject()
protected readonly twentyConfigService: TwentyConfigService;
@Inject()
protected readonly metricsService: MetricsService;
@@ -525,10 +536,75 @@ export abstract class CommonBaseQueryRunnerService<
}
private async throttleQueryExecution(authContext: WorkspaceAuthContext) {
+ const isApiRateLimitV2Enabled =
+ await this.featureFlagService.isFeatureEnabled(
+ FeatureFlagKey.IS_API_RATE_LIMIT_V2_ENABLED,
+ authContext.workspace.id,
+ );
+
+ if (isApiRateLimitV2Enabled) {
+ await this.consumeApiSpeedLimit(authContext);
+
+ return;
+ }
+
await this.throttleApiKeyQueryExecution(authContext);
await this.throttleApplicationQueryExecution(authContext);
}
+ private async consumeApiSpeedLimit(authContext: WorkspaceAuthContext) {
+ try {
+ await this.usageLimitSpeedService.consumeOrThrow({
+ resourceType: UsageResourceType.API,
+ authContext,
+ operationType: UsageOperationType.API_REQUEST,
+ });
+ } catch (error) {
+ if (
+ error instanceof UsageLimitException &&
+ isDefined(error.exhaustedScope) &&
+ error.exhaustedScope.isFallback
+ ) {
+ await this.incrementApiSpeedCeilingMetrics({
+ authContext,
+ exhaustedScope: error.exhaustedScope,
+ });
+ }
+
+ throw error;
+ }
+ }
+
+ private async incrementApiSpeedCeilingMetrics({
+ authContext,
+ exhaustedScope,
+ }: {
+ authContext: WorkspaceAuthContext;
+ exhaustedScope: ExhaustedScope;
+ }) {
+ if (exhaustedScope.spenderType === 'apiKey') {
+ await this.metricsService.incrementCounterForEvent({
+ key: MetricsKeys.CommonApiQueryRateLimited,
+ shouldStoreInCache: false,
+ });
+ }
+
+ if (
+ exhaustedScope.spenderType === 'application' &&
+ isApplicationAuthContext(authContext)
+ ) {
+ await this.metricsService.incrementCounterForEvent({
+ key: MetricsKeys.CommonApiApplicationQueryRateLimited,
+ shouldStoreInCache: false,
+ attributes: {
+ universal_identifier: authContext.application.universalIdentifier,
+ app_name: authContext.application.name,
+ source_type: authContext.application.sourceType,
+ },
+ });
+ }
+ }
+
private async throttleApplicationQueryExecution(
authContext: WorkspaceAuthContext,
) {
diff --git a/packages/twenty-server/src/engine/api/graphql/workspace-query-runner/utils/workspace-query-runner-graphql-api-exception-handler.util.ts b/packages/twenty-server/src/engine/api/graphql/workspace-query-runner/utils/workspace-query-runner-graphql-api-exception-handler.util.ts
index 75dd7d86f6f..622bb45031d 100644
--- a/packages/twenty-server/src/engine/api/graphql/workspace-query-runner/utils/workspace-query-runner-graphql-api-exception-handler.util.ts
+++ b/packages/twenty-server/src/engine/api/graphql/workspace-query-runner/utils/workspace-query-runner-graphql-api-exception-handler.util.ts
@@ -16,6 +16,8 @@ import { RecordTransformerException } from 'src/engine/core-modules/record-trans
import { recordTransformerGraphqlApiExceptionHandler } from 'src/engine/core-modules/record-transformer/utils/record-transformer-graphql-api-exception-handler.util';
import { ThrottlerException } from 'src/engine/core-modules/throttler/throttler.exception';
import { throttlerToGraphqlApiExceptionHandler } from 'src/engine/core-modules/throttler/utils/throttler-to-graphql-api-exception-handler.util';
+import { UsageLimitException } from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';
+import { usageLimitToGraphqlApiExceptionHandler } from 'src/engine/core-modules/usage-limit/utils/usage-limit-to-graphql-api-exception-handler.util';
import { PermissionsException } from 'src/engine/metadata-modules/permissions/permissions.exception';
import { permissionGraphqlApiExceptionHandler } from 'src/engine/metadata-modules/permissions/utils/permission-graphql-api-exception-handler.util';
import { TwentyOrmException } from 'src/engine/twenty-orm/exceptions/twenty-orm.exception';
@@ -47,6 +49,8 @@ export const workspaceQueryRunnerGraphqlApiExceptionHandler = (
return authGraphqlApiExceptionHandler(error);
case error instanceof ApiKeyException:
return apiKeyGraphqlApiExceptionHandler(error);
+ case error instanceof UsageLimitException:
+ return usageLimitToGraphqlApiExceptionHandler(error);
case error instanceof ThrottlerException:
return throttlerToGraphqlApiExceptionHandler(error);
case error instanceof GraphqlDirectExecutionException:
diff --git a/packages/twenty-server/src/engine/api/rest/rest-api-exception.filter.ts b/packages/twenty-server/src/engine/api/rest/rest-api-exception.filter.ts
index 0d932fc69d4..22221bf7955 100644
--- a/packages/twenty-server/src/engine/api/rest/rest-api-exception.filter.ts
+++ b/packages/twenty-server/src/engine/api/rest/rest-api-exception.filter.ts
@@ -8,6 +8,7 @@ import {
import { type Response } from 'express';
import { HttpExceptionHandlerService } from 'src/engine/core-modules/exception-handler/http-exception-handler.service';
+import { hasRestResponse } from 'src/engine/core-modules/exception-handler/utils/has-rest-response.util';
@Catch()
export class RestApiExceptionFilter implements ExceptionFilter {
@@ -19,6 +20,10 @@ export class RestApiExceptionFilter implements ExceptionFilter {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
+ if (hasRestResponse(exception)) {
+ response.set(exception.getResponseHeaders());
+ }
+
const statusCode =
exception instanceof HttpException ? exception.getStatus() : 400; // should actually default to 500 but we dont have input validation yet and dont want to be flooded with errors from input https://github.com/twentyhq/core-team-issues/issues/1027
diff --git a/packages/twenty-server/src/engine/api/rest/utils/workspace-query-runner-rest-api-exception-handler.util.ts b/packages/twenty-server/src/engine/api/rest/utils/workspace-query-runner-rest-api-exception-handler.util.ts
index b4c29d35d72..c1ba010f466 100644
--- a/packages/twenty-server/src/engine/api/rest/utils/workspace-query-runner-rest-api-exception-handler.util.ts
+++ b/packages/twenty-server/src/engine/api/rest/utils/workspace-query-runner-rest-api-exception-handler.util.ts
@@ -7,6 +7,8 @@ import { commonQueryRunnerToRestApiExceptionHandler } from 'src/engine/api/commo
import { RestInputRequestParserException } from 'src/engine/api/rest/input-request-parsers/rest-input-request-parser.exception';
import { ThrottlerException } from 'src/engine/core-modules/throttler/throttler.exception';
import { throttlerToRestApiExceptionHandler } from 'src/engine/core-modules/throttler/utils/throttler-to-rest-api-exception-handler.util';
+import { UsageLimitException } from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';
+import { usageLimitToRestApiExceptionHandler } from 'src/engine/core-modules/usage-limit/utils/usage-limit-to-rest-api-exception-handler.util';
import { TwentyOrmException } from 'src/engine/twenty-orm/exceptions/twenty-orm.exception';
import { isTwentyOrmUserInputError } from 'src/engine/twenty-orm/utils/is-twenty-orm-user-input-error.util';
@@ -22,6 +24,8 @@ export const workspaceQueryRunnerRestApiExceptionHandler = (
return commonQueryRunnerToRestApiExceptionHandler(error);
case error instanceof RestInputRequestParserException:
throw new BadRequestException(error.message);
+ case error instanceof UsageLimitException:
+ return usageLimitToRestApiExceptionHandler(error);
case error instanceof ThrottlerException:
return throttlerToRestApiExceptionHandler(error);
case error instanceof TwentyOrmException &&
diff --git a/packages/twenty-server/src/engine/core-modules/cache-storage/exceptions/cache-storage.exception.ts b/packages/twenty-server/src/engine/core-modules/cache-storage/exceptions/cache-storage.exception.ts
new file mode 100644
index 00000000000..83a5e3179fe
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/cache-storage/exceptions/cache-storage.exception.ts
@@ -0,0 +1,36 @@
+import { type MessageDescriptor } from '@lingui/core';
+import { msg } from '@lingui/core/macro';
+import { assertUnreachable } from 'twenty-shared/utils';
+
+import { CustomException } from 'src/utils/custom-exception';
+
+export enum CacheStorageExceptionCode {
+ SCRIPT_EXECUTION_FAILED = 'SCRIPT_EXECUTION_FAILED',
+ REDIS_CACHE_REQUIRED = 'REDIS_CACHE_REQUIRED',
+}
+
+const getCacheStorageExceptionUserFriendlyMessage = (
+ code: CacheStorageExceptionCode,
+) => {
+ switch (code) {
+ case CacheStorageExceptionCode.SCRIPT_EXECUTION_FAILED:
+ case CacheStorageExceptionCode.REDIS_CACHE_REQUIRED:
+ return msg`An unexpected error occurred.`;
+ default:
+ assertUnreachable(code);
+ }
+};
+
+export class CacheStorageException extends CustomException<CacheStorageExceptionCode> {
+ constructor(
+ message: string,
+ code: CacheStorageExceptionCode,
+ { userFriendlyMessage }: { userFriendlyMessage?: MessageDescriptor } = {},
+ ) {
+ super(message, code, {
+ userFriendlyMessage:
+ userFriendlyMessage ??
+ getCacheStorageExceptionUserFriendlyMessage(code),
+ });
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/cache-storage/services/cache-storage.service.ts b/packages/twenty-server/src/engine/core-modules/cache-storage/services/cache-storage.service.ts
index 4c115bd2881..48f8ee0f9c5 100644
--- a/packages/twenty-server/src/engine/core-modules/cache-storage/services/cache-storage.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/cache-storage/services/cache-storage.service.ts
@@ -4,6 +4,11 @@ import { Inject, Injectable } from '@nestjs/common';
import { type Milliseconds } from 'cache-manager';
import { type RedisCache } from 'cache-manager-redis-yet';
+import {
+ CacheStorageException,
+ CacheStorageExceptionCode,
+} from 'src/engine/core-modules/cache-storage/exceptions/cache-storage.exception';
+import { type CacheScript } from 'src/engine/core-modules/cache-storage/types/cache-script.type';
import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';
@Injectable()
@@ -383,6 +388,35 @@ end`;
}) as Promise<number>;
}
+ async runScript<TResult>({
+ script,
+ keys,
+ args,
+ }: {
+ script: CacheScript;
+ keys: string[];
+ args: string[];
+ }): Promise<TResult> {
+ if (!this.isRedisCache(this.cache)) {
+ throw new CacheStorageException(
+ 'runScript is only supported with Redis cache',
+ CacheStorageExceptionCode.REDIS_CACHE_REQUIRED,
+ );
+ }
+
+ try {
+ return (await this.cache.store.client.eval(script.source, {
+ keys: keys.map((key) => this.getKey(key)),
+ arguments: args,
+ })) as TResult;
+ } catch (error) {
+ throw new CacheStorageException(
+ `Cache script "${script.name}" failed: ${error instanceof Error ? error.message : 'unknown error'}`,
+ CacheStorageExceptionCode.SCRIPT_EXECUTION_FAILED,
+ );
+ }
+ }
+
async hashSetWithExpire({
key,
field,
diff --git a/packages/twenty-server/src/engine/core-modules/cache-storage/types/cache-script.type.ts b/packages/twenty-server/src/engine/core-modules/cache-storage/types/cache-script.type.ts
new file mode 100644
index 00000000000..874ecad9d6a
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/cache-storage/types/cache-script.type.ts
@@ -0,0 +1,4 @@
+export type CacheScript = {
+ name: string;
+ source: string;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum.ts b/packages/twenty-server/src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum.ts
index 587c89eff10..eb5de265d35 100644
--- a/packages/twenty-server/src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum.ts
+++ b/packages/twenty-server/src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum.ts
@@ -12,6 +12,7 @@ export enum CacheStorageNamespace {
EngineMetrics = 'engine:metrics',
EngineSubscriptions = 'engine:subscriptions',
EngineBillingUsage = 'engine:billing-usage',
+ EngineUsageLimit = 'engine:usage-limit',
EngineOnboardingInviteSuggestions = 'engine:onboarding-invite-suggestions',
IntegrationTests = 'integration-tests',
}
diff --git a/packages/twenty-server/src/engine/core-modules/exception-handler/http-exception-handler.service.ts b/packages/twenty-server/src/engine/core-modules/exception-handler/http-exception-handler.service.ts
index 602d4f7b0d0..d3a90a453d8 100644
--- a/packages/twenty-server/src/engine/core-modules/exception-handler/http-exception-handler.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/exception-handler/http-exception-handler.service.ts
@@ -18,6 +18,7 @@ import { CustomError } from 'twenty-shared/utils';
import { PostgresException } from 'src/engine/api/graphql/workspace-query-runner/utils/postgres-exception';
import { ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';
+import { hasRestResponse } from 'src/engine/core-modules/exception-handler/utils/has-rest-response.util';
import { TwentyOrmException } from 'src/engine/twenty-orm/exceptions/twenty-orm.exception';
import { isTwentyOrmUserInputError } from 'src/engine/twenty-orm/utils/is-twenty-orm-user-input-error.util';
import { handleException } from 'src/engine/utils/global-exception-handler.util';
@@ -116,6 +117,10 @@ export class HttpExceptionHandlerService {
shouldBeCapturedBySentry,
});
+ if (hasRestResponse(exception)) {
+ return response.status(statusCode).send(exception.getResponseBody());
+ }
+
return response.status(statusCode).send({
statusCode,
error: exception.name ?? getErrorNameFromStatusCode(statusCode),
diff --git a/packages/twenty-server/src/engine/core-modules/exception-handler/types/http-exception-with-rest-response.type.ts b/packages/twenty-server/src/engine/core-modules/exception-handler/types/http-exception-with-rest-response.type.ts
new file mode 100644
index 00000000000..daa43d2a18f
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/exception-handler/types/http-exception-with-rest-response.type.ts
@@ -0,0 +1,4 @@
+export type HttpExceptionWithRestResponse = {
+ getResponseHeaders: () => Record<string, string>;
+ getResponseBody: () => Record<string, unknown>;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/exception-handler/utils/has-rest-response.util.ts b/packages/twenty-server/src/engine/core-modules/exception-handler/utils/has-rest-response.util.ts
new file mode 100644
index 00000000000..254c58a26d5
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/exception-handler/utils/has-rest-response.util.ts
@@ -0,0 +1,12 @@
+import { isFunction, isObject } from '@sniptt/guards';
+
+import { type HttpExceptionWithRestResponse } from 'src/engine/core-modules/exception-handler/types/http-exception-with-rest-response.type';
+
+export const hasRestResponse = (
+ exception: unknown,
+): exception is HttpExceptionWithRestResponse =>
+ isObject(exception) &&
+ 'getResponseHeaders' in exception &&
+ isFunction(exception.getResponseHeaders) &&
+ 'getResponseBody' in exception &&
+ isFunction(exception.getResponseBody);
diff --git a/packages/twenty-server/src/engine/core-modules/graphql/utils/graphql-errors.util.ts b/packages/twenty-server/src/engine/core-modules/graphql/utils/graphql-errors.util.ts
index e5115a3ab7e..b908f124d70 100644
--- a/packages/twenty-server/src/engine/core-modules/graphql/utils/graphql-errors.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/graphql/utils/graphql-errors.util.ts
@@ -33,6 +33,8 @@ export enum ErrorCode {
INTERNAL_SERVER_ERROR = 'INTERNAL_SERVER_ERROR',
METADATA_VALIDATION_FAILED = 'METADATA_VALIDATION_FAILED',
APPLICATION_INSTALLATION_FAILED = 'APPLICATION_INSTALLATION_FAILED',
+ RATE_LIMITED = 'RATE_LIMITED',
+ QUOTA_EXHAUSTED = 'QUOTA_EXHAUSTED',
}
type RestrictedGraphQLErrorExtensions = {
diff --git a/packages/twenty-server/src/engine/core-modules/twenty-config/types/numeric-config-variable-key.type.ts b/packages/twenty-server/src/engine/core-modules/twenty-config/types/numeric-config-variable-key.type.ts
new file mode 100644
index 00000000000..e894257548d
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/twenty-config/types/numeric-config-variable-key.type.ts
@@ -0,0 +1,7 @@
+import { type ConfigVariables } from 'src/engine/core-modules/twenty-config/config-variables';
+
+export type NumericConfigVariableKey = {
+ [Key in keyof ConfigVariables]-?: ConfigVariables[Key] extends number
+ ? Key
+ : never;
+}[keyof ConfigVariables];
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/spender-type-specificity.constant.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/spender-type-specificity.constant.ts
new file mode 100644
index 00000000000..319e696c22c
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/spender-type-specificity.constant.ts
@@ -0,0 +1,11 @@
+import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
+
+export const SPENDER_TYPE_SPECIFICITY: Record<SpenderType, number> = {
+ apiKey: 0,
+ userWorkspace: 1,
+ agent: 2,
+ workflow: 3,
+ logicFunction: 4,
+ application: 5,
+ workspace: 6,
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/try-consume-token-buckets-script.constant.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/try-consume-token-buckets-script.constant.ts
new file mode 100644
index 00000000000..d0f6499853d
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/try-consume-token-buckets-script.constant.ts
@@ -0,0 +1,68 @@
+import { type CacheScript } from 'src/engine/core-modules/cache-storage/types/cache-script.type';
+
+export const TRY_CONSUME_TOKEN_BUCKETS_SCRIPT: CacheScript = {
+ name: 'usage-limit:try-consume-token-buckets',
+ source: `
+local cost = tonumber(ARGV[1])
+local buckets = cjson.decode(ARGV[2])
+
+if #buckets ~= #KEYS then
+ return redis.error_reply(
+ 'try-consume-token-buckets: ' .. #KEYS .. ' keys but ' .. #buckets .. ' bucket configs'
+ )
+end
+
+local now = redis.call('TIME')
+local nowMs = tonumber(now[1]) * 1000 + math.floor(tonumber(now[2]) / 1000)
+local available = {}
+local exhaustedIndex = 0
+local retryAfterMs = 0
+
+for i = 1, #KEYS do
+ local bucket = buckets[i]
+ local state = redis.call('HMGET', KEYS[i], 't', 'ts')
+ local tokens = tonumber(state[1])
+ local lastRefillAt = tonumber(state[2])
+
+ if tokens == nil or lastRefillAt == nil then
+ tokens = bucket.burst
+ lastRefillAt = nowMs
+ end
+
+ local elapsed = nowMs - lastRefillAt
+ if elapsed < 0 then elapsed = 0 end
+
+ local refilled = tokens + (elapsed * bucket.refill / bucket.windowMs)
+ if refilled > bucket.burst then refilled = bucket.burst end
+ available[i] = refilled
+
+ if refilled < cost then
+ local bucketRetryAfterMs = math.ceil((cost - refilled) * bucket.windowMs / bucket.refill)
+
+ -- Buckets arrive narrowest first, so the first exhausted one names the
+ -- scope, while the caller has to wait for the slowest of them to refill.
+ if exhaustedIndex == 0 then
+ exhaustedIndex = i
+ end
+
+ if bucketRetryAfterMs > retryAfterMs then
+ retryAfterMs = bucketRetryAfterMs
+ end
+ end
+end
+
+if exhaustedIndex > 0 then
+ return { 0, exhaustedIndex, retryAfterMs }
+end
+
+for i = 1, #KEYS do
+ local bucket = buckets[i]
+ redis.call('HSET', KEYS[i], 't', tostring(available[i] - cost), 'ts', tostring(nowMs))
+ -- Never expire before an empty bucket would have refilled, or the key
+ -- vanishing hands back a full burst the elapsed time had not yet earned.
+ redis.call('PEXPIRE', KEYS[i], math.ceil(bucket.burst / bucket.refill * bucket.windowMs))
+end
+
+return { 1, 0, 0 }
+`,
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-limit-definitions.constant.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-limit-definitions.constant.ts
index f57d0473427..328776c2cfb 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-limit-definitions.constant.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-limit-definitions.constant.ts
@@ -10,25 +10,28 @@ export const USAGE_LIMIT_DEFINITIONS: Record<
[UsageResourceType.API]: {
speed: {
allowedOperationTypes: [UsageOperationType.API_REQUEST],
- allowedSpenderTypes: ['workspace', 'apiKey', 'application'],
+ allowedSpenderTypes: ['apiKey', 'application'],
fallbacks: [
{
- spenderType: 'workspace',
+ spenderType: 'apiKey',
counterScope: 'perWorkspace',
- maxTokensConfigVariable: 'API_RATE_LIMITING_SHORT_LIMIT',
+ limitValueConfigVariable: 'API_RATE_LIMITING_SHORT_LIMIT',
windowMsConfigVariable: 'API_RATE_LIMITING_SHORT_TTL_IN_MS',
+ isOverridable: true,
},
{
- spenderType: 'workspace',
+ spenderType: 'apiKey',
counterScope: 'perWorkspace',
- maxTokensConfigVariable: 'API_RATE_LIMITING_LONG_LIMIT',
+ limitValueConfigVariable: 'API_RATE_LIMITING_LONG_LIMIT',
windowMsConfigVariable: 'API_RATE_LIMITING_LONG_TTL_IN_MS',
+ isOverridable: true,
},
{
spenderType: 'application',
counterScope: 'crossWorkspace',
- maxTokensConfigVariable: 'APPLICATION_API_RATE_LIMITING_LIMIT',
+ limitValueConfigVariable: 'APPLICATION_API_RATE_LIMITING_LIMIT',
windowMsConfigVariable: 'APPLICATION_API_RATE_LIMITING_TTL_IN_MS',
+ isOverridable: false,
},
],
},
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/exceptions/usage-limit-http.exception.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/exceptions/usage-limit-http.exception.ts
new file mode 100644
index 00000000000..ee0262df33b
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/exceptions/usage-limit-http.exception.ts
@@ -0,0 +1,25 @@
+import { HttpException, HttpStatus } from '@nestjs/common';
+
+import { type HttpExceptionWithRestResponse } from 'src/engine/core-modules/exception-handler/types/http-exception-with-rest-response.type';
+import { type UsageLimitRestResponseBody } from 'src/engine/core-modules/usage-limit/types/usage-limit-rest-response-body.type';
+
+export class UsageLimitHttpException
+ extends HttpException
+ implements HttpExceptionWithRestResponse
+{
+ constructor(
+ private readonly responseBody: UsageLimitRestResponseBody,
+ private readonly responseHeaders: Record<string, string>,
+ ) {
+ super(responseBody, HttpStatus.TOO_MANY_REQUESTS);
+ this.message = responseBody.messages[0];
+ }
+
+ getResponseBody(): UsageLimitRestResponseBody {
+ return this.responseBody;
+ }
+
+ getResponseHeaders(): Record<string, string> {
+ return this.responseHeaders;
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/filters/__tests__/usage-limit-graphql-api-exception.filter.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/filters/__tests__/usage-limit-graphql-api-exception.filter.spec.ts
index fdfd191bf1d..bcd6e100874 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/filters/__tests__/usage-limit-graphql-api-exception.filter.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/filters/__tests__/usage-limit-graphql-api-exception.filter.spec.ts
@@ -35,7 +35,7 @@ describe('UsageLimitGraphqlApiExceptionFilter', () => {
);
});
- it('surfaces an exhausted quota as forbidden', () => {
+ it('surfaces an exhausted quota through the shared enforcement mapping', () => {
const graphqlError = catchAsGraphQLError(
new UsageLimitException(
'Quota exhausted',
@@ -43,6 +43,6 @@ describe('UsageLimitGraphqlApiExceptionFilter', () => {
),
);
- expect(graphqlError.extensions.code).toBe(ErrorCode.FORBIDDEN);
+ expect(graphqlError.extensions.code).toBe(ErrorCode.QUOTA_EXHAUSTED);
});
});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/filters/usage-limit-graphql-api-exception.filter.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/filters/usage-limit-graphql-api-exception.filter.ts
index da3456d1797..a716a52744d 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/filters/usage-limit-graphql-api-exception.filter.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/filters/usage-limit-graphql-api-exception.filter.ts
@@ -2,24 +2,22 @@ import { Catch, type ExceptionFilter } from '@nestjs/common';
import { assertUnreachable } from 'twenty-shared/utils';
-import {
- ForbiddenError,
- UserInputError,
-} from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
+import { UserInputError } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
import {
UsageLimitException,
UsageLimitExceptionCode,
} from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';
+import { usageLimitToGraphqlApiExceptionHandler } from 'src/engine/core-modules/usage-limit/utils/usage-limit-to-graphql-api-exception-handler.util';
@Catch(UsageLimitException)
export class UsageLimitGraphqlApiExceptionFilter implements ExceptionFilter {
catch(exception: UsageLimitException) {
switch (exception.code) {
case UsageLimitExceptionCode.LIMIT_RULE_INVALID:
- case UsageLimitExceptionCode.RATE_LIMITED:
throw new UserInputError(exception);
+ case UsageLimitExceptionCode.RATE_LIMITED:
case UsageLimitExceptionCode.QUOTA_EXHAUSTED:
- throw new ForbiddenError(exception);
+ return usageLimitToGraphqlApiExceptionHandler(exception);
default:
assertUnreachable(exception.code);
}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/__tests__/usage-limit-speed.service.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/__tests__/usage-limit-speed.service.spec.ts
new file mode 100644
index 00000000000..5c743359d8d
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/__tests__/usage-limit-speed.service.spec.ts
@@ -0,0 +1,103 @@
+import { Test, type TestingModule } from '@nestjs/testing';
+
+import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
+import {
+ CacheStorageException,
+ CacheStorageExceptionCode,
+} from 'src/engine/core-modules/cache-storage/exceptions/cache-storage.exception';
+import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';
+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
+import { UsageLimitSpeedService } from 'src/engine/core-modules/usage-limit/services/usage-limit-speed.service';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+import {
+ WorkspaceCacheException,
+ WorkspaceCacheExceptionCode,
+} from 'src/engine/workspace-cache/exceptions/workspace-cache.exception';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+
+const apiKeyContext = {
+ type: 'apiKey',
+ workspace: { id: 'workspace-1' },
+ apiKey: { id: 'key-1' },
+} as WorkspaceAuthContext;
+
+describe('UsageLimitSpeedService', () => {
+ let service: UsageLimitSpeedService;
+
+ const cacheStorage = {
+ runScript: jest.fn().mockResolvedValue([1, 0, 0]),
+ };
+
+ const workspaceCacheService = {
+ getOrRecompute: jest
+ .fn()
+ .mockResolvedValue({ usageLimitRules: { byResourceType: {} } }),
+ };
+
+ const twentyConfigService = {
+ get: jest.fn((key: string) => (key.endsWith('_IN_MS') ? 60_000 : 100)),
+ };
+
+ const consume = () =>
+ service.consumeOrThrow({
+ resourceType: UsageResourceType.API,
+ authContext: apiKeyContext,
+ operationType: UsageOperationType.API_REQUEST,
+ });
+
+ beforeEach(async () => {
+ jest.clearAllMocks();
+
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [
+ UsageLimitSpeedService,
+ {
+ provide: CacheStorageNamespace.EngineUsageLimit,
+ useValue: cacheStorage,
+ },
+ { provide: WorkspaceCacheService, useValue: workspaceCacheService },
+ { provide: TwentyConfigService, useValue: twentyConfigService },
+ ],
+ }).compile();
+
+ service = module.get<UsageLimitSpeedService>(UsageLimitSpeedService);
+ });
+
+ it('admits the request when the rules cannot be read from storage', async () => {
+ workspaceCacheService.getOrRecompute.mockRejectedValueOnce(
+ new Error('Socket closed unexpectedly'),
+ );
+
+ await expect(consume()).resolves.toBeUndefined();
+ expect(cacheStorage.runScript).not.toHaveBeenCalled();
+ });
+
+ it('surfaces a misuse of the cache api instead of degrading', async () => {
+ workspaceCacheService.getOrRecompute.mockRejectedValueOnce(
+ new WorkspaceCacheException(
+ 'Invalid parameters',
+ WorkspaceCacheExceptionCode.INVALID_PARAMETERS,
+ ),
+ );
+
+ await expect(consume()).rejects.toThrow(WorkspaceCacheException);
+ });
+
+ it('admits the request when the counters cannot be consumed', async () => {
+ cacheStorage.runScript.mockRejectedValueOnce(
+ new CacheStorageException(
+ 'Script execution failed',
+ CacheStorageExceptionCode.SCRIPT_EXECUTION_FAILED,
+ ),
+ );
+
+ await expect(consume()).resolves.toBeUndefined();
+ });
+
+ it('denies the request when a bucket is exhausted', async () => {
+ cacheStorage.runScript.mockResolvedValueOnce([0, 1, 1500]);
+
+ await expect(consume()).rejects.toThrow(/Rate limit exceeded/);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-speed.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-speed.service.ts
new file mode 100644
index 00000000000..c37d92bd5fd
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-speed.service.ts
@@ -0,0 +1,225 @@
+import { Injectable, Logger } from '@nestjs/common';
+
+import { isDefined } from 'twenty-shared/utils';
+
+import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
+import { InjectCacheStorage } from 'src/engine/core-modules/cache-storage/decorators/cache-storage.decorator';
+import { CacheStorageException } from 'src/engine/core-modules/cache-storage/exceptions/cache-storage.exception';
+import { CacheStorageService } from 'src/engine/core-modules/cache-storage/services/cache-storage.service';
+import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';
+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
+import { TRY_CONSUME_TOKEN_BUCKETS_SCRIPT } from 'src/engine/core-modules/usage-limit/constants/try-consume-token-buckets-script.constant';
+import {
+ UsageLimitException,
+ UsageLimitExceptionCode,
+} from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';
+import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
+import { type SpeedBucketOutcome } from 'src/engine/core-modules/usage-limit/types/speed-bucket-outcome.type';
+import { type SpeedBucketRequest } from 'src/engine/core-modules/usage-limit/types/speed-bucket-request.type';
+import { type UsageLimitRules } from 'src/engine/core-modules/usage-limit/types/usage-limit-rules.type';
+import { buildSpeedBuckets } from 'src/engine/core-modules/usage-limit/utils/build-speed-buckets.util';
+import { findUsageLimitDefinition } from 'src/engine/core-modules/usage-limit/utils/find-usage-limit-definition.util';
+import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { type UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+import { WorkspaceCacheException } from 'src/engine/workspace-cache/exceptions/workspace-cache.exception';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+
+const ADMITTED: SpeedBucketOutcome = { admitted: true };
+
+@Injectable()
+export class UsageLimitSpeedService {
+ private readonly logger = new Logger(UsageLimitSpeedService.name);
+
+ constructor(
+ @InjectCacheStorage(CacheStorageNamespace.EngineUsageLimit)
+ private readonly cacheStorage: CacheStorageService,
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ private readonly twentyConfigService: TwentyConfigService,
+ ) {}
+
+ async consumeOrThrow({
+ resourceType,
+ authContext,
+ operationType,
+ cost = 1,
+ }: {
+ resourceType: UsageResourceType;
+ authContext: WorkspaceAuthContext;
+ operationType: UsageOperationType;
+ cost?: number;
+ }): Promise<void> {
+ const outcome = await this.consumeAdmittingOnFailure({
+ resourceType,
+ authContext,
+ operationType,
+ cost,
+ });
+
+ if (outcome.admitted) {
+ return;
+ }
+
+ throw new UsageLimitException(
+ `Rate limit exceeded for ${outcome.exhausted.spenderType}: ${outcome.exhausted.refillPerWindow} requests per ${outcome.exhausted.windowMs / 1000}s.`,
+ UsageLimitExceptionCode.RATE_LIMITED,
+ {
+ exhaustedScope: {
+ resourceType,
+ limitKind: 'speed',
+ spenderType: outcome.exhausted.spenderType,
+ spenderId: outcome.exhausted.spenderId,
+ limitValue: outcome.exhausted.refillPerWindow,
+ remaining: 0,
+ windowSeconds: Math.ceil(outcome.exhausted.windowMs / 1000),
+ retryAfterMs: outcome.retryAfterMs,
+ isFallback: outcome.exhausted.isFallback,
+ },
+ },
+ );
+ }
+
+ private async consumeAdmittingOnFailure({
+ resourceType,
+ authContext,
+ operationType,
+ cost,
+ }: {
+ resourceType: UsageResourceType;
+ authContext: WorkspaceAuthContext;
+ operationType: UsageOperationType;
+ cost: number;
+ }): Promise<SpeedBucketOutcome> {
+ const buckets = await this.buildBuckets({
+ resourceType,
+ authContext,
+ operationType,
+ });
+
+ if (buckets.length === 0) {
+ return ADMITTED;
+ }
+
+ try {
+ return await this.consumeTokens({ buckets, cost });
+ } catch (error) {
+ if (!(error instanceof CacheStorageException)) {
+ throw error;
+ }
+
+ this.logger.error(`Usage limit enforcement degraded: ${error.message}`);
+
+ return ADMITTED;
+ }
+ }
+
+ private async consumeTokens({
+ buckets,
+ cost,
+ }: {
+ buckets: SpeedBucketRequest[];
+ cost: number;
+ }): Promise<SpeedBucketOutcome> {
+ const bucketConfigs = buckets.map((bucket) => ({
+ burst: bucket.burst,
+ refill: bucket.refillPerWindow,
+ windowMs: bucket.windowMs,
+ }));
+
+ const [admitted, failedIndex, retryAfterMs] =
+ await this.cacheStorage.runScript<number[]>({
+ script: TRY_CONSUME_TOKEN_BUCKETS_SCRIPT,
+ keys: buckets.map((bucket) => bucket.key),
+ args: [String(cost), JSON.stringify(bucketConfigs)],
+ });
+
+ if (admitted === 1) {
+ return ADMITTED;
+ }
+
+ const exhausted = buckets[failedIndex - 1];
+
+ if (!isDefined(exhausted)) {
+ this.logger.warn(
+ `try-consume-token-buckets returned an out-of-range index ${failedIndex}`,
+ );
+
+ return ADMITTED;
+ }
+
+ return { admitted: false, exhausted, retryAfterMs };
+ }
+
+ private async buildBuckets({
+ resourceType,
+ authContext,
+ operationType,
+ }: {
+ resourceType: UsageResourceType;
+ authContext: WorkspaceAuthContext;
+ operationType: UsageOperationType;
+ }): Promise<SpeedBucketRequest[]> {
+ const definition = findUsageLimitDefinition({
+ resourceType,
+ limitKind: 'speed',
+ });
+
+ if (!isDefined(definition)) {
+ return [];
+ }
+
+ const rules = await this.findRulesAdmittingOnFailure({
+ workspaceId: authContext.workspace.id,
+ resourceType,
+ });
+
+ if (!isDefined(rules)) {
+ return [];
+ }
+
+ return buildSpeedBuckets({
+ defaultUsageLimitFallbacks: definition.fallbacks.map((fallback) => ({
+ spenderType: fallback.spenderType,
+ counterScope: fallback.counterScope,
+ isOverridable: fallback.isOverridable,
+ maxTokens: this.twentyConfigService.get(
+ fallback.limitValueConfigVariable,
+ ),
+ windowMs: this.twentyConfigService.get(fallback.windowMsConfigVariable),
+ })),
+ rules,
+ authContext,
+ resourceType,
+ operationType,
+ });
+ }
+
+ private async findRulesAdmittingOnFailure({
+ workspaceId,
+ resourceType,
+ }: {
+ workspaceId: string;
+ resourceType: UsageResourceType;
+ }): Promise<FlatUsageLimit[] | null> {
+ let usageLimitRules: UsageLimitRules;
+
+ try {
+ ({ usageLimitRules } = await this.workspaceCacheService.getOrRecompute(
+ workspaceId,
+ ['usageLimitRules'],
+ ));
+ } catch (error) {
+ if (error instanceof WorkspaceCacheException) {
+ throw error;
+ }
+
+ this.logger.error(
+ 'Usage limit rules unavailable, enforcement degraded',
+ error,
+ );
+
+ return null;
+ }
+
+ return usageLimitRules.byResourceType[resourceType] ?? [];
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/counter-scope.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/counter-scope.type.ts
new file mode 100644
index 00000000000..6bcf9c6bb84
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/counter-scope.type.ts
@@ -0,0 +1 @@
+export type CounterScope = 'perWorkspace' | 'crossWorkspace';
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/default-usage-limit-fallback.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/default-usage-limit-fallback.type.ts
new file mode 100644
index 00000000000..0deef6f2358
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/default-usage-limit-fallback.type.ts
@@ -0,0 +1,9 @@
+import { type UsageLimitFallback } from 'src/engine/core-modules/usage-limit/types/usage-limit-fallback.type';
+
+export type DefaultUsageLimitFallback = Pick<
+ UsageLimitFallback,
+ 'spenderType' | 'counterScope' | 'isOverridable'
+> & {
+ maxTokens: number;
+ windowMs: number;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/exhausted-scope.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/exhausted-scope.type.ts
index 75202e4e03a..2de44606eb1 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/exhausted-scope.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/exhausted-scope.type.ts
@@ -11,4 +11,5 @@ export type ExhaustedScope = {
remaining: number;
windowSeconds: number;
retryAfterMs: number;
+ isFallback: boolean;
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/speed-bucket-outcome.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/speed-bucket-outcome.type.ts
new file mode 100644
index 00000000000..86f0e9c459a
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/speed-bucket-outcome.type.ts
@@ -0,0 +1,9 @@
+import { type SpeedBucketRequest } from 'src/engine/core-modules/usage-limit/types/speed-bucket-request.type';
+
+export type SpeedBucketOutcome =
+ | { admitted: true }
+ | {
+ admitted: false;
+ exhausted: SpeedBucketRequest;
+ retryAfterMs: number;
+ };
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/speed-bucket-request.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/speed-bucket-request.type.ts
new file mode 100644
index 00000000000..9412d6f4bff
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/speed-bucket-request.type.ts
@@ -0,0 +1,11 @@
+import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
+
+export type SpeedBucketRequest = {
+ key: string;
+ burst: number;
+ refillPerWindow: number;
+ windowMs: number;
+ spenderType: SpenderType;
+ spenderId: string | null;
+ isFallback: boolean;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/spender.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/spender.type.ts
new file mode 100644
index 00000000000..e28427f7141
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/spender.type.ts
@@ -0,0 +1,6 @@
+import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
+
+export type Spender = {
+ spenderType: SpenderType;
+ spenderId: string;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-fallback.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-fallback.type.ts
index a4845b68028..42b6c601a75 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-fallback.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-fallback.type.ts
@@ -1,9 +1,11 @@
-import { type ConfigVariables } from 'src/engine/core-modules/twenty-config/config-variables';
+import { type NumericConfigVariableKey } from 'src/engine/core-modules/twenty-config/types/numeric-config-variable-key.type';
+import { type CounterScope } from 'src/engine/core-modules/usage-limit/types/counter-scope.type';
import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
export type UsageLimitFallback = {
spenderType: SpenderType;
- counterScope: 'perWorkspace' | 'crossWorkspace';
- maxTokensConfigVariable: keyof ConfigVariables;
- windowMsConfigVariable: keyof ConfigVariables;
+ counterScope: CounterScope;
+ isOverridable: boolean;
+ limitValueConfigVariable: NumericConfigVariableKey;
+ windowMsConfigVariable: NumericConfigVariableKey;
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-rest-response-body.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-rest-response-body.type.ts
new file mode 100644
index 00000000000..6bcaaedcf28
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-rest-response-body.type.ts
@@ -0,0 +1,17 @@
+import { type LimitKind } from 'src/engine/core-modules/usage-limit/types/limit-kind.type';
+import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
+
+export type UsageLimitRestResponseBody = {
+ statusCode: number;
+ error: string;
+ messages: string[];
+ limitKind: LimitKind;
+ scope: {
+ spenderType: SpenderType;
+ spenderId: string | null;
+ };
+ limit: number;
+ remaining: number;
+ windowSeconds: number;
+ retryAfterSeconds: number;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.module.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.module.ts
index 9ba9f07b37f..909d32aa90e 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.module.ts
@@ -6,6 +6,7 @@ import { ApplicationEntity } from 'src/engine/core-modules/application/applicati
import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
import { AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';
import { LogicFunctionEntity } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
+import { UsageLimitSpeedService } from 'src/engine/core-modules/usage-limit/services/usage-limit-speed.service';
import { UsageLimitResolver } from 'src/engine/core-modules/usage-limit/usage-limit.resolver';
import { UsageLimitService } from 'src/engine/core-modules/usage-limit/services/usage-limit.service';
import { UsageLimitRulesCacheService } from 'src/engine/core-modules/usage-limit/services/usage-limit-rules-cache.service';
@@ -28,6 +29,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
PermissionsModule,
],
providers: [
+ UsageLimitSpeedService,
UsageLimitRulesCacheService,
UsageLimitService,
UsageLimitResolver,
@@ -38,6 +40,6 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
provideWorkspaceScopedRepository(AgentEntity),
provideWorkspaceScopedRepository(LogicFunctionEntity),
],
- exports: [UsageLimitRulesCacheService],
+ exports: [UsageLimitSpeedService, UsageLimitRulesCacheService],
})
export class UsageLimitModule {}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-speed-buckets.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-speed-buckets.util.spec.ts
new file mode 100644
index 00000000000..b18bd2f726d
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-speed-buckets.util.spec.ts
@@ -0,0 +1,233 @@
+import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+import { type DefaultUsageLimitFallback } from 'src/engine/core-modules/usage-limit/types/default-usage-limit-fallback.type';
+import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
+import { buildSpeedBuckets } from 'src/engine/core-modules/usage-limit/utils/build-speed-buckets.util';
+
+const workspace = { id: 'workspace-1' };
+
+// The registry defaults, standing in for API_RATE_LIMITING_* and
+// APPLICATION_API_RATE_LIMITING_*.
+const DEFAULT_USAGE_LIMIT_FALLBACKS: DefaultUsageLimitFallback[] = [
+ {
+ spenderType: 'apiKey',
+ counterScope: 'perWorkspace',
+ maxTokens: 100,
+ windowMs: 1000,
+ isOverridable: true,
+ },
+ {
+ spenderType: 'apiKey',
+ counterScope: 'perWorkspace',
+ maxTokens: 100,
+ windowMs: 60_000,
+ isOverridable: true,
+ },
+ {
+ spenderType: 'application',
+ counterScope: 'crossWorkspace',
+ maxTokens: 500,
+ windowMs: 60_000,
+ isOverridable: false,
+ },
+];
+
+const buildRule = (overrides: Partial<FlatUsageLimit>): FlatUsageLimit => ({
+ id: 'rule-id',
+ resourceType: UsageResourceType.API,
+ operationType: UsageOperationType.API_REQUEST,
+ spenderType: 'apiKey',
+ spenderId: '',
+ limitKind: 'speed',
+ windowSeconds: 60,
+ limitValueType: 'absolute',
+ limitValue: 100,
+ burstValue: null,
+ ...overrides,
+});
+
+const buildBuckets = ({
+ authContext,
+ rules = [],
+}: {
+ authContext: WorkspaceAuthContext;
+ rules?: FlatUsageLimit[];
+}) =>
+ buildSpeedBuckets({
+ defaultUsageLimitFallbacks: DEFAULT_USAGE_LIMIT_FALLBACKS,
+ rules,
+ authContext,
+ resourceType: UsageResourceType.API,
+ operationType: UsageOperationType.API_REQUEST,
+ });
+
+const apiKeyContext = {
+ type: 'apiKey',
+ workspace,
+ apiKey: { id: 'key-1' },
+} as WorkspaceAuthContext;
+
+const applicationContext = {
+ type: 'application',
+ workspace,
+ application: { id: 'app-1', universalIdentifier: 'app-uid' },
+} as WorkspaceAuthContext;
+
+const userContext = {
+ type: 'user',
+ workspace,
+ userWorkspaceId: 'user-workspace-1',
+} as WorkspaceAuthContext;
+
+const agentRunContext = {
+ type: 'user',
+ workspace,
+ userWorkspaceId: 'user-workspace-1',
+ viaApplication: { id: 'app-1', universalIdentifier: 'app-uid' },
+} as WorkspaceAuthContext;
+
+const systemContext = { type: 'system', workspace } as WorkspaceAuthContext;
+
+// Parity with the throttler this replaces: it metered API keys against a single
+// workspace-wide counter and applications against a cross-workspace one, and
+// left every other caller alone.
+describe('buildSpeedBuckets with no rules configured', () => {
+ it('meters an api key against one shared counter per window', () => {
+ expect(buildBuckets({ authContext: apiKeyContext })).toEqual([
+ expect.objectContaining({
+ key: '{workspace-1}:speed:API:API_REQUEST:apiKey:-:1',
+ refillPerWindow: 100,
+ spenderType: 'apiKey',
+ spenderId: null,
+ }),
+ expect.objectContaining({
+ key: '{workspace-1}:speed:API:API_REQUEST:apiKey:-:60',
+ refillPerWindow: 100,
+ spenderId: null,
+ }),
+ ]);
+ });
+
+ it('meters an application against one counter across every workspace', () => {
+ expect(buildBuckets({ authContext: applicationContext })).toEqual([
+ expect.objectContaining({
+ key: '{server}:speed:API:API_REQUEST:application:app-uid:60',
+ refillPerWindow: 500,
+ spenderType: 'application',
+ spenderId: 'app-uid',
+ }),
+ ]);
+ });
+
+ it('leaves a front-end request alone', () => {
+ expect(buildBuckets({ authContext: userContext })).toEqual([]);
+ });
+
+ it('leaves an agent running as a user alone', () => {
+ expect(buildBuckets({ authContext: agentRunContext })).toEqual([]);
+ });
+
+ it('leaves a system request alone', () => {
+ expect(buildBuckets({ authContext: systemContext })).toEqual([]);
+ });
+});
+
+describe('buildSpeedBuckets with rules configured', () => {
+ it('shares one counter between every api key when the rule names none', () => {
+ const [bucket] = buildBuckets({
+ authContext: apiKeyContext,
+ rules: [buildRule({ spenderId: '', limitValue: 10, windowSeconds: 1 })],
+ });
+
+ expect(bucket).toMatchObject({
+ key: '{workspace-1}:speed:API:API_REQUEST:apiKey:-:1',
+ refillPerWindow: 10,
+ spenderId: null,
+ });
+ });
+
+ it('gives a named api key its own counter on top of the shared one', () => {
+ const buckets = buildBuckets({
+ authContext: apiKeyContext,
+ rules: [
+ buildRule({ id: 'shared', spenderId: '', limitValue: 10 }),
+ buildRule({ id: 'own', spenderId: 'key-1', limitValue: 5 }),
+ ],
+ });
+
+ expect(buckets.map((bucket) => bucket.key)).toEqual([
+ '{workspace-1}:speed:API:API_REQUEST:apiKey:key-1:60',
+ '{workspace-1}:speed:API:API_REQUEST:apiKey:-:60',
+ ]);
+ });
+
+ it('keeps a named api key charged for the defaults', () => {
+ const buckets = buildBuckets({
+ authContext: apiKeyContext,
+ rules: [buildRule({ spenderId: 'key-1', limitValue: 5 })],
+ });
+
+ expect(buckets.map((bucket) => bucket.key)).toEqual([
+ '{workspace-1}:speed:API:API_REQUEST:apiKey:key-1:60',
+ '{workspace-1}:speed:API:API_REQUEST:apiKey:-:1',
+ '{workspace-1}:speed:API:API_REQUEST:apiKey:-:60',
+ ]);
+ });
+
+ it('replaces every default once a rule covers the spender type', () => {
+ const buckets = buildBuckets({
+ authContext: apiKeyContext,
+ rules: [buildRule({ spenderId: '', windowSeconds: 60, limitValue: 10 })],
+ });
+
+ expect(
+ buckets.map((bucket) => [bucket.windowMs, bucket.refillPerWindow]),
+ ).toEqual([[60_000, 10]]);
+ });
+
+ it('tells the platform default apart from a configured rule', () => {
+ const buckets = buildBuckets({
+ authContext: apiKeyContext,
+ rules: [buildRule({ spenderId: 'key-1', limitValue: 5 })],
+ });
+
+ expect(buckets.map((bucket) => bucket.isFallback)).toEqual([
+ false,
+ true,
+ true,
+ ]);
+ });
+
+ it('keeps an application charged for the ceiling every workspace shares', () => {
+ const buckets = buildBuckets({
+ authContext: applicationContext,
+ rules: [buildRule({ spenderType: 'application', spenderId: '' })],
+ });
+
+ expect(buckets.map((bucket) => bucket.key)).toEqual([
+ '{server}:speed:API:API_REQUEST:application:app-uid:60',
+ '{workspace-1}:speed:API:API_REQUEST:application:-:60',
+ ]);
+ });
+
+ it('applies a workspace rule to a caller that no other rule covers', () => {
+ const buckets = buildBuckets({
+ authContext: userContext,
+ rules: [
+ buildRule({
+ spenderType: 'workspace',
+ spenderId: '',
+ limitValue: 1000,
+ }),
+ ],
+ });
+
+ expect(buckets).toEqual([
+ expect.objectContaining({
+ key: '{workspace-1}:speed:API:API_REQUEST:workspace:-:60',
+ refillPerWindow: 1000,
+ }),
+ ]);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-spenders-from-auth-context.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-spenders-from-auth-context.util.spec.ts
new file mode 100644
index 00000000000..2d31fb9f6f5
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-spenders-from-auth-context.util.spec.ts
@@ -0,0 +1,67 @@
+import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
+import { buildSpendersFromAuthContext } from 'src/engine/core-modules/usage-limit/utils/build-spenders-from-auth-context.util';
+
+const workspace = { id: 'workspace-1' };
+
+describe('buildSpendersFromAuthContext', () => {
+ it('charges an api key and the workspace it belongs to', () => {
+ const authContext = {
+ type: 'apiKey',
+ workspace,
+ apiKey: { id: 'key-1' },
+ } as WorkspaceAuthContext;
+
+ expect(buildSpendersFromAuthContext(authContext)).toEqual([
+ { spenderType: 'apiKey', spenderId: 'key-1' },
+ { spenderType: 'workspace', spenderId: '' },
+ ]);
+ });
+
+ it('charges an application and the workspace it runs in', () => {
+ const authContext = {
+ type: 'application',
+ workspace,
+ application: { id: 'app-1' },
+ } as WorkspaceAuthContext;
+
+ expect(buildSpendersFromAuthContext(authContext)).toEqual([
+ { spenderType: 'application', spenderId: 'app-1' },
+ { spenderType: 'workspace', spenderId: '' },
+ ]);
+ });
+
+ it('charges a human and the workspace they belong to', () => {
+ const authContext = {
+ type: 'user',
+ workspace,
+ userWorkspaceId: 'user-workspace-1',
+ } as WorkspaceAuthContext;
+
+ expect(buildSpendersFromAuthContext(authContext)).toEqual([
+ { spenderType: 'userWorkspace', spenderId: 'user-workspace-1' },
+ { spenderType: 'workspace', spenderId: '' },
+ ]);
+ });
+
+ it('charges the application too when it acts on behalf of a user', () => {
+ const authContext = {
+ type: 'user',
+ workspace,
+ userWorkspaceId: 'user-workspace-1',
+ viaApplication: { id: 'app-1' },
+ } as WorkspaceAuthContext;
+
+ expect(buildSpendersFromAuthContext(authContext)).toContainEqual({
+ spenderType: 'application',
+ spenderId: 'app-1',
+ });
+ });
+
+ it('charges only the workspace when nothing narrower is authenticated', () => {
+ const authContext = { type: 'system', workspace } as WorkspaceAuthContext;
+
+ expect(buildSpendersFromAuthContext(authContext)).toEqual([
+ { spenderType: 'workspace', spenderId: '' },
+ ]);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-rules-for-spender.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-rules-for-spender.util.spec.ts
new file mode 100644
index 00000000000..ad25cf31eb9
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-rules-for-spender.util.spec.ts
@@ -0,0 +1,125 @@
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
+import { findRulesForSpender } from 'src/engine/core-modules/usage-limit/utils/find-rules-for-spender.util';
+
+const buildRule = (overrides: Partial<FlatUsageLimit>): FlatUsageLimit => ({
+ id: 'rule-id',
+ resourceType: UsageResourceType.API,
+ operationType: UsageOperationType.API_REQUEST,
+ spenderType: 'apiKey',
+ spenderId: '',
+ limitKind: 'speed',
+ windowSeconds: 60,
+ limitValueType: 'absolute',
+ limitValue: 100,
+ burstValue: null,
+ ...overrides,
+});
+
+describe('findRulesForSpender', () => {
+ const spender = { spenderType: 'apiKey' as const, spenderId: 'key-1' };
+
+ it('charges a named spender against its own rule and the shared one', () => {
+ const shared = buildRule({ id: 'shared', spenderId: '' });
+ const own = buildRule({ id: 'own', spenderId: 'key-1', limitValue: 50 });
+
+ expect(
+ findRulesForSpender({
+ rules: [shared, own],
+ spender,
+ operationType: UsageOperationType.API_REQUEST,
+ }),
+ ).toEqual([shared, own]);
+ });
+
+ it('charges a spender with no rule of its own against the shared rule', () => {
+ const shared = buildRule({ id: 'shared', spenderId: '' });
+
+ expect(
+ findRulesForSpender({
+ rules: [shared],
+ spender,
+ operationType: UsageOperationType.API_REQUEST,
+ }),
+ ).toEqual([shared]);
+ });
+
+ it('ignores a rule belonging to another spender', () => {
+ const otherKey = buildRule({ id: 'other', spenderId: 'key-2' });
+
+ expect(
+ findRulesForSpender({
+ rules: [otherKey],
+ spender,
+ operationType: UsageOperationType.API_REQUEST,
+ }),
+ ).toEqual([]);
+ });
+
+ it('ignores a rule scoped to another spender type', () => {
+ const application = buildRule({
+ id: 'application',
+ spenderType: 'application',
+ spenderId: '',
+ });
+
+ expect(
+ findRulesForSpender({
+ rules: [application],
+ spender,
+ operationType: UsageOperationType.API_REQUEST,
+ }),
+ ).toEqual([]);
+ });
+
+ it('ignores a rule scoped to a different operation', () => {
+ const otherOperation = buildRule({
+ spenderId: 'key-1',
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ });
+
+ expect(
+ findRulesForSpender({
+ rules: [otherOperation],
+ spender,
+ operationType: UsageOperationType.API_REQUEST,
+ }),
+ ).toEqual([]);
+ });
+
+ it('returns a burst and a sustained rule together', () => {
+ const burst = buildRule({ id: 'burst', windowSeconds: 1, limitValue: 20 });
+ const sustained = buildRule({ id: 'sustained', windowSeconds: 60 });
+
+ expect(
+ findRulesForSpender({
+ rules: [burst, sustained],
+ spender,
+ operationType: UsageOperationType.API_REQUEST,
+ }),
+ ).toEqual([burst, sustained]);
+ });
+
+ it('keeps every window of the shared rules when the spender has its own rule', () => {
+ const sharedBurst = buildRule({
+ id: 'shared-burst',
+ windowSeconds: 1,
+ limitValue: 20,
+ });
+ const sharedSustained = buildRule({ id: 'shared-sustained' });
+ const own = buildRule({
+ id: 'own',
+ spenderId: 'key-1',
+ limitValue: 5000,
+ });
+
+ expect(
+ findRulesForSpender({
+ rules: [sharedBurst, sharedSustained, own],
+ spender,
+ operationType: UsageOperationType.API_REQUEST,
+ }),
+ ).toEqual([sharedBurst, sharedSustained, own]);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/usage-limit-to-graphql-api-exception-handler.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/usage-limit-to-graphql-api-exception-handler.util.spec.ts
new file mode 100644
index 00000000000..0d069991dc9
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/usage-limit-to-graphql-api-exception-handler.util.spec.ts
@@ -0,0 +1,95 @@
+import {
+ BaseGraphQLError,
+ ErrorCode,
+} from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+import {
+ UsageLimitException,
+ UsageLimitExceptionCode,
+} from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';
+import { type ExhaustedScope } from 'src/engine/core-modules/usage-limit/types/exhausted-scope.type';
+import { usageLimitToGraphqlApiExceptionHandler } from 'src/engine/core-modules/usage-limit/utils/usage-limit-to-graphql-api-exception-handler.util';
+import { shouldCaptureException } from 'src/engine/utils/global-exception-handler.util';
+
+const buildExhaustedScope = (
+ overrides: Partial<ExhaustedScope> = {},
+): ExhaustedScope => ({
+ resourceType: UsageResourceType.API,
+ limitKind: 'speed',
+ spenderType: 'apiKey',
+ spenderId: 'key-1',
+ limitValue: 3,
+ remaining: 0,
+ windowSeconds: 60,
+ retryAfterMs: 11983,
+ isFallback: true,
+ ...overrides,
+});
+
+const catchThrown = (exhaustedScope?: ExhaustedScope): BaseGraphQLError => {
+ try {
+ usageLimitToGraphqlApiExceptionHandler(
+ new UsageLimitException(
+ 'Rate limit exceeded for apiKey: 3 requests per 60s.',
+ UsageLimitExceptionCode.RATE_LIMITED,
+ { exhaustedScope },
+ ),
+ );
+ } catch (error) {
+ return error as BaseGraphQLError;
+ }
+
+ throw new Error('the handler was expected to throw');
+};
+
+describe('usageLimitToGraphqlApiExceptionHandler', () => {
+ it('raises a BaseGraphQLError so the code survives error normalisation', () => {
+ const error = catchThrown(buildExhaustedScope());
+
+ expect(error).toBeInstanceOf(BaseGraphQLError);
+ expect(error.extensions.code).toBe(ErrorCode.RATE_LIMITED);
+ });
+
+ it('keeps transport concerns out of the GraphQL error', () => {
+ expect(catchThrown(buildExhaustedScope()).extensions.http).toBeUndefined();
+ });
+
+ it('reports the exhausted scope back to the caller', () => {
+ const error = catchThrown(buildExhaustedScope());
+
+ expect(error.extensions).toMatchObject({
+ limitKind: 'speed',
+ limit: 3,
+ remaining: 0,
+ windowSeconds: 60,
+ retryAfterMs: 11983,
+ scope: { spenderType: 'apiKey', spenderId: 'key-1' },
+ });
+ });
+
+ it('keeps a denial out of Sentry', () => {
+ expect(shouldCaptureException(catchThrown(buildExhaustedScope()))).toBe(
+ false,
+ );
+ });
+
+ it('still names the code when no scope was resolved', () => {
+ expect(catchThrown(undefined).extensions.code).toBe(ErrorCode.RATE_LIMITED);
+ });
+
+ it('names an exhausted quota apart from an exhausted rate', () => {
+ try {
+ usageLimitToGraphqlApiExceptionHandler(
+ new UsageLimitException(
+ 'Usage quota exhausted.',
+ UsageLimitExceptionCode.QUOTA_EXHAUSTED,
+ { exhaustedScope: buildExhaustedScope() },
+ ),
+ );
+ } catch (error) {
+ expect((error as BaseGraphQLError).extensions.code).toBe(
+ ErrorCode.QUOTA_EXHAUSTED,
+ );
+ }
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/usage-limit-to-rest-api-exception-handler.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/usage-limit-to-rest-api-exception-handler.util.spec.ts
new file mode 100644
index 00000000000..a0f40bb33f5
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/usage-limit-to-rest-api-exception-handler.util.spec.ts
@@ -0,0 +1,103 @@
+import { HttpStatus } from '@nestjs/common';
+
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+import { UsageLimitHttpException } from 'src/engine/core-modules/usage-limit/exceptions/usage-limit-http.exception';
+import {
+ UsageLimitException,
+ UsageLimitExceptionCode,
+} from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';
+import { type ExhaustedScope } from 'src/engine/core-modules/usage-limit/types/exhausted-scope.type';
+import { usageLimitToRestApiExceptionHandler } from 'src/engine/core-modules/usage-limit/utils/usage-limit-to-rest-api-exception-handler.util';
+
+const buildExhaustedScope = (
+ overrides: Partial<ExhaustedScope> = {},
+): ExhaustedScope => ({
+ resourceType: UsageResourceType.API,
+ limitKind: 'speed',
+ spenderType: 'apiKey',
+ spenderId: 'key-1',
+ limitValue: 3,
+ remaining: 0,
+ windowSeconds: 60,
+ retryAfterMs: 11983,
+ isFallback: true,
+ ...overrides,
+});
+
+const catchThrown = (
+ exhaustedScope?: ExhaustedScope,
+): UsageLimitHttpException => {
+ try {
+ usageLimitToRestApiExceptionHandler(
+ new UsageLimitException(
+ 'Rate limit exceeded for apiKey: 3 requests per 60s.',
+ UsageLimitExceptionCode.RATE_LIMITED,
+ { exhaustedScope },
+ ),
+ );
+ } catch (error) {
+ return error as UsageLimitHttpException;
+ }
+
+ throw new Error('the handler was expected to throw');
+};
+
+describe('usageLimitToRestApiExceptionHandler', () => {
+ it('answers 429 with the exhausted scope in the body', () => {
+ const error = catchThrown(buildExhaustedScope());
+
+ expect(error.getStatus()).toBe(HttpStatus.TOO_MANY_REQUESTS);
+ expect(error.getResponseBody()).toEqual({
+ statusCode: HttpStatus.TOO_MANY_REQUESTS,
+ error: 'RATE_LIMITED',
+ messages: ['Rate limit exceeded for apiKey: 3 requests per 60s.'],
+ limitKind: 'speed',
+ scope: { spenderType: 'apiKey', spenderId: 'key-1' },
+ limit: 3,
+ remaining: 0,
+ windowSeconds: 60,
+ retryAfterSeconds: 12,
+ });
+ });
+
+ it('tells the caller when to come back', () => {
+ expect(catchThrown(buildExhaustedScope()).getResponseHeaders()).toEqual(
+ expect.objectContaining({
+ 'Retry-After': '12',
+ 'X-RateLimit-Limit': '3',
+ 'X-RateLimit-Remaining': '0',
+ }),
+ );
+ });
+
+ it('never asks the caller to retry in zero seconds', () => {
+ expect(
+ catchThrown(
+ buildExhaustedScope({ retryAfterMs: 4 }),
+ ).getResponseHeaders()['Retry-After'],
+ ).toBe('1');
+ });
+
+ it('keeps the message readable for logs', () => {
+ expect(catchThrown(buildExhaustedScope()).message).toBe(
+ 'Rate limit exceeded for apiKey: 3 requests per 60s.',
+ );
+ });
+
+ it('falls back to a bare 429 when no scope was resolved', () => {
+ let thrown: unknown;
+
+ try {
+ usageLimitToRestApiExceptionHandler(
+ new UsageLimitException(
+ 'Rate limit exceeded.',
+ UsageLimitExceptionCode.RATE_LIMITED,
+ ),
+ );
+ } catch (error) {
+ thrown = error;
+ }
+
+ expect(thrown).not.toBeInstanceOf(UsageLimitHttpException);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/validate-usage-limit-against-definition.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/validate-usage-limit-against-definition.util.spec.ts
index 03b9bb30bb8..454a0fc7f64 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/validate-usage-limit-against-definition.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/validate-usage-limit-against-definition.util.spec.ts
@@ -73,7 +73,7 @@ describe('validateUsageLimitAgainstDefinition', () => {
);
});
- it('rejects a workspace rule, since the instance operator owns that scope', () => {
+ it('rejects a workspace rule, because the definition does not allow that scope', () => {
expect(() =>
validateUsageLimitAgainstDefinition({
...validSpeedRule,
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-fallback-speed-bucket.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-fallback-speed-bucket.util.ts
new file mode 100644
index 00000000000..2d5fcef5bcc
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-fallback-speed-bucket.util.ts
@@ -0,0 +1,51 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
+import { type DefaultUsageLimitFallback } from 'src/engine/core-modules/usage-limit/types/default-usage-limit-fallback.type';
+import { type SpeedBucketRequest } from 'src/engine/core-modules/usage-limit/types/speed-bucket-request.type';
+import { type Spender } from 'src/engine/core-modules/usage-limit/types/spender.type';
+import { buildSpeedBucketKey } from 'src/engine/core-modules/usage-limit/utils/build-speed-bucket-key.util';
+import { getApplicationUniversalIdentifier } from 'src/engine/core-modules/usage-limit/utils/get-application-universal-identifier.util';
+import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { type UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+
+export const buildFallbackSpeedBucket = ({
+ fallback,
+ spender,
+ authContext,
+ resourceType,
+ operationType,
+}: {
+ fallback: DefaultUsageLimitFallback;
+ spender: Spender;
+ authContext: WorkspaceAuthContext;
+ resourceType: UsageResourceType;
+ operationType: UsageOperationType;
+}): SpeedBucketRequest | null => {
+ const isCrossWorkspace = fallback.counterScope === 'crossWorkspace';
+ const universalIdentifier = getApplicationUniversalIdentifier(authContext);
+
+ if (isCrossWorkspace && !isDefined(universalIdentifier)) {
+ return null;
+ }
+
+ const spenderId = isCrossWorkspace ? universalIdentifier : null;
+
+ return {
+ key: buildSpeedBucketKey({
+ counterScope: fallback.counterScope,
+ workspaceId: authContext.workspace.id,
+ resourceType,
+ operationType,
+ spenderType: spender.spenderType,
+ spenderId,
+ windowSeconds: Math.ceil(fallback.windowMs / 1000),
+ }),
+ burst: fallback.maxTokens,
+ refillPerWindow: fallback.maxTokens,
+ windowMs: fallback.windowMs,
+ spenderType: spender.spenderType,
+ spenderId,
+ isFallback: true,
+ };
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-rate-limit-response-headers.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-rate-limit-response-headers.util.ts
new file mode 100644
index 00000000000..74db692d2b8
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-rate-limit-response-headers.util.ts
@@ -0,0 +1,14 @@
+import { type ExhaustedScope } from 'src/engine/core-modules/usage-limit/types/exhausted-scope.type';
+
+export const buildRateLimitResponseHeaders = ({
+ exhaustedScope,
+ retryAfterSeconds,
+}: {
+ exhaustedScope: ExhaustedScope;
+ retryAfterSeconds: number;
+}): Record<string, string> => ({
+ 'Retry-After': String(retryAfterSeconds),
+ 'X-RateLimit-Limit': String(exhaustedScope.limitValue),
+ 'X-RateLimit-Remaining': String(exhaustedScope.remaining),
+ 'X-RateLimit-Reset': String(Math.ceil(Date.now() / 1000) + retryAfterSeconds),
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-speed-bucket-key.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-speed-bucket-key.util.ts
new file mode 100644
index 00000000000..507b4e63abf
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-speed-bucket-key.util.ts
@@ -0,0 +1,29 @@
+import { type CounterScope } from 'src/engine/core-modules/usage-limit/types/counter-scope.type';
+import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
+import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { type UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+
+const ABSENT = '-';
+const SERVER_SCOPE = 'server';
+
+export const buildSpeedBucketKey = ({
+ counterScope,
+ workspaceId,
+ resourceType,
+ operationType,
+ spenderType,
+ spenderId,
+ windowSeconds,
+}: {
+ counterScope: CounterScope;
+ workspaceId: string;
+ resourceType: UsageResourceType;
+ operationType: UsageOperationType;
+ spenderType: SpenderType;
+ spenderId?: string | null;
+ windowSeconds: number;
+}): string => {
+ const scope = counterScope === 'crossWorkspace' ? SERVER_SCOPE : workspaceId;
+
+ return `{${scope}}:speed:${resourceType}:${operationType}:${spenderType}:${spenderId || ABSENT}:${windowSeconds}`;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-speed-buckets.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-speed-buckets.util.ts
new file mode 100644
index 00000000000..36f6e8d31f5
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-speed-buckets.util.ts
@@ -0,0 +1,80 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
+import { SPENDER_TYPE_SPECIFICITY } from 'src/engine/core-modules/usage-limit/constants/spender-type-specificity.constant';
+import { type DefaultUsageLimitFallback } from 'src/engine/core-modules/usage-limit/types/default-usage-limit-fallback.type';
+import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
+import { type SpeedBucketRequest } from 'src/engine/core-modules/usage-limit/types/speed-bucket-request.type';
+import { buildFallbackSpeedBucket } from 'src/engine/core-modules/usage-limit/utils/build-fallback-speed-bucket.util';
+import { buildSpeedBucketKey } from 'src/engine/core-modules/usage-limit/utils/build-speed-bucket-key.util';
+import { buildSpendersFromAuthContext } from 'src/engine/core-modules/usage-limit/utils/build-spenders-from-auth-context.util';
+import { findRulesForSpender } from 'src/engine/core-modules/usage-limit/utils/find-rules-for-spender.util';
+import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { type UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+
+const bucketSpecificity = (bucket: SpeedBucketRequest): number =>
+ SPENDER_TYPE_SPECIFICITY[bucket.spenderType] * 2 +
+ (isDefined(bucket.spenderId) ? 0 : 1);
+
+export const buildSpeedBuckets = ({
+ defaultUsageLimitFallbacks,
+ rules,
+ authContext,
+ resourceType,
+ operationType,
+}: {
+ defaultUsageLimitFallbacks: DefaultUsageLimitFallback[];
+ rules: FlatUsageLimit[];
+ authContext: WorkspaceAuthContext;
+ resourceType: UsageResourceType;
+ operationType: UsageOperationType;
+}): SpeedBucketRequest[] => {
+ const spenders = buildSpendersFromAuthContext(authContext);
+
+ const buckets = spenders.flatMap((spender) => {
+ const spenderRules = findRulesForSpender({ rules, spender, operationType });
+
+ const ruleBuckets = spenderRules.map((rule) => ({
+ key: buildSpeedBucketKey({
+ counterScope: 'perWorkspace',
+ workspaceId: authContext.workspace.id,
+ resourceType,
+ operationType,
+ spenderType: spender.spenderType,
+ spenderId: rule.spenderId,
+ windowSeconds: rule.windowSeconds,
+ }),
+ burst: rule.burstValue ?? rule.limitValue,
+ refillPerWindow: rule.limitValue,
+ windowMs: rule.windowSeconds * 1000,
+ spenderType: spender.spenderType,
+ spenderId: rule.spenderId === '' ? null : rule.spenderId,
+ isFallback: false,
+ }));
+
+ const hasRuleForEverySpender = spenderRules.some(
+ (rule) => rule.spenderId === '',
+ );
+
+ const fallbackBuckets = defaultUsageLimitFallbacks
+ .filter(
+ (fallback) =>
+ fallback.spenderType === spender.spenderType &&
+ !(fallback.isOverridable && hasRuleForEverySpender),
+ )
+ .map((fallback) =>
+ buildFallbackSpeedBucket({
+ fallback,
+ spender,
+ authContext,
+ resourceType,
+ operationType,
+ }),
+ )
+ .filter(isDefined);
+
+ return [...ruleBuckets, ...fallbackBuckets];
+ });
+
+ return buckets.sort((a, b) => bucketSpecificity(a) - bucketSpecificity(b));
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-spenders-from-auth-context.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-spenders-from-auth-context.util.ts
new file mode 100644
index 00000000000..2f24cb5ff8d
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-spenders-from-auth-context.util.ts
@@ -0,0 +1,42 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { isApiKeyAuthContext } from 'src/engine/core-modules/auth/guards/is-api-key-auth-context.guard';
+import { isApplicationAuthContext } from 'src/engine/core-modules/auth/guards/is-application-auth-context.guard';
+import { isUserAuthContext } from 'src/engine/core-modules/auth/guards/is-user-auth-context.guard';
+import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
+import { type Spender } from 'src/engine/core-modules/usage-limit/types/spender.type';
+
+export const buildSpendersFromAuthContext = (
+ authContext: WorkspaceAuthContext,
+): Spender[] => {
+ const spenders: Spender[] = [];
+
+ if (isApiKeyAuthContext(authContext)) {
+ spenders.push({ spenderType: 'apiKey', spenderId: authContext.apiKey.id });
+ }
+
+ if (isApplicationAuthContext(authContext)) {
+ spenders.push({
+ spenderType: 'application',
+ spenderId: authContext.application.id,
+ });
+ }
+
+ if (isUserAuthContext(authContext)) {
+ spenders.push({
+ spenderType: 'userWorkspace',
+ spenderId: authContext.userWorkspaceId,
+ });
+
+ const applicationId =
+ authContext.application?.id ?? authContext.viaApplication?.id;
+
+ if (isDefined(applicationId)) {
+ spenders.push({ spenderType: 'application', spenderId: applicationId });
+ }
+ }
+
+ spenders.push({ spenderType: 'workspace', spenderId: '' });
+
+ return spenders;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-rules-for-spender.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-rules-for-spender.util.ts
new file mode 100644
index 00000000000..18e90ae6757
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-rules-for-spender.util.ts
@@ -0,0 +1,22 @@
+import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
+import { type Spender } from 'src/engine/core-modules/usage-limit/types/spender.type';
+import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+
+// A rule naming the spender and a rule left open to every spender of that type
+// produce two different buckets, so both apply rather than the narrower one
+// replacing the shared one.
+export const findRulesForSpender = ({
+ rules,
+ spender,
+ operationType,
+}: {
+ rules: FlatUsageLimit[];
+ spender: Spender;
+ operationType: UsageOperationType;
+}): FlatUsageLimit[] =>
+ rules.filter(
+ (rule) =>
+ rule.spenderType === spender.spenderType &&
+ rule.operationType === operationType &&
+ (rule.spenderId === '' || rule.spenderId === spender.spenderId),
+ );
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-application-universal-identifier.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-application-universal-identifier.util.ts
new file mode 100644
index 00000000000..e83ec7cf44f
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-application-universal-identifier.util.ts
@@ -0,0 +1,12 @@
+import { isApplicationAuthContext } from 'src/engine/core-modules/auth/guards/is-application-auth-context.guard';
+import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
+
+// Deliberately blind to an application carried by a user context: the throttler
+// this replaces only metered requests the application made in its own name, and
+// widening it would charge agent runs to the application's cross-workspace budget.
+export const getApplicationUniversalIdentifier = (
+ authContext: WorkspaceAuthContext,
+): string | null =>
+ isApplicationAuthContext(authContext)
+ ? (authContext.application.universalIdentifier ?? null)
+ : null;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-retry-after-seconds.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-retry-after-seconds.util.ts
new file mode 100644
index 00000000000..b0476d41ade
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-retry-after-seconds.util.ts
@@ -0,0 +1,4 @@
+// Retry-After is expressed in whole seconds, and a value of 0 would invite an
+// immediate retry that is guaranteed to be denied again.
+export const getRetryAfterSeconds = (retryAfterMs: number): number =>
+ Math.max(1, Math.ceil(retryAfterMs / 1000));
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-usage-limit-error-code.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-usage-limit-error-code.util.ts
new file mode 100644
index 00000000000..94ac35bcd2e
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-usage-limit-error-code.util.ts
@@ -0,0 +1,9 @@
+import { ErrorCode } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
+import { UsageLimitExceptionCode } from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';
+
+export const getUsageLimitErrorCode = (
+ code: UsageLimitExceptionCode,
+): ErrorCode =>
+ code === UsageLimitExceptionCode.QUOTA_EXHAUSTED
+ ? ErrorCode.QUOTA_EXHAUSTED
+ : ErrorCode.RATE_LIMITED;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/usage-limit-to-graphql-api-exception-handler.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/usage-limit-to-graphql-api-exception-handler.util.ts
new file mode 100644
index 00000000000..3ab06ce3cba
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/usage-limit-to-graphql-api-exception-handler.util.ts
@@ -0,0 +1,41 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { BaseGraphQLError } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
+import { type UsageLimitException } from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';
+import { getUsageLimitErrorCode } from 'src/engine/core-modules/usage-limit/utils/get-usage-limit-error-code.util';
+
+export const usageLimitToGraphqlApiExceptionHandler = (
+ error: UsageLimitException,
+): never => {
+ const { exhaustedScope } = error;
+
+ const commonExtensions = {
+ subCode: error.code,
+ userFriendlyMessage: error.userFriendlyMessage,
+ };
+
+ if (!isDefined(exhaustedScope)) {
+ throw new BaseGraphQLError(
+ error.message,
+ getUsageLimitErrorCode(error.code),
+ commonExtensions,
+ );
+ }
+
+ throw new BaseGraphQLError(
+ error.message,
+ getUsageLimitErrorCode(error.code),
+ {
+ ...commonExtensions,
+ limitKind: exhaustedScope.limitKind,
+ limit: exhaustedScope.limitValue,
+ remaining: exhaustedScope.remaining,
+ windowSeconds: exhaustedScope.windowSeconds,
+ retryAfterMs: exhaustedScope.retryAfterMs,
+ scope: {
+ spenderType: exhaustedScope.spenderType,
+ spenderId: exhaustedScope.spenderId,
+ },
+ },
+ );
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/usage-limit-to-rest-api-exception-handler.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/usage-limit-to-rest-api-exception-handler.util.ts
new file mode 100644
index 00000000000..ca4fbf33015
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/usage-limit-to-rest-api-exception-handler.util.ts
@@ -0,0 +1,39 @@
+import { HttpException, HttpStatus } from '@nestjs/common';
+
+import { isDefined } from 'twenty-shared/utils';
+
+import { UsageLimitHttpException } from 'src/engine/core-modules/usage-limit/exceptions/usage-limit-http.exception';
+import { type UsageLimitException } from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';
+import { buildRateLimitResponseHeaders } from 'src/engine/core-modules/usage-limit/utils/build-rate-limit-response-headers.util';
+import { getRetryAfterSeconds } from 'src/engine/core-modules/usage-limit/utils/get-retry-after-seconds.util';
+import { getUsageLimitErrorCode } from 'src/engine/core-modules/usage-limit/utils/get-usage-limit-error-code.util';
+
+export const usageLimitToRestApiExceptionHandler = (
+ error: UsageLimitException,
+): never => {
+ const { exhaustedScope } = error;
+
+ if (!isDefined(exhaustedScope)) {
+ throw new HttpException(error.message, HttpStatus.TOO_MANY_REQUESTS);
+ }
+
+ const retryAfterSeconds = getRetryAfterSeconds(exhaustedScope.retryAfterMs);
+
+ throw new UsageLimitHttpException(
+ {
+ statusCode: HttpStatus.TOO_MANY_REQUESTS,
+ error: getUsageLimitErrorCode(error.code),
+ messages: [error.message],
+ limitKind: exhaustedScope.limitKind,
+ scope: {
+ spenderType: exhaustedScope.spenderType,
+ spenderId: exhaustedScope.spenderId,
+ },
+ limit: exhaustedScope.limitValue,
+ remaining: exhaustedScope.remaining,
+ windowSeconds: exhaustedScope.windowSeconds,
+ retryAfterSeconds,
+ },
+ buildRateLimitResponseHeaders({ exhaustedScope, retryAfterSeconds }),
+ );
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/validate-usage-limit-against-definition.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/validate-usage-limit-against-definition.util.ts
index 06ac1980472..39720b15b73 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/validate-usage-limit-against-definition.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/validate-usage-limit-against-definition.util.ts
@@ -1,7 +1,6 @@
import { isNonEmptyString } from '@sniptt/guards';
import { isDefined, isValidUuid } from 'twenty-shared/utils';
-import { OPERATOR_ONLY_SPENDER_TYPES } from 'src/engine/core-modules/usage-limit/constants/operator-only-spender-types.constant';
import { type UpsertUsageLimitInput } from 'src/engine/core-modules/usage-limit/dtos/upsert-usage-limit.input';
import {
UsageLimitException,
@@ -38,13 +37,6 @@ export const validateUsageLimitAgainstDefinition = (
);
}
- if (OPERATOR_ONLY_SPENDER_TYPES.includes(input.spenderType)) {
- throw new UsageLimitException(
- `${input.spenderType} limits are set by the instance operator`,
- UsageLimitExceptionCode.LIMIT_RULE_INVALID,
- );
- }
-
if (isNonEmptyString(input.spenderId) && !isValidUuid(input.spenderId)) {
throw new UsageLimitException(
`${input.spenderId} is not a valid ${input.spenderType} id`,
diff --git a/packages/twenty-server/src/engine/utils/global-exception-handler.util.ts b/packages/twenty-server/src/engine/utils/global-exception-handler.util.ts
index 3d3bab52a7d..c0087f65717 100644
--- a/packages/twenty-server/src/engine/utils/global-exception-handler.util.ts
+++ b/packages/twenty-server/src/engine/utils/global-exception-handler.util.ts
@@ -42,6 +42,8 @@ export const graphQLErrorCodesToFilter = [
ErrorCode.CONFLICT,
ErrorCode.BAD_USER_INPUT,
ErrorCode.METADATA_VALIDATION_FAILED,
+ ErrorCode.RATE_LIMITED,
+ ErrorCode.QUOTA_EXHAUSTED,
];
export const handleExceptionAndConvertToGraphQLError = (
diff --git a/packages/twenty-server/test/integration/usage-limit/api-rate-limit.integration-spec.ts b/packages/twenty-server/test/integration/usage-limit/api-rate-limit.integration-spec.ts
new file mode 100644
index 00000000000..8b3893c1258
--- /dev/null
+++ b/packages/twenty-server/test/integration/usage-limit/api-rate-limit.integration-spec.ts
@@ -0,0 +1,279 @@
+import { findManyOperationFactory } from 'test/integration/graphql/utils/find-many-operation-factory.util';
+import { generateApiKeyToken } from 'test/integration/graphql/utils/generate-api-key-token.util';
+import { makeGraphqlAPIRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
+import { makeMetadataAPIRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+import { makeRestAPIRequest } from 'test/integration/rest/utils/make-rest-api-request.util';
+import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';
+import { jestExpectToBeDefined } from 'test/utils/jest-expect-to-be-defined.util.test';
+
+import { gql } from 'graphql-tag';
+import { createClient } from 'redis';
+import { FeatureFlagKey } from 'twenty-shared/types';
+import { type Repository } from 'typeorm';
+
+import { ApiKeyEntity } from 'src/engine/core-modules/api-key/api-key.entity';
+import { FeatureFlagEntity } from 'src/engine/core-modules/feature-flag/feature-flag.entity';
+import { UsageLimitEntity } from 'src/engine/core-modules/usage-limit/usage-limit.entity';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+
+const WINDOW_SECONDS = 1;
+const LIMIT_VALUE = 1;
+
+describe('API rate limiting', () => {
+ let usageLimitRepository: Repository<UsageLimitEntity>;
+ let featureFlagRepository: Repository<FeatureFlagEntity>;
+ let apiKeyRepository: Repository<ApiKeyEntity>;
+ let redis: Awaited<ReturnType<typeof createClient>>;
+ let usageLimitId: string;
+ let apiKeyId: string;
+ let apiKeyToken: string;
+
+ const findCompaniesOverGraphql = () =>
+ makeGraphqlAPIRequest(
+ findManyOperationFactory({
+ objectMetadataSingularName: 'company',
+ objectMetadataPluralName: 'companies',
+ gqlFields: 'id',
+ first: 1,
+ }),
+ apiKeyToken,
+ );
+
+ const findCompaniesOverRest = () =>
+ makeRestAPIRequest({
+ method: 'get',
+ path: '/companies?limit=1',
+ bearer: apiKeyToken,
+ });
+
+ // Every test starts from a full bucket so it does not inherit whatever the
+ // previous one spent.
+ const waitForBucketRefill = () =>
+ new Promise((resolve) => setTimeout(resolve, WINDOW_SECONDS * 1000 + 200));
+
+ const invalidateWorkspaceCaches = async () => {
+ const keys = [
+ ...(await redis.keys(`*featureFlagsMap:${SEED_APPLE_WORKSPACE_ID}*`)),
+ ...(await redis.keys(`*usageLimitRules:${SEED_APPLE_WORKSPACE_ID}*`)),
+ ];
+
+ if (keys.length > 0) {
+ await redis.del(keys);
+ }
+
+ await new Promise((resolve) => setTimeout(resolve, 300));
+ };
+
+ // The rule targets a key created for this suite alone. A workspace-scoped one
+ // would meter every caller in the seeded workspace, and deleting it here
+ // cannot undo that: the workspace cache memoizes resolved entries in process
+ // for MEMOIZER_TTL_MS, so the next spec file would still be rate limited.
+ const createDedicatedApiKey = async () => {
+ const rolesResponse = await makeMetadataAPIRequest({
+ query: gql`
+ query GetRoles {
+ getRoles {
+ id
+ label
+ }
+ }
+ `,
+ });
+
+ const adminRoleId = rolesResponse.body.data?.getRoles?.find(
+ (role: { label: string }) => role.label === 'Admin',
+ )?.id;
+
+ jestExpectToBeDefined(adminRoleId);
+
+ const createResponse = await makeMetadataAPIRequest({
+ query: gql`
+ mutation CreateApiKey($input: CreateApiKeyInput!) {
+ createApiKey(input: $input) {
+ id
+ }
+ }
+ `,
+ variables: {
+ input: {
+ name: 'API rate limiting test key',
+ expiresAt: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
+ roleId: adminRoleId,
+ },
+ },
+ });
+
+ apiKeyId = createResponse.body.data?.createApiKey?.id;
+ jestExpectToBeDefined(apiKeyId);
+
+ const tokenResponse = await generateApiKeyToken({
+ apiKeyId,
+ accessToken: APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ });
+
+ apiKeyToken = tokenResponse.body.data?.generateApiKeyToken?.token;
+ jestExpectToBeDefined(apiKeyToken);
+ };
+
+ beforeAll(async () => {
+ usageLimitRepository =
+ getCoreRepository<UsageLimitEntity>(UsageLimitEntity);
+ featureFlagRepository =
+ getCoreRepository<FeatureFlagEntity>(FeatureFlagEntity);
+ apiKeyRepository = getCoreRepository<ApiKeyEntity>(ApiKeyEntity);
+ redis = await createClient({ url: process.env.REDIS_URL }).connect();
+
+ await createDedicatedApiKey();
+
+ await featureFlagRepository.delete({
+ key: FeatureFlagKey.IS_API_RATE_LIMIT_V2_ENABLED,
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ });
+ await featureFlagRepository.save({
+ key: FeatureFlagKey.IS_API_RATE_LIMIT_V2_ENABLED,
+ value: true,
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ });
+
+ const [usageLimit] = await usageLimitRepository.save([
+ {
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ resourceType: UsageResourceType.API,
+ operationType: UsageOperationType.API_REQUEST,
+ spenderType: 'apiKey',
+ spenderId: apiKeyId,
+ limitKind: 'speed',
+ windowSeconds: WINDOW_SECONDS,
+ limitValueType: 'absolute',
+ limitValue: LIMIT_VALUE,
+ burstValue: LIMIT_VALUE,
+ },
+ ]);
+
+ usageLimitId = usageLimit.id;
+
+ await invalidateWorkspaceCaches();
+ });
+
+ afterAll(async () => {
+ await usageLimitRepository.delete({ id: usageLimitId });
+ await featureFlagRepository.delete({
+ key: FeatureFlagKey.IS_API_RATE_LIMIT_V2_ENABLED,
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ });
+ await apiKeyRepository.delete({ id: apiKeyId });
+ await invalidateWorkspaceCaches();
+ await redis.quit();
+ });
+
+ describe('over GraphQL', () => {
+ it('admits a request and rejects the one that follows it', async () => {
+ await waitForBucketRefill();
+
+ const admitted = await findCompaniesOverGraphql();
+
+ expect(admitted.body.errors).toBeUndefined();
+
+ const rejected = await findCompaniesOverGraphql();
+
+ expect(rejected.body.errors?.[0]?.extensions?.code).toBe('RATE_LIMITED');
+ });
+
+ // GraphQL keeps answering 200 and reports the denial in the extensions, so
+ // an Apollo caller reads it as a GraphQL error rather than a network one.
+ it('reports the denial in the body rather than in the HTTP status', async () => {
+ await waitForBucketRefill();
+ await findCompaniesOverGraphql();
+
+ const rejected = await findCompaniesOverGraphql();
+
+ expect(rejected.status).toBe(200);
+ expect(rejected.body.errors?.[0]?.extensions?.http).toBeUndefined();
+ });
+
+ it('names the exhausted scope and says when to retry', async () => {
+ await waitForBucketRefill();
+ await findCompaniesOverGraphql();
+
+ const { body } = await findCompaniesOverGraphql();
+ const extensions = body.errors?.[0]?.extensions;
+
+ expect(extensions).toMatchObject({
+ code: 'RATE_LIMITED',
+ limitKind: 'speed',
+ limit: LIMIT_VALUE,
+ remaining: 0,
+ windowSeconds: WINDOW_SECONDS,
+ scope: { spenderType: 'apiKey', spenderId: apiKeyId },
+ });
+ expect(extensions.retryAfterMs).toBeGreaterThan(0);
+ });
+
+ it('lets the caller back in once the window refills', async () => {
+ await waitForBucketRefill();
+ await findCompaniesOverGraphql();
+ await findCompaniesOverGraphql();
+
+ await waitForBucketRefill();
+
+ expect((await findCompaniesOverGraphql()).body.errors).toBeUndefined();
+ });
+ });
+
+ describe('over REST', () => {
+ it('admits a request and rejects the one that follows it', async () => {
+ await waitForBucketRefill();
+
+ const admitted = await findCompaniesOverRest();
+
+ expect(admitted.status).toBe(200);
+
+ const rejected = await findCompaniesOverRest();
+
+ expect(rejected.status).toBe(429);
+ });
+
+ it('names the exhausted scope in the body', async () => {
+ await waitForBucketRefill();
+ await findCompaniesOverRest();
+
+ const { body } = await findCompaniesOverRest();
+
+ expect(body).toMatchObject({
+ statusCode: 429,
+ error: 'RATE_LIMITED',
+ limitKind: 'speed',
+ limit: LIMIT_VALUE,
+ remaining: 0,
+ windowSeconds: WINDOW_SECONDS,
+ retryAfterSeconds: 1,
+ scope: { spenderType: 'apiKey', spenderId: apiKeyId },
+ });
+ expect(body.messages).toHaveLength(1);
+ });
+
+ it('answers with a Retry-After the caller can honour', async () => {
+ await waitForBucketRefill();
+ await findCompaniesOverRest();
+
+ const rejected = await findCompaniesOverRest();
+
+ expect(rejected.headers['retry-after']).toBe('1');
+ expect(rejected.headers['x-ratelimit-limit']).toBe(String(LIMIT_VALUE));
+ expect(rejected.headers['x-ratelimit-remaining']).toBe('0');
+ expect(Number(rejected.headers['x-ratelimit-reset'])).toBeGreaterThan(0);
+ });
+
+ it('lets the caller back in once the window refills', async () => {
+ await waitForBucketRefill();
+ await findCompaniesOverRest();
+ await findCompaniesOverRest();
+
+ await waitForBucketRefill();
+
+ expect((await findCompaniesOverRest()).status).toBe(200);
+ });
+ });
+});
diff --git a/packages/twenty-shared/src/types/FeatureFlagKey.ts b/packages/twenty-shared/src/types/FeatureFlagKey.ts
index cc916b21c4b..60853090d12 100644
--- a/packages/twenty-shared/src/types/FeatureFlagKey.ts
+++ b/packages/twenty-shared/src/types/FeatureFlagKey.ts
@@ -10,4 +10,5 @@ export enum FeatureFlagKey {
IS_WORKFLOW_VERSION_IN_CORE_ENABLED = 'IS_WORKFLOW_VERSION_IN_CORE_ENABLED',
IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED = 'IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED',
IS_WORKFLOW_DISPATCH_FROM_CORE_ENABLED = 'IS_WORKFLOW_DISPATCH_FROM_CORE_ENABLED',
+ IS_API_RATE_LIMIT_V2_ENABLED = 'IS_API_RATE_LIMIT_V2_ENABLED',
}