Skip to content

The open alternative to Salesforce, designed for AI.

feat(usage): meter common API calls in complexity points (#26671)

Etienned23218e9e8e8
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 d6955bdac4a..57fbdb62c95 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
@@ -129,12 +129,13 @@ export abstract class CommonBaseQueryRunnerService<
flatFieldMetadataMaps,
} = queryRunnerContext;
- if ((queryRunnerContext.nestedOperationDepth ?? 0) === 0) {
+ const isRootOperation =
+ (queryRunnerContext.nestedOperationDepth ?? 0) === 0;
+
+ if (isRootOperation) {
await this.consumeApiSpeedLimit(authContext);
}
- this.recordApiUsage(authContext);
-
await this.validate(args, queryRunnerContext);
if (flatObjectMetadata.isSystem === true) {
@@ -159,12 +160,16 @@ export abstract class CommonBaseQueryRunnerService<
selectedFieldsResult,
} as CommonExtendedInput<Args>;
- this.validateQueryComplexity(
+ const queryComplexity = this.validateQueryComplexity(
selectedFieldsResult,
processedArgs,
queryRunnerContext,
);
+ if (isRootOperation) {
+ this.recordApiComplexityUsage(authContext, queryComplexity);
+ }
+
const results = await this.workspaceOrmManager.executeInWorkspaceContext(
async () =>
this.executeQueryAndEnrichResults(
@@ -544,26 +549,23 @@ export abstract class CommonBaseQueryRunnerService<
};
}
- private recordApiUsage(authContext: WorkspaceAuthContext) {
+ private recordApiComplexityUsage(
+ authContext: WorkspaceAuthContext,
+ queryComplexity: number,
+ ) {
const apiType = getApiType();
if (!isDefined(apiType)) {
return;
}
- const spenders = buildUsageSpendersFromAuthContext(authContext);
-
- if (!isDefined(spenders.apiKeyId) && !isDefined(spenders.applicationId)) {
- return;
- }
-
this.usageRecorderService.accumulate(authContext.workspace.id, {
resourceType: UsageResourceType.API,
operationType: UsageOperationType.API_REQUEST,
- quantity: 1,
- unit: UsageUnit.REQUEST,
+ quantity: queryComplexity,
+ unit: UsageUnit.COMPLEXITY,
resourceContext: apiType,
- spenders,
+ spenders: buildUsageSpendersFromAuthContext(authContext),
});
}
@@ -624,7 +626,7 @@ export abstract class CommonBaseQueryRunnerService<
selectedFieldsResult: CommonSelectedFieldsResult,
args: CommonExtendedInput<Args>,
queryRunnerContext: CommonBaseQueryRunnerContext,
- ) {
+ ): number {
const maximumComplexity = this.twentyConfigService.get(
'COMMON_QUERY_COMPLEXITY_LIMIT',
);
@@ -654,5 +656,7 @@ export abstract class CommonBaseQueryRunnerService<
},
);
}
+
+ return queryComplexity;
}
}
diff --git a/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.service.ts b/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.service.ts
index fa2a72de562..ec2d8d61c75 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.service.ts
@@ -3,7 +3,10 @@
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
-import { isUsageOperationTypeValue } from 'twenty-shared/application';
+import {
+ isUsageOperationTypeValue,
+ type UsageOperationTypeValue,
+} from 'twenty-shared/application';
import { isDefined } from 'twenty-shared/utils';
import { type Repository } from 'typeorm';
@@ -17,10 +20,14 @@ import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
import { UsageRecorderService } from 'src/engine/core-modules/usage/services/usage-recorder.service';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
-// Each operation type has one canonical counting unit — matches how
-// `ai-billing.service.ts` emits native usage events.
+type AppChargeableOperationType =
+ (typeof UsageOperationType)[UsageOperationTypeValue];
+
+// An app sends a quantity and never a unit, so the platform names what the
+// number counts. Keyed on the app-facing vocabulary, so adding a value to
+// twenty-shared's USAGE_OPERATION_TYPES fails to compile until it has a unit.
const USAGE_UNIT_BY_OPERATION_TYPE: Record<
- Exclude<UsageOperationType, UsageOperationType.ALL>,
+ AppChargeableOperationType,
UsageUnit
> = {
[UsageOperationType.AI_CHAT_TOKEN]: UsageUnit.TOKEN,
@@ -30,13 +37,6 @@ const USAGE_UNIT_BY_OPERATION_TYPE: Record<
[UsageOperationType.WEB_SEARCH]: UsageUnit.INVOCATION,
[UsageOperationType.CALL_RECORDING]: UsageUnit.MINUTE,
[UsageOperationType.EMAIL_SEND]: UsageUnit.INVOCATION,
- [UsageOperationType.MESSAGE_CAMPAIGN_SEND]: UsageUnit.INVOCATION,
- [UsageOperationType.API_REQUEST]: UsageUnit.REQUEST,
- [UsageOperationType.WEBHOOK_CALL]: UsageUnit.REQUEST,
- [UsageOperationType.STORAGE_FILE]: UsageUnit.BYTE,
- [UsageOperationType.RECORD_WRITE]: UsageUnit.RECORD,
- // Platform-raised only; ApplicationRecurringChargeService sets its own unit.
- [UsageOperationType.SUBSCRIPTION]: UsageUnit.CREDIT,
};
// `workspaceId` + `applicationId` come from the application-access token,
@@ -116,7 +116,7 @@ export class AppBillingService {
workspaceId: string;
applicationId: string;
charge: ChargeDto;
- }): Promise<Exclude<UsageOperationType, UsageOperationType.ALL>> {
+ }): Promise<AppChargeableOperationType> {
if (!isDefined(charge.operation)) {
if (!isDefined(charge.operationType)) {
throw new BadRequestException(
diff --git a/packages/twenty-server/src/engine/core-modules/usage/enums/usage-unit.enum.ts b/packages/twenty-server/src/engine/core-modules/usage/enums/usage-unit.enum.ts
index 8a865240e5b..b11fa095e58 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/enums/usage-unit.enum.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/enums/usage-unit.enum.ts
@@ -10,4 +10,5 @@ export enum UsageUnit {
REQUEST = 'REQUEST',
SEAT = 'SEAT',
RECORD = 'RECORD',
+ COMPLEXITY = 'COMPLEXITY',
}