Skip to content

The open alternative to Salesforce, designed for AI.

feat(usage-limit): cap workspace records with a stock limit (#26147)

Etienne3b9f0d20f922
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index 188ba84d74d..22bee27667b 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -1595,6 +1595,7 @@ enum UsageResourceType {
LOGIC_FUNCTION
EMAIL
WEBHOOK
+ RECORD
}
enum UsageOperationType {
@@ -1609,6 +1610,7 @@ enum UsageOperationType {
API_REQUEST
WEBHOOK_CALL
STORAGE_FILE
+ RECORD_WRITE
SUBSCRIPTION
}
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index 49b50ddb3f6..23c91e378b2 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -1235,9 +1235,9 @@ export interface UsageQuotaDefinition {
__typename: 'UsageQuotaDefinition'
}
-export type UsageResourceType = 'AI' | 'WORKFLOW' | 'APP' | 'STORAGE' | 'API' | 'LOGIC_FUNCTION' | 'EMAIL' | 'WEBHOOK'
+export type UsageResourceType = 'AI' | 'WORKFLOW' | 'APP' | 'STORAGE' | 'API' | 'LOGIC_FUNCTION' | 'EMAIL' | 'WEBHOOK' | 'RECORD'
-export type UsageOperationType = 'ALL' | 'AI_CHAT_TOKEN' | 'AI_WORKFLOW_TOKEN' | 'WORKFLOW_EXECUTION' | 'CODE_EXECUTION' | 'WEB_SEARCH' | 'CALL_RECORDING' | 'EMAIL_SEND' | 'API_REQUEST' | 'WEBHOOK_CALL' | 'STORAGE_FILE' | 'SUBSCRIPTION'
+export type UsageOperationType = 'ALL' | 'AI_CHAT_TOKEN' | 'AI_WORKFLOW_TOKEN' | 'WORKFLOW_EXECUTION' | 'CODE_EXECUTION' | 'WEB_SEARCH' | 'CALL_RECORDING' | 'EMAIL_SEND' | 'API_REQUEST' | 'WEBHOOK_CALL' | 'STORAGE_FILE' | 'RECORD_WRITE' | 'SUBSCRIPTION'
export interface UsageQuotaDefinitions {
definitions: UsageQuotaDefinition[]
@@ -10772,7 +10772,8 @@ export const enumUsageResourceType = {
API: 'API' as const,
LOGIC_FUNCTION: 'LOGIC_FUNCTION' as const,
EMAIL: 'EMAIL' as const,
- WEBHOOK: 'WEBHOOK' as const
+ WEBHOOK: 'WEBHOOK' as const,
+ RECORD: 'RECORD' as const
}
export const enumUsageOperationType = {
@@ -10787,6 +10788,7 @@ export const enumUsageOperationType = {
API_REQUEST: 'API_REQUEST' as const,
WEBHOOK_CALL: 'WEBHOOK_CALL' as const,
STORAGE_FILE: 'STORAGE_FILE' as const,
+ RECORD_WRITE: 'RECORD_WRITE' as const,
SUBSCRIPTION: 'SUBSCRIPTION' as const
}
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index edcf62db1a0..f1087af0ac1 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -6885,6 +6885,7 @@ export enum UsageOperationType {
CALL_RECORDING = 'CALL_RECORDING',
CODE_EXECUTION = 'CODE_EXECUTION',
EMAIL_SEND = 'EMAIL_SEND',
+ RECORD_WRITE = 'RECORD_WRITE',
STORAGE_FILE = 'STORAGE_FILE',
SUBSCRIPTION = 'SUBSCRIPTION',
WEBHOOK_CALL = 'WEBHOOK_CALL',
@@ -6948,6 +6949,7 @@ export enum UsageResourceType {
APP = 'APP',
EMAIL = 'EMAIL',
LOGIC_FUNCTION = 'LOGIC_FUNCTION',
+ RECORD = 'RECORD',
STORAGE = 'STORAGE',
WEBHOOK = 'WEBHOOK',
WORKFLOW = 'WORKFLOW'
diff --git a/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitOperationTypeIcons.ts b/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitOperationTypeIcons.ts
index c163a4f0c62..a1ea199d371 100644
--- a/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitOperationTypeIcons.ts
+++ b/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitOperationTypeIcons.ts
@@ -1,4 +1,5 @@
import {
+ IconAddressBook,
IconApi,
IconCode,
type IconComponent,
@@ -31,5 +32,6 @@ export const USAGE_LIMIT_OPERATION_TYPE_ICONS: Record<
[UsageOperationType.API_REQUEST]: IconApi,
[UsageOperationType.WEBHOOK_CALL]: IconWebhook,
[UsageOperationType.STORAGE_FILE]: IconFiles,
+ [UsageOperationType.RECORD_WRITE]: IconAddressBook,
[UsageOperationType.SUBSCRIPTION]: IconRepeat,
};
diff --git a/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitResourceTypeIcons.ts b/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitResourceTypeIcons.ts
index 77420460f2d..3a2ee100a89 100644
--- a/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitResourceTypeIcons.ts
+++ b/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitResourceTypeIcons.ts
@@ -1,4 +1,5 @@
import {
+ IconAddressBook,
IconApi,
IconApps,
IconFiles,
@@ -20,6 +21,7 @@ export const USAGE_LIMIT_RESOURCE_TYPE_ICONS: Record<
[UsageResourceType.APP]: IconApps,
[UsageResourceType.EMAIL]: IconMail,
[UsageResourceType.LOGIC_FUNCTION]: IconSettingsAutomation,
+ [UsageResourceType.RECORD]: IconAddressBook,
[UsageResourceType.STORAGE]: IconFiles,
[UsageResourceType.WEBHOOK]: IconWebhook,
[UsageResourceType.WORKFLOW]: IconSettingsAutomation,
diff --git a/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitResourceTypeLabels.ts b/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitResourceTypeLabels.ts
index b613740ce5a..38af87a6813 100644
--- a/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitResourceTypeLabels.ts
+++ b/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitResourceTypeLabels.ts
@@ -12,6 +12,7 @@ export const USAGE_LIMIT_RESOURCE_TYPE_LABELS: Record<
[UsageResourceType.APP]: msg`Apps`,
[UsageResourceType.EMAIL]: msg`Email`,
[UsageResourceType.LOGIC_FUNCTION]: msg`Logic functions`,
+ [UsageResourceType.RECORD]: msg`Records`,
[UsageResourceType.STORAGE]: msg`Storage`,
[UsageResourceType.WEBHOOK]: msg`Webhooks`,
[UsageResourceType.WORKFLOW]: msg`Workflows`,
diff --git a/packages/twenty-front/src/modules/settings/usage/constants/UsageOperationTypeLabels.ts b/packages/twenty-front/src/modules/settings/usage/constants/UsageOperationTypeLabels.ts
index a57413a5248..9a1fa0f97e0 100644
--- a/packages/twenty-front/src/modules/settings/usage/constants/UsageOperationTypeLabels.ts
+++ b/packages/twenty-front/src/modules/settings/usage/constants/UsageOperationTypeLabels.ts
@@ -20,5 +20,6 @@ export const USAGE_OPERATION_TYPE_LABELS: Record<
[UsageOperationType.API_REQUEST]: msg`API Request`,
[UsageOperationType.WEBHOOK_CALL]: msg`Webhook Call`,
[UsageOperationType.STORAGE_FILE]: msg`File Storage`,
+ [UsageOperationType.RECORD_WRITE]: msg`Records`,
[UsageOperationType.SUBSCRIPTION]: msg`Subscription`,
};
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 c98ab27174c..33f721eb37c 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
@@ -32,6 +32,7 @@ const USAGE_UNIT_BY_OPERATION_TYPE: Record<
[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,
};
diff --git a/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts b/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
index 5b562d0348b..f32d0e64caa 100644
--- a/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
+++ b/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
@@ -699,6 +699,16 @@ export class ConfigVariables {
@IsOptional()
WORKSPACE_STORAGE_LIMIT_BYTES: number = 100 * 1024 * 1024 * 1024;
+ @ConfigVariablesMetadata({
+ group: ConfigVariablesGroup.STORAGE_CONFIG,
+ description:
+ 'Maximum number of records a single workspace may hold across its objects, system objects other than messages and calendar events left out, soft-deleted records included. A write that would cross it is refused',
+ type: ConfigVariableType.NUMBER,
+ })
+ @CastToPositiveNumber()
+ @IsOptional()
+ WORKSPACE_RECORD_LIMIT: number = 10_000_000;
+
@ConfigVariablesMetadata({
group: ConfigVariablesGroup.LOGIC_FUNCTION_CONFIG,
description: 'Type of function execution (local or Lambda)',
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/count-live-records-query.constant.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/count-live-records-query.constant.ts
new file mode 100644
index 00000000000..0d4a3637407
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/count-live-records-query.constant.ts
@@ -0,0 +1,5 @@
+export const COUNT_LIVE_RECORDS_QUERY = `
+ SELECT COALESCE(SUM(n_live_tup), 0)::bigint AS quantity
+ FROM pg_stat_user_tables
+ WHERE schemaname = $1 AND relname = ANY($2)
+`;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/record-stock-tracked-system-object-universal-identifiers.constant.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/record-stock-tracked-system-object-universal-identifiers.constant.ts
new file mode 100644
index 00000000000..e8c6739c17d
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/record-stock-tracked-system-object-universal-identifiers.constant.ts
@@ -0,0 +1,7 @@
+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
+
+export const RECORD_STOCK_TRACKED_SYSTEM_OBJECT_UNIVERSAL_IDENTIFIERS: string[] =
+ [
+ STANDARD_OBJECTS.message.universalIdentifier,
+ STANDARD_OBJECTS.calendarEvent.universalIdentifier,
+ ];
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 66cbedaf153..3260b1f60cf 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
@@ -109,4 +109,19 @@ export const USAGE_LIMIT_DEFINITIONS = {
],
},
},
+ [UsageResourceType.RECORD]: {
+ stock: {
+ allowedOperationTypes: [UsageOperationType.RECORD_WRITE],
+ allowedSpenderTypes: ['workspace'],
+ allowedMeters: ['quantity'],
+ defaults: [
+ {
+ spenderType: 'workspace',
+ meter: 'quantity',
+ limitValueConfigVariable: 'WORKSPACE_RECORD_LIMIT',
+ isOverridable: true,
+ },
+ ],
+ },
+ },
} satisfies Record<UsageResourceType, UsageLimitDefinitions>;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-stock.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-stock.service.ts
index 767b5141f85..19a74b1ccd7 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-stock.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-stock.service.ts
@@ -37,6 +37,7 @@ import { buildStockScopeKey } from 'src/engine/core-modules/usage-limit/utils/bu
import { buildStockWarmLockKey } from 'src/engine/core-modules/usage-limit/utils/build-stock-warm-lock-key.util';
import { findExhaustedStockCounter } from 'src/engine/core-modules/usage-limit/utils/find-exhausted-stock-counter.util';
import { findUsageLimitDefinition } from 'src/engine/core-modules/usage-limit/utils/find-usage-limit-definition.util';
+import { getStockExhaustedUserFriendlyMessage } from 'src/engine/core-modules/usage-limit/utils/get-stock-exhausted-user-friendly-message.util';
import { isStockLimit } from 'src/engine/core-modules/usage-limit/utils/is-stock-limit.util';
import { isStockResourceType } from 'src/engine/core-modules/usage-limit/utils/is-stock-resource-type.util';
import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
@@ -99,7 +100,12 @@ export class UsageLimitStockService {
throw new UsageLimitException(
`${exhausted.counter.resourceType} limit reached for this workspace`,
UsageLimitExceptionCode.STOCK_EXHAUSTED,
- { exhaustedScope: buildStockExhaustedScope(exhausted) },
+ {
+ userFriendlyMessage: getStockExhaustedUserFriendlyMessage(
+ exhausted.counter.resourceType,
+ ),
+ exhaustedScope: buildStockExhaustedScope(exhausted),
+ },
);
}
} catch (error) {
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/workspace-record-stock.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/workspace-record-stock.service.ts
new file mode 100644
index 00000000000..ffb07c2e335
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/workspace-record-stock.service.ts
@@ -0,0 +1,104 @@
+import { Injectable } from '@nestjs/common';
+import { InjectDataSource } from '@nestjs/typeorm';
+
+import { DataSource } from 'typeorm';
+
+import { COUNT_LIVE_RECORDS_QUERY } from 'src/engine/core-modules/usage-limit/constants/count-live-records-query.constant';
+import { UsageLimitStockService } from 'src/engine/core-modules/usage-limit/services/usage-limit-stock.service';
+import { buildRecordStockTableNames } from 'src/engine/core-modules/usage-limit/utils/build-record-stock-table-names.util';
+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 FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';
+import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
+import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
+
+const RECORD_STOCK_SCOPE = {
+ resourceType: UsageResourceType.RECORD,
+ operationType: UsageOperationType.RECORD_WRITE,
+ spenders: {},
+};
+
+@Injectable()
+export class WorkspaceRecordStockService {
+ constructor(
+ private readonly usageLimitStockService: UsageLimitStockService,
+ @InjectDataSource()
+ private readonly coreDataSource: DataSource,
+ ) {}
+
+ async assertRecordStockAvailable({
+ workspaceId,
+ quantity,
+ flatObjectMetadataMaps,
+ }: {
+ workspaceId: string;
+ quantity: number;
+ flatObjectMetadataMaps: FlatEntityMaps<FlatObjectMetadata>;
+ }): Promise<void> {
+ if (quantity <= 0) {
+ return;
+ }
+
+ await this.usageLimitStockService.assertStockAvailable({
+ ...RECORD_STOCK_SCOPE,
+ workspaceId,
+ cost: { quantity },
+ computeUsedStock: () =>
+ this.computeRecordUsedStock({ workspaceId, flatObjectMetadataMaps }),
+ });
+ }
+
+ async acquireRecordStock({
+ workspaceId,
+ quantity,
+ }: {
+ workspaceId: string;
+ quantity: number;
+ }): Promise<void> {
+ if (quantity <= 0) {
+ return;
+ }
+
+ await this.usageLimitStockService.acquireStock({
+ ...RECORD_STOCK_SCOPE,
+ workspaceId,
+ cost: { quantity },
+ });
+ }
+
+ async releaseRecordStock({
+ workspaceId,
+ quantity,
+ }: {
+ workspaceId: string;
+ quantity: number;
+ }): Promise<void> {
+ if (quantity <= 0) {
+ return;
+ }
+
+ await this.usageLimitStockService.releaseStock({
+ ...RECORD_STOCK_SCOPE,
+ workspaceId,
+ cost: { quantity },
+ });
+ }
+
+ private async computeRecordUsedStock({
+ workspaceId,
+ flatObjectMetadataMaps,
+ }: {
+ workspaceId: string;
+ flatObjectMetadataMaps: FlatEntityMaps<FlatObjectMetadata>;
+ }): Promise<{ quantity: number; bytes: number }> {
+ const [used] = await this.coreDataSource.query<{ quantity: string }[]>(
+ COUNT_LIVE_RECORDS_QUERY,
+ [
+ getWorkspaceSchemaName(workspaceId),
+ buildRecordStockTableNames(flatObjectMetadataMaps),
+ ],
+ );
+
+ return { quantity: Number(used?.quantity ?? 0), bytes: 0 };
+ }
+}
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 72b2e81aa27..808dbcc9d84 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
@@ -17,6 +17,7 @@ import { UsageQuotaDefinitionService } from 'src/engine/core-modules/usage-limit
import { UsageLimitEntitlementService } from 'src/engine/core-modules/usage-limit/services/usage-limit-entitlement.service';
import { UsageLimitSpeedService } from 'src/engine/core-modules/usage-limit/services/usage-limit-speed.service';
import { UsageLimitStockService } from 'src/engine/core-modules/usage-limit/services/usage-limit-stock.service';
+import { WorkspaceRecordStockService } from 'src/engine/core-modules/usage-limit/services/workspace-record-stock.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 { UsageLimitsCacheService } from 'src/engine/core-modules/usage-limit/services/usage-limits-cache.service';
@@ -46,6 +47,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
UsageLimitQuotaService,
UsageLimitSpeedService,
UsageLimitStockService,
+ WorkspaceRecordStockService,
UsageLimitEntitlementService,
UsageLimitsCacheService,
UsagePeriodService,
@@ -65,6 +67,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
UsageLimitQuotaService,
UsageLimitSpeedService,
UsageLimitStockService,
+ WorkspaceRecordStockService,
UsageLimitsCacheService,
],
})
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-record-stock-table-names.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-record-stock-table-names.util.spec.ts
new file mode 100644
index 00000000000..97360d13645
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-record-stock-table-names.util.spec.ts
@@ -0,0 +1,62 @@
+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
+
+import { buildRecordStockTableNames } from 'src/engine/core-modules/usage-limit/utils/build-record-stock-table-names.util';
+import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';
+import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
+import { TWENTY_STANDARD_APPLICATION } from 'src/engine/workspace-manager/twenty-standard-application/constants/twenty-standard-applications';
+
+const buildFlatObjectMetadata = (
+ overrides: Partial<FlatObjectMetadata>,
+): FlatObjectMetadata =>
+ ({
+ universalIdentifier: overrides.nameSingular,
+ isSystem: false,
+ applicationUniversalIdentifier:
+ TWENTY_STANDARD_APPLICATION.universalIdentifier,
+ ...overrides,
+ }) as FlatObjectMetadata;
+
+const buildMaps = (
+ flatObjectMetadatas: FlatObjectMetadata[],
+): FlatEntityMaps<FlatObjectMetadata> =>
+ ({
+ byUniversalIdentifier: Object.fromEntries(
+ flatObjectMetadatas.map((flatObjectMetadata) => [
+ flatObjectMetadata.universalIdentifier,
+ flatObjectMetadata,
+ ]),
+ ),
+ }) as FlatEntityMaps<FlatObjectMetadata>;
+
+describe('buildRecordStockTableNames', () => {
+ it('names the table of every tracked object', () => {
+ const tableNames = buildRecordStockTableNames(
+ buildMaps([
+ buildFlatObjectMetadata({ nameSingular: 'person' }),
+ buildFlatObjectMetadata({
+ nameSingular: 'rocket',
+ applicationUniversalIdentifier: 'custom-app',
+ }),
+ buildFlatObjectMetadata({
+ nameSingular: 'message',
+ isSystem: true,
+ universalIdentifier: STANDARD_OBJECTS.message.universalIdentifier,
+ }),
+ buildFlatObjectMetadata({
+ nameSingular: 'timelineActivity',
+ isSystem: true,
+ }),
+ ]),
+ );
+
+ expect(tableNames).toEqual(['person', '_rocket', 'message']);
+ });
+
+ it('skips holes in the map', () => {
+ const maps = buildMaps([]);
+
+ maps.byUniversalIdentifier.missing = undefined;
+
+ expect(buildRecordStockTableNames(maps)).toEqual([]);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/is-record-stock-tracked-object.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/is-record-stock-tracked-object.util.spec.ts
new file mode 100644
index 00000000000..d0b9f44be8b
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/is-record-stock-tracked-object.util.spec.ts
@@ -0,0 +1,33 @@
+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
+
+import { isRecordStockTrackedObject } from 'src/engine/core-modules/usage-limit/utils/is-record-stock-tracked-object.util';
+
+describe('isRecordStockTrackedObject', () => {
+ it('tracks every non-system object', () => {
+ expect(
+ isRecordStockTrackedObject({
+ isSystem: false,
+ universalIdentifier: 'custom-object',
+ }),
+ ).toBe(true);
+ });
+
+ it('leaves system objects out of the record stock', () => {
+ expect(
+ isRecordStockTrackedObject({
+ isSystem: true,
+ universalIdentifier:
+ STANDARD_OBJECTS.timelineActivity.universalIdentifier,
+ }),
+ ).toBe(false);
+ });
+
+ it.each([
+ ['message', STANDARD_OBJECTS.message.universalIdentifier],
+ ['calendarEvent', STANDARD_OBJECTS.calendarEvent.universalIdentifier],
+ ])('still tracks the %s system object', (_, universalIdentifier) => {
+ expect(
+ isRecordStockTrackedObject({ isSystem: true, universalIdentifier }),
+ ).toBe(true);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-record-stock-table-names.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-record-stock-table-names.util.ts
new file mode 100644
index 00000000000..c2504e34085
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-record-stock-table-names.util.ts
@@ -0,0 +1,14 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';
+import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
+import { isRecordStockTrackedObject } from 'src/engine/core-modules/usage-limit/utils/is-record-stock-tracked-object.util';
+import { computeObjectTargetTable } from 'src/engine/utils/compute-object-target-table.util';
+
+export const buildRecordStockTableNames = (
+ flatObjectMetadataMaps: FlatEntityMaps<FlatObjectMetadata>,
+): string[] =>
+ Object.values(flatObjectMetadataMaps.byUniversalIdentifier)
+ .filter(isDefined)
+ .filter(isRecordStockTrackedObject)
+ .map(computeObjectTargetTable);
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-stock-exhausted-user-friendly-message.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-stock-exhausted-user-friendly-message.util.ts
new file mode 100644
index 00000000000..51c8e82d725
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-stock-exhausted-user-friendly-message.util.ts
@@ -0,0 +1,17 @@
+import { type MessageDescriptor } from '@lingui/core';
+import { msg } from '@lingui/core/macro';
+
+import { type StockResourceType } from 'src/engine/core-modules/usage-limit/types/stock-resource-type.type';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+
+const STOCK_EXHAUSTED_USER_FRIENDLY_MESSAGES: Record<
+ StockResourceType,
+ MessageDescriptor
+> = {
+ [UsageResourceType.STORAGE]: msg`This workspace has reached its storage limit.`,
+ [UsageResourceType.RECORD]: msg`This workspace has reached its record limit.`,
+};
+
+export const getStockExhaustedUserFriendlyMessage = (
+ resourceType: StockResourceType,
+): MessageDescriptor => STOCK_EXHAUSTED_USER_FRIENDLY_MESSAGES[resourceType];
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-record-stock-tracked-object.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-record-stock-tracked-object.util.ts
new file mode 100644
index 00000000000..e7504079ff1
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-record-stock-tracked-object.util.ts
@@ -0,0 +1,13 @@
+import { RECORD_STOCK_TRACKED_SYSTEM_OBJECT_UNIVERSAL_IDENTIFIERS } from 'src/engine/core-modules/usage-limit/constants/record-stock-tracked-system-object-universal-identifiers.constant';
+import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
+
+export const isRecordStockTrackedObject = (
+ flatObjectMetadata: Pick<
+ FlatObjectMetadata,
+ 'isSystem' | 'universalIdentifier'
+ >,
+): boolean =>
+ !flatObjectMetadata.isSystem ||
+ RECORD_STOCK_TRACKED_SYSTEM_OBJECT_UNIVERSAL_IDENTIFIERS.includes(
+ flatObjectMetadata.universalIdentifier,
+ );
diff --git a/packages/twenty-server/src/engine/core-modules/usage/enums/usage-operation-type.enum.ts b/packages/twenty-server/src/engine/core-modules/usage/enums/usage-operation-type.enum.ts
index 5ed2c4c9aad..e590949bf55 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/enums/usage-operation-type.enum.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/enums/usage-operation-type.enum.ts
@@ -17,6 +17,7 @@ export enum UsageOperationType {
API_REQUEST = 'API_REQUEST',
WEBHOOK_CALL = 'WEBHOOK_CALL',
STORAGE_FILE = 'STORAGE_FILE',
+ RECORD_WRITE = 'RECORD_WRITE',
// Platform-raised, once per billing period. Also out of
// USAGE_OPERATION_TYPES: an app declares the amount, it never charges this.
SUBSCRIPTION = 'SUBSCRIPTION',
diff --git a/packages/twenty-server/src/engine/core-modules/usage/enums/usage-resource-type.enum.ts b/packages/twenty-server/src/engine/core-modules/usage/enums/usage-resource-type.enum.ts
index 21c8727e39a..e600ddb3058 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/enums/usage-resource-type.enum.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/enums/usage-resource-type.enum.ts
@@ -11,6 +11,7 @@ export enum UsageResourceType {
LOGIC_FUNCTION = 'LOGIC_FUNCTION',
EMAIL = 'EMAIL',
WEBHOOK = 'WEBHOOK',
+ RECORD = 'RECORD',
}
registerEnumType(UsageResourceType, {
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 a363ff86434..8a865240e5b 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
@@ -9,4 +9,5 @@ export enum UsageUnit {
BYTE = 'BYTE',
REQUEST = 'REQUEST',
SEAT = 'SEAT',
+ RECORD = 'RECORD',
}
diff --git a/packages/twenty-server/src/engine/twenty-orm/datasource/workspace-data-source.service.ts b/packages/twenty-server/src/engine/twenty-orm/datasource/workspace-data-source.service.ts
index 5e122a473c0..b5d77c17f1c 100644
--- a/packages/twenty-server/src/engine/twenty-orm/datasource/workspace-data-source.service.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/datasource/workspace-data-source.service.ts
@@ -15,6 +15,7 @@ import {
DatabasePoolName,
} from 'src/database/typeorm/database-pool-metrics.service';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
+import { WorkspaceRecordStockService } from 'src/engine/core-modules/usage-limit/services/workspace-record-stock.service';
import { type WorkspaceInternalContext } from 'src/engine/twenty-orm/interfaces/workspace-internal-context.interface';
import { getWorkspaceContext } from 'src/engine/twenty-orm/storage/orm-workspace-context.storage';
import { WorkspaceDataSource } from 'src/engine/twenty-orm/datasource/workspace-data-source';
@@ -51,6 +52,7 @@ export class WorkspaceDataSourceService
@InjectDataSource()
private readonly coreDataSource: DataSource,
private readonly databasePoolMetricsService: DatabasePoolMetricsService,
+ private readonly workspaceRecordStockService: WorkspaceRecordStockService,
) {}
onModuleInit(): void {
@@ -124,6 +126,7 @@ export class WorkspaceDataSourceService
userWorkspaceRoleMap: workspaceContext.userWorkspaceRoleMap,
apiKeyRoleMap: workspaceContext.apiKeyRoleMap,
eventEmitterService: this.workspaceEventEmitter,
+ recordStock: this.workspaceRecordStockService,
coreDataSource: this.coreDataSource,
};
}
diff --git a/packages/twenty-server/src/engine/twenty-orm/datasource/workspace-data-source.ts b/packages/twenty-server/src/engine/twenty-orm/datasource/workspace-data-source.ts
index 2c3102a351b..f63c042df08 100644
--- a/packages/twenty-server/src/engine/twenty-orm/datasource/workspace-data-source.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/datasource/workspace-data-source.ts
@@ -87,6 +87,20 @@ export class WorkspaceDataSource {
),
),
},
+ recordStock: {
+ assertRecordStockAvailable: (args) =>
+ this.internalContext.recordStock.assertRecordStockAvailable(args),
+ acquireRecordStock: async (args) => {
+ afterCommit(() =>
+ this.internalContext.recordStock.acquireRecordStock(args),
+ );
+ },
+ releaseRecordStock: async (args) => {
+ afterCommit(() =>
+ this.internalContext.recordStock.releaseRecordStock(args),
+ );
+ },
+ },
};
const result = await this.runInClientTransaction((executor) =>
work({
diff --git a/packages/twenty-server/src/engine/twenty-orm/interfaces/workspace-internal-context.interface.ts b/packages/twenty-server/src/engine/twenty-orm/interfaces/workspace-internal-context.interface.ts
index 5ca82777cce..01a331d5266 100644
--- a/packages/twenty-server/src/engine/twenty-orm/interfaces/workspace-internal-context.interface.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/interfaces/workspace-internal-context.interface.ts
@@ -2,6 +2,7 @@ import { type DataSource } from 'typeorm';
import { type FeatureFlagKey } from 'twenty-shared/types';
import { type BillingEntitlements } from 'src/engine/core-modules/billing/types/billing-entitlements.type';
+import { type WorkspaceRecordStockService } from 'src/engine/core-modules/usage-limit/services/workspace-record-stock.service';
import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';
import { type OrmFlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/orm-flat-field-metadata.type';
import { type FlatIndexMetadata } from 'src/engine/metadata-modules/flat-index-metadata/types/flat-index-metadata.type';
@@ -25,5 +26,9 @@ export interface WorkspaceInternalContext {
userWorkspaceRoleMap: UserWorkspaceRoleMap;
apiKeyRoleMap: Record<string, string>;
eventEmitterService: Pick<WorkspaceEventEmitter, 'emitDatabaseBatchEvent'>;
+ recordStock: Pick<
+ WorkspaceRecordStockService,
+ 'assertRecordStockAvailable' | 'acquireRecordStock' | 'releaseRecordStock'
+ >;
coreDataSource: DataSource;
}
diff --git a/packages/twenty-server/src/engine/twenty-orm/repository/workspace-repository.ts b/packages/twenty-server/src/engine/twenty-orm/repository/workspace-repository.ts
index 1403cb52a78..cfe6287bb74 100644
--- a/packages/twenty-server/src/engine/twenty-orm/repository/workspace-repository.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/repository/workspace-repository.ts
@@ -17,6 +17,7 @@ import {
import { DatabaseEventAction } from 'src/engine/api/graphql/graphql-query-runner/enums/database-event-action';
import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
+import { isRecordStockTrackedObject } from 'src/engine/core-modules/usage-limit/utils/is-record-stock-tracked-object.util';
import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
import {
PermissionsException,
@@ -964,6 +965,8 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
affectedRecords: formattedRecords,
});
+ await this.assertRecordStockAvailable(recordsToInsert.length);
+
const sql = buildInsertStatement({
tableShape: this.options.tableShape,
columnNames,
@@ -974,6 +977,8 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
const rawRows = await this.executeRaw<ObjectRecord>(sql, parameters);
+ await this.acquireRecordStock(rawRows.length);
+
if (isDefined(filesFieldFileIds)) {
await this.filesFieldSync.updateFileEntityRecords(filesFieldFileIds);
}
@@ -1209,6 +1214,41 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
};
}
+ private async assertRecordStockAvailable(quantity: number): Promise<void> {
+ if (!isRecordStockTrackedObject(this.options.flatObjectMetadata)) {
+ return;
+ }
+
+ await this.options.internalContext.recordStock.assertRecordStockAvailable({
+ workspaceId: this.options.internalContext.workspaceId,
+ quantity,
+ flatObjectMetadataMaps:
+ this.options.internalContext.flatObjectMetadataMaps,
+ });
+ }
+
+ private async acquireRecordStock(quantity: number): Promise<void> {
+ if (!isRecordStockTrackedObject(this.options.flatObjectMetadata)) {
+ return;
+ }
+
+ await this.options.internalContext.recordStock.acquireRecordStock({
+ workspaceId: this.options.internalContext.workspaceId,
+ quantity,
+ });
+ }
+
+ private async releaseRecordStock(quantity: number): Promise<void> {
+ if (!isRecordStockTrackedObject(this.options.flatObjectMetadata)) {
+ return;
+ }
+
+ await this.options.internalContext.recordStock.releaseRecordStock({
+ workspaceId: this.options.internalContext.workspaceId,
+ quantity,
+ });
+ }
+
private async emitCreateEvents(insertedIds: string[]): Promise<void> {
if (insertedIds.length === 0 || this.options.shouldSkipEventEmission) {
return;
@@ -1535,6 +1575,10 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
setColumns,
});
+ if (kind === 'delete') {
+ await this.releaseRecordStock(mutationResult.generatedMaps.length);
+ }
+
if (isDefined(filesFieldFileIds)) {
await this.filesFieldSync.updateFileEntityRecords(filesFieldFileIds);
}
diff --git a/packages/twenty-server/src/engine/twenty-orm/twenty-orm.module.ts b/packages/twenty-server/src/engine/twenty-orm/twenty-orm.module.ts
index 92fd20e241e..896a9f7edfe 100644
--- a/packages/twenty-server/src/engine/twenty-orm/twenty-orm.module.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/twenty-orm.module.ts
@@ -6,6 +6,7 @@ import { WorkspaceBillingEntitlementsCacheModule } from 'src/engine/core-modules
import { ApplicationEntity } from 'src/engine/core-modules/application/application.entity';
import { FeatureFlagEntity } from 'src/engine/core-modules/feature-flag/feature-flag.entity';
import { TwentyConfigModule } from 'src/engine/core-modules/twenty-config/twenty-config.module';
+import { UsageLimitModule } from 'src/engine/core-modules/usage-limit/usage-limit.module';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { FieldMetadataEntity } from 'src/engine/metadata-modules/field-metadata/field-metadata.entity';
import { WorkspaceManyOrAllFlatEntityMapsCacheModule } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.module';
@@ -36,6 +37,7 @@ import { WorkspaceEventEmitterModule } from 'src/engine/workspace-event-emitter/
WorkspaceFeatureFlagsMapCacheModule,
WorkspaceBillingEntitlementsCacheModule,
TwentyConfigModule,
+ UsageLimitModule,
WorkspaceEventEmitterModule,
WorkspaceCacheModule,
RecordSharingFeatureModule,
diff --git a/packages/twenty-server/test/integration/usage-limit/record-stock-limit.integration-spec.ts b/packages/twenty-server/test/integration/usage-limit/record-stock-limit.integration-spec.ts
new file mode 100644
index 00000000000..40fc59c2fc9
--- /dev/null
+++ b/packages/twenty-server/test/integration/usage-limit/record-stock-limit.integration-spec.ts
@@ -0,0 +1,234 @@
+import { createManyOperationFactory } from 'test/integration/graphql/utils/create-many-operation-factory.util';
+import { deleteManyOperationFactory } from 'test/integration/graphql/utils/delete-many-operation-factory.util';
+import { destroyManyOperationFactory } from 'test/integration/graphql/utils/destroy-many-operation-factory.util';
+import { makeGraphqlAPIRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
+import { expectEventually } from 'test/integration/utils/expect-eventually.util';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';
+
+import { createClient } from 'redis';
+import { type Repository } from 'typeorm';
+import { v4 } from 'uuid';
+
+import { RECORD_STOCK_TRACKED_SYSTEM_OBJECT_UNIVERSAL_IDENTIFIERS } from 'src/engine/core-modules/usage-limit/constants/record-stock-tracked-system-object-universal-identifiers.constant';
+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 { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+
+const SCHEMA_NAME = getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID);
+const HEADROOM = 2;
+const STATS_FLUSH_TIMEOUT_MS = 30_000;
+
+describe('Record stock limit', () => {
+ let usageLimitRepository: Repository<UsageLimitEntity>;
+ let redis: Awaited<ReturnType<typeof createClient>>;
+ let usageLimitId: string;
+ let baselineRecordCount: number;
+ const createdRocketIds: string[] = [];
+
+ const createRockets = async (count: number) => {
+ const ids = Array.from({ length: count }, () => v4());
+
+ createdRocketIds.push(...ids);
+
+ return makeGraphqlAPIRequest(
+ createManyOperationFactory({
+ objectMetadataSingularName: 'rocket',
+ objectMetadataPluralName: 'rockets',
+ gqlFields: 'id',
+ data: ids.map((id) => ({ id, name: 'Record stock test' })),
+ }),
+ );
+ };
+
+ const softDeleteRockets = (ids: string[]) =>
+ makeGraphqlAPIRequest(
+ deleteManyOperationFactory({
+ objectMetadataSingularName: 'rocket',
+ objectMetadataPluralName: 'rockets',
+ gqlFields: 'id',
+ filter: { id: { in: ids } },
+ }),
+ );
+
+ const destroyRockets = (ids: string[]) =>
+ makeGraphqlAPIRequest(
+ destroyManyOperationFactory({
+ objectMetadataSingularName: 'rocket',
+ objectMetadataPluralName: 'rockets',
+ gqlFields: 'id',
+ filter: { id: { in: ids } },
+ }),
+ );
+
+ const findTrackedTableNames = async (): Promise<string[]> => {
+ const rows: { nameSingular: string; isCustom: boolean }[] =
+ await global.testDataSource.query(
+ `SELECT "nameSingular", "applicationId" <> (
+ SELECT "applicationId" FROM core."objectMetadata"
+ WHERE "workspaceId" = $1 AND "nameSingular" = 'person'
+ ) AS "isCustom"
+ FROM core."objectMetadata"
+ WHERE "workspaceId" = $1
+ AND (NOT "isSystem" OR "universalIdentifier" = ANY($2))`,
+ [
+ SEED_APPLE_WORKSPACE_ID,
+ RECORD_STOCK_TRACKED_SYSTEM_OBJECT_UNIVERSAL_IDENTIFIERS,
+ ],
+ );
+
+ return rows.map(({ nameSingular, isCustom }) =>
+ isCustom ? `_${nameSingular}` : nameSingular,
+ );
+ };
+
+ const countRecords = async (): Promise<number> => {
+ const [row]: { quantity: string }[] = await global.testDataSource.query(
+ `SELECT COALESCE(SUM(n_live_tup), 0)::bigint AS quantity
+ FROM pg_stat_user_tables
+ WHERE schemaname = $1 AND relname = ANY($2)`,
+ [SCHEMA_NAME, await findTrackedTableNames()],
+ );
+
+ return Number(row.quantity);
+ };
+
+ const waitForRecordCount = (expected: number) =>
+ expectEventually(
+ async () => {
+ expect(await countRecords()).toBe(expected);
+ },
+ { timeoutMs: STATS_FLUSH_TIMEOUT_MS },
+ );
+
+ const waitForStatsToSettle = async (): Promise<number> => {
+ let previous = await countRecords();
+
+ for (;;) {
+ await new Promise((resolve) => setTimeout(resolve, 1_500));
+
+ const current = await countRecords();
+
+ if (current === previous) {
+ return current;
+ }
+
+ previous = current;
+ }
+ };
+
+ const dropKeys = async (pattern: string) => {
+ const keys = await redis.keys(pattern);
+
+ if (keys.length > 0) {
+ await redis.del(keys);
+ }
+ };
+
+ const dropStockCounter = () =>
+ dropKeys(`*{${SEED_APPLE_WORKSPACE_ID}}:stock:RECORD:*`);
+
+ const refreshUsageLimitsCache = () =>
+ getAppProviderByClassName<WorkspaceCacheService>(
+ 'WorkspaceCacheService',
+ ).invalidateAndRecompute(SEED_APPLE_WORKSPACE_ID, ['usageLimits']);
+
+ const expectRefused = (response: { body: { errors?: unknown[] } }) => {
+ expect(
+ (response.body.errors?.[0] as { extensions?: { subCode?: string } })
+ ?.extensions?.subCode,
+ ).toBe('STOCK_EXHAUSTED');
+ };
+
+ const expectAdmitted = (response: { body: { errors?: unknown[] } }) => {
+ expect(response.body.errors).toBeUndefined();
+ };
+
+ beforeAll(async () => {
+ usageLimitRepository =
+ getCoreRepository<UsageLimitEntity>(UsageLimitEntity);
+ redis = await createClient({ url: process.env.REDIS_URL }).connect();
+
+ await usageLimitRepository.delete({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ resourceType: UsageResourceType.RECORD,
+ });
+ baselineRecordCount = await waitForStatsToSettle();
+
+ const [usageLimit] = await usageLimitRepository.save([
+ {
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ resourceType: UsageResourceType.RECORD,
+ operationType: UsageOperationType.RECORD_WRITE,
+ spenderType: 'workspace',
+ spenderId: '',
+ limitKind: 'stock',
+ periodCount: 1,
+ periodUnit: 'lifetime',
+ meter: 'quantity',
+ limitValue: baselineRecordCount + HEADROOM,
+ burstValue: null,
+ },
+ ]);
+
+ usageLimitId = usageLimit.id;
+
+ await refreshUsageLimitsCache();
+ });
+
+ beforeEach(async () => {
+ await waitForRecordCount(baselineRecordCount);
+ await dropStockCounter();
+ }, STATS_FLUSH_TIMEOUT_MS + 5_000);
+
+ afterEach(async () => {
+ if (createdRocketIds.length > 0) {
+ await global.testDataSource.query(
+ `DELETE FROM "${SCHEMA_NAME}"."_rocket" WHERE id = ANY($1)`,
+ [createdRocketIds],
+ );
+ createdRocketIds.length = 0;
+ }
+ });
+
+ afterAll(async () => {
+ await usageLimitRepository.delete({ id: usageLimitId });
+ await refreshUsageLimitsCache();
+ await dropStockCounter();
+ await redis.quit();
+ });
+
+ it('refuses the write that would cross the limit', async () => {
+ expectAdmitted(await createRockets(HEADROOM));
+ expectRefused(await createRockets(1));
+ });
+
+ it('refuses a batch as a whole when only part of it fits', async () => {
+ expectRefused(await createRockets(HEADROOM + 1));
+ expectAdmitted(await createRockets(HEADROOM));
+ });
+
+ it('gives the capacity back when records are destroyed', async () => {
+ const admitted = await createRockets(HEADROOM);
+
+ expectAdmitted(admitted);
+ expectRefused(await createRockets(1));
+
+ await destroyRockets([admitted.body.data.createRockets[0].id]);
+
+ expectAdmitted(await createRockets(1));
+ });
+
+ it('keeps soft-deleted records counted until they are destroyed', async () => {
+ const admitted = await createRockets(HEADROOM);
+
+ expectAdmitted(admitted);
+
+ await softDeleteRockets([admitted.body.data.createRockets[0].id]);
+
+ expectRefused(await createRockets(1));
+ });
+});
diff --git a/packages/twenty-shared/src/application/usageOperationTypesType.ts b/packages/twenty-shared/src/application/usageOperationTypesType.ts
index 60ca370863c..65352d5665c 100644
--- a/packages/twenty-shared/src/application/usageOperationTypesType.ts
+++ b/packages/twenty-shared/src/application/usageOperationTypesType.ts
@@ -1,7 +1,8 @@
// The subset of the server's UsageOperationType an app may bill under, so a
// manifest can name a category without importing server code. API_REQUEST,
-// STORAGE_FILE and SUBSCRIPTION are left out on purpose: the platform raises
-// all three itself, and API_REQUEST rows feed the workspace's API rate limit.
+// STORAGE_FILE, RECORD_WRITE and SUBSCRIPTION are left out on purpose: the
+// platform raises all four itself, and API_REQUEST rows feed the workspace's
+// API rate limit.
export const USAGE_OPERATION_TYPES = [
'AI_CHAT_TOKEN',
'AI_WORKFLOW_TOKEN',