Skip to content

The open alternative to Salesforce, designed for AI.

feat(usage-limit) - reshape the limit model for quota kinds (#25277)

Etienne3baeae4760a4
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index 07e068f70d8..d46eb8f3733 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -934,48 +934,6 @@ type ApplicationRegistration {
galleryImagesUrls: [String!]!
}
-type UsageLimit {
- id: UUID!
- resourceType: UsageResourceType!
- operationType: UsageOperationType!
- spenderType: String!
- spenderId: String!
- limitKind: String!
- windowSeconds: Int!
- limitValueType: String!
- limitValue: BigInt!
- burstValue: BigInt
- createdAt: DateTime!
- updatedAt: DateTime!
-}
-
-enum UsageResourceType {
- AI
- WORKFLOW
- APP
- STORAGE
- API
- LOGIC_FUNCTION
- EMAIL
-}
-
-enum UsageOperationType {
- AI_CHAT_TOKEN
- AI_WORKFLOW_TOKEN
- WORKFLOW_EXECUTION
- CODE_EXECUTION
- WEB_SEARCH
- CALL_RECORDING
- EMAIL_SEND
- API_REQUEST
- SUBSCRIPTION
-}
-
-"""
-The `BigInt` scalar type represents non-fractional signed whole numeric values.
-"""
-scalar BigInt
-
type SdkClientChecksums {
core: String
metadata: String!
@@ -1861,6 +1819,50 @@ type ConnectedAccountPublicDTO {
connectionParameters: PublicImapSmtpCaldavConnectionParameters
}
+type UsageLimit {
+ id: UUID!
+ resourceType: UsageResourceType!
+ operationType: UsageOperationType!
+ spenderType: String!
+ spenderId: String
+ limitKind: String!
+ periodCount: Int!
+ periodUnit: String!
+ meter: String!
+ limitValue: BigInt!
+ burstValue: BigInt
+ createdAt: DateTime!
+ updatedAt: DateTime!
+}
+
+enum UsageResourceType {
+ AI
+ WORKFLOW
+ APP
+ STORAGE
+ API
+ LOGIC_FUNCTION
+ EMAIL
+}
+
+enum UsageOperationType {
+ ALL
+ AI_CHAT_TOKEN
+ AI_WORKFLOW_TOKEN
+ WORKFLOW_EXECUTION
+ CODE_EXECUTION
+ WEB_SEARCH
+ CALL_RECORDING
+ EMAIL_SEND
+ API_REQUEST
+ SUBSCRIPTION
+}
+
+"""
+The `BigInt` scalar type represents non-fractional signed whole numeric values.
+"""
+scalar BigInt
+
type FeatureFlag {
key: FeatureFlagKey!
value: Boolean!
@@ -3992,7 +3994,9 @@ input UpsertUsageLimitInput {
spenderType: String!
spenderId: String
limitKind: String!
- windowSeconds: Int! = 0
+ periodCount: Int!
+ periodUnit: String!
+ meter: String!
limitValue: BigInt!
burstValue: BigInt
}
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index 90fd69ff408..15b36f77878 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -664,26 +664,6 @@ export interface ApplicationRegistration {
__typename: 'ApplicationRegistration'
}
-export interface UsageLimit {
- id: Scalars['UUID']
- resourceType: UsageResourceType
- operationType: UsageOperationType
- spenderType: Scalars['String']
- spenderId: Scalars['String']
- limitKind: Scalars['String']
- windowSeconds: Scalars['Int']
- limitValueType: Scalars['String']
- limitValue: Scalars['BigInt']
- burstValue?: Scalars['BigInt']
- createdAt: Scalars['DateTime']
- updatedAt: Scalars['DateTime']
- __typename: 'UsageLimit'
-}
-
-export type UsageResourceType = 'AI' | 'WORKFLOW' | 'APP' | 'STORAGE' | 'API' | 'LOGIC_FUNCTION' | 'EMAIL'
-
-export type UsageOperationType = 'AI_CHAT_TOKEN' | 'AI_WORKFLOW_TOKEN' | 'WORKFLOW_EXECUTION' | 'CODE_EXECUTION' | 'WEB_SEARCH' | 'CALL_RECORDING' | 'EMAIL_SEND' | 'API_REQUEST' | 'SUBSCRIPTION'
-
export interface SdkClientChecksums {
core?: Scalars['String']
metadata: Scalars['String']
@@ -1505,6 +1485,27 @@ export interface ConnectedAccountPublicDTO {
__typename: 'ConnectedAccountPublicDTO'
}
+export interface UsageLimit {
+ id: Scalars['UUID']
+ resourceType: UsageResourceType
+ operationType: UsageOperationType
+ spenderType: Scalars['String']
+ spenderId?: Scalars['String']
+ limitKind: Scalars['String']
+ periodCount: Scalars['Int']
+ periodUnit: Scalars['String']
+ meter: Scalars['String']
+ limitValue: Scalars['BigInt']
+ burstValue?: Scalars['BigInt']
+ createdAt: Scalars['DateTime']
+ updatedAt: Scalars['DateTime']
+ __typename: 'UsageLimit'
+}
+
+export type UsageResourceType = 'AI' | 'WORKFLOW' | 'APP' | 'STORAGE' | 'API' | 'LOGIC_FUNCTION' | 'EMAIL'
+
+export type UsageOperationType = 'ALL' | 'AI_CHAT_TOKEN' | 'AI_WORKFLOW_TOKEN' | 'WORKFLOW_EXECUTION' | 'CODE_EXECUTION' | 'WEB_SEARCH' | 'CALL_RECORDING' | 'EMAIL_SEND' | 'API_REQUEST' | 'SUBSCRIPTION'
+
export interface FeatureFlag {
key: FeatureFlagKey
value: Scalars['Boolean']
@@ -4072,23 +4073,6 @@ export interface ApplicationRegistrationGenqlSelection{
__scalar?: boolean | number
}
-export interface UsageLimitGenqlSelection{
- id?: boolean | number
- resourceType?: boolean | number
- operationType?: boolean | number
- spenderType?: boolean | number
- spenderId?: boolean | number
- limitKind?: boolean | number
- windowSeconds?: boolean | number
- limitValueType?: boolean | number
- limitValue?: boolean | number
- burstValue?: boolean | number
- createdAt?: boolean | number
- updatedAt?: boolean | number
- __typename?: boolean | number
- __scalar?: boolean | number
-}
-
export interface SdkClientChecksumsGenqlSelection{
core?: boolean | number
metadata?: boolean | number
@@ -4961,6 +4945,24 @@ export interface ConnectedAccountPublicDTOGenqlSelection{
__scalar?: boolean | number
}
+export interface UsageLimitGenqlSelection{
+ id?: boolean | number
+ resourceType?: boolean | number
+ operationType?: boolean | number
+ spenderType?: boolean | number
+ spenderId?: boolean | number
+ limitKind?: boolean | number
+ periodCount?: boolean | number
+ periodUnit?: boolean | number
+ meter?: boolean | number
+ limitValue?: boolean | number
+ burstValue?: boolean | number
+ createdAt?: boolean | number
+ updatedAt?: boolean | number
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
export interface FeatureFlagGenqlSelection{
key?: boolean | number
value?: boolean | number
@@ -6986,7 +6988,7 @@ update: UpdateNavigationMenuItemInput}
export interface UpdateNavigationMenuItemInput {folderId?: (Scalars['UUID'] | null),position?: (Scalars['Float'] | null),name?: (Scalars['String'] | null),link?: (Scalars['String'] | null),icon?: (Scalars['String'] | null),color?: (Scalars['String'] | null),pageLayoutId?: (Scalars['UUID'] | null)}
-export interface UpsertUsageLimitInput {resourceType: UsageResourceType,operationType: UsageOperationType,spenderType: Scalars['String'],spenderId?: (Scalars['String'] | null),limitKind: Scalars['String'],windowSeconds: Scalars['Int'],limitValue: Scalars['BigInt'],burstValue?: (Scalars['BigInt'] | null)}
+export interface UpsertUsageLimitInput {resourceType: UsageResourceType,operationType: UsageOperationType,spenderType: Scalars['String'],spenderId?: (Scalars['String'] | null),limitKind: Scalars['String'],periodCount: Scalars['Int'],periodUnit: Scalars['String'],meter: Scalars['String'],limitValue: Scalars['BigInt'],burstValue?: (Scalars['BigInt'] | null)}
export interface CreateViewFilterGroupInput {id?: (Scalars['UUID'] | null),parentViewFilterGroupId?: (Scalars['UUID'] | null),logicalOperator?: (ViewFilterGroupLogicalOperator | null),positionInViewFilterGroup?: (Scalars['Float'] | null),viewId: Scalars['UUID']}
@@ -7688,14 +7690,6 @@ export interface LogicFunctionLogsInput {applicationId?: (Scalars['UUID'] | null
- const UsageLimit_possibleTypes: string[] = ['UsageLimit']
- export const isUsageLimit = (obj?: { __typename?: any } | null): obj is UsageLimit => {
- if (!obj?.__typename) throw new Error('__typename is missing in "isUsageLimit"')
- return UsageLimit_possibleTypes.includes(obj.__typename)
- }
-
-
-
const SdkClientChecksums_possibleTypes: string[] = ['SdkClientChecksums']
export const isSdkClientChecksums = (obj?: { __typename?: any } | null): obj is SdkClientChecksums => {
if (!obj?.__typename) throw new Error('__typename is missing in "isSdkClientChecksums"')
@@ -8376,6 +8370,14 @@ export interface LogicFunctionLogsInput {applicationId?: (Scalars['UUID'] | null
+ const UsageLimit_possibleTypes: string[] = ['UsageLimit']
+ export const isUsageLimit = (obj?: { __typename?: any } | null): obj is UsageLimit => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isUsageLimit"')
+ return UsageLimit_possibleTypes.includes(obj.__typename)
+ }
+
+
+
const FeatureFlag_possibleTypes: string[] = ['FeatureFlag']
export const isFeatureFlag = (obj?: { __typename?: any } | null): obj is FeatureFlag => {
if (!obj?.__typename) throw new Error('__typename is missing in "isFeatureFlag"')
@@ -9959,28 +9961,6 @@ export const enumOnboardingStatus = {
COMPLETED: 'COMPLETED' as const
}
-export const enumUsageResourceType = {
- AI: 'AI' as const,
- WORKFLOW: 'WORKFLOW' as const,
- APP: 'APP' as const,
- STORAGE: 'STORAGE' as const,
- API: 'API' as const,
- LOGIC_FUNCTION: 'LOGIC_FUNCTION' as const,
- EMAIL: 'EMAIL' as const
-}
-
-export const enumUsageOperationType = {
- AI_CHAT_TOKEN: 'AI_CHAT_TOKEN' as const,
- AI_WORKFLOW_TOKEN: 'AI_WORKFLOW_TOKEN' as const,
- WORKFLOW_EXECUTION: 'WORKFLOW_EXECUTION' as const,
- CODE_EXECUTION: 'CODE_EXECUTION' as const,
- WEB_SEARCH: 'WEB_SEARCH' as const,
- CALL_RECORDING: 'CALL_RECORDING' as const,
- EMAIL_SEND: 'EMAIL_SEND' as const,
- API_REQUEST: 'API_REQUEST' as const,
- SUBSCRIPTION: 'SUBSCRIPTION' as const
-}
-
export const enumWidgetType = {
VIEW: 'VIEW' as const,
IFRAME: 'IFRAME' as const,
@@ -10171,6 +10151,29 @@ export const enumEmailConnectionSecurity = {
SSL_TLS: 'SSL_TLS' as const
}
+export const enumUsageResourceType = {
+ AI: 'AI' as const,
+ WORKFLOW: 'WORKFLOW' as const,
+ APP: 'APP' as const,
+ STORAGE: 'STORAGE' as const,
+ API: 'API' as const,
+ LOGIC_FUNCTION: 'LOGIC_FUNCTION' as const,
+ EMAIL: 'EMAIL' as const
+}
+
+export const enumUsageOperationType = {
+ ALL: 'ALL' as const,
+ AI_CHAT_TOKEN: 'AI_CHAT_TOKEN' as const,
+ AI_WORKFLOW_TOKEN: 'AI_WORKFLOW_TOKEN' as const,
+ WORKFLOW_EXECUTION: 'WORKFLOW_EXECUTION' as const,
+ CODE_EXECUTION: 'CODE_EXECUTION' as const,
+ WEB_SEARCH: 'WEB_SEARCH' as const,
+ CALL_RECORDING: 'CALL_RECORDING' as const,
+ EMAIL_SEND: 'EMAIL_SEND' as const,
+ API_REQUEST: 'API_REQUEST' as const,
+ SUBSCRIPTION: 'SUBSCRIPTION' as const
+}
+
export const enumFeatureFlagKey = {
IS_APP_CLAIMING_ENABLED: 'IS_APP_CLAIMING_ENABLED' as const,
IS_UNIQUE_INDEXES_ENABLED: 'IS_UNIQUE_INDEXES_ENABLED' as const,
diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.ts
index 49f215c0c48..dac30c73b69 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts
@@ -34,30 +34,30 @@ export default {
70,
72,
73,
- 76,
- 77,
- 78,
- 84,
- 87,
+ 80,
+ 83,
+ 88,
+ 89,
92,
93,
- 96,
- 97,
+ 95,
+ 98,
99,
- 102,
- 103,
- 113,
- 128,
+ 109,
+ 124,
+ 130,
+ 131,
+ 132,
134,
- 135,
- 136,
- 138,
- 147,
- 149,
- 156,
- 159,
- 161,
+ 143,
+ 145,
+ 152,
+ 155,
+ 157,
+ 178,
182,
+ 183,
+ 184,
186,
193,
194,
@@ -112,13 +112,13 @@ export default {
1
],
"metadata": [
- 133
+ 129
],
"on_BillingLicensedProduct": [
- 142
+ 138
],
"on_BillingMeteredProduct": [
- 143
+ 139
],
"__typename": [
1
@@ -1642,16 +1642,16 @@ export default {
185
],
"billingSubscriptions": [
- 146
+ 142
],
"installedApplications": [
47
],
"currentBillingSubscription": [
- 146
+ 142
],
"billingCustomer": [
- 145
+ 141
],
"billingEntitlements": [
254
@@ -1818,50 +1818,6 @@ export default {
1
]
},
- "UsageLimit": {
- "id": [
- 3
- ],
- "resourceType": [
- 76
- ],
- "operationType": [
- 77
- ],
- "spenderType": [
- 1
- ],
- "spenderId": [
- 1
- ],
- "limitKind": [
- 1
- ],
- "windowSeconds": [
- 26
- ],
- "limitValueType": [
- 1
- ],
- "limitValue": [
- 78
- ],
- "burstValue": [
- 78
- ],
- "createdAt": [
- 4
- ],
- "updatedAt": [
- 4
- ],
- "__typename": [
- 1
- ]
- },
- "UsageResourceType": {},
- "UsageOperationType": {},
- "BigInt": {},
"SdkClientChecksums": {
"core": [
1
@@ -1932,19 +1888,19 @@ export default {
1
],
"type": [
- 84
+ 80
],
"objectMetadataId": [
3
],
"gridPosition": [
- 82
+ 78
],
"position": [
- 85
+ 81
],
"configuration": [
- 90
+ 86
],
"conditionalDisplay": [
9
@@ -1974,13 +1930,13 @@ export default {
"WidgetType": {},
"PageLayoutWidgetPosition": {
"on_PageLayoutWidgetGridPosition": [
- 86
+ 82
],
"on_PageLayoutWidgetVerticalListPosition": [
- 88
+ 84
],
"on_PageLayoutWidgetCanvasPosition": [
- 89
+ 85
],
"__typename": [
1
@@ -1988,7 +1944,7 @@ export default {
},
"PageLayoutWidgetGridPosition": {
"layoutMode": [
- 87
+ 83
],
"row": [
26
@@ -2009,7 +1965,7 @@ export default {
"PageLayoutTabLayoutMode": {},
"PageLayoutWidgetVerticalListPosition": {
"layoutMode": [
- 87
+ 83
],
"index": [
26
@@ -2020,7 +1976,7 @@ export default {
},
"PageLayoutWidgetCanvasPosition": {
"layoutMode": [
- 87
+ 83
],
"__typename": [
1
@@ -2028,85 +1984,85 @@ export default {
},
"WidgetConfiguration": {
"on_AggregateChartConfiguration": [
- 91
+ 87
],
"on_StandaloneRichTextConfiguration": [
- 94
+ 90
],
"on_PieChartConfiguration": [
- 95
+ 91
],
"on_LineChartConfiguration": [
- 98
+ 94
],
"on_IframeConfiguration": [
- 100
+ 96
],
"on_BarChartConfiguration": [
- 101
+ 97
],
"on_CalendarConfiguration": [
- 104
+ 100
],
"on_FrontComponentConfiguration": [
- 105
+ 101
],
"on_EmailsConfiguration": [
- 106
+ 102
],
"on_EmailThreadConfiguration": [
- 107
+ 103
],
"on_CallRecordingSummaryConfiguration": [
- 108
+ 104
],
"on_CallRecordingTranscriptConfiguration": [
- 109
+ 105
],
"on_MessageCampaignBodyConfiguration": [
- 110
+ 106
],
"on_MessageCampaignDetailsConfiguration": [
- 111
+ 107
],
"on_FieldConfiguration": [
- 112
+ 108
],
"on_FieldRichTextConfiguration": [
- 114
+ 110
],
"on_FieldsConfiguration": [
- 115
+ 111
],
"on_FormFieldConfiguration": [
- 116
+ 112
],
"on_FilesConfiguration": [
- 117
+ 113
],
"on_NotesConfiguration": [
- 118
+ 114
],
"on_TasksConfiguration": [
- 119
+ 115
],
"on_TimelineConfiguration": [
- 120
+ 116
],
"on_ViewConfiguration": [
- 121
+ 117
],
"on_RecordTableConfiguration": [
- 122
+ 118
],
"on_WorkflowConfiguration": [
- 123
+ 119
],
"on_WorkflowRunConfiguration": [
- 124
+ 120
],
"on_WorkflowVersionConfiguration": [
- 125
+ 121
],
"__typename": [
1
@@ -2114,7 +2070,7 @@ export default {
},
"AggregateChartConfiguration": {
"configurationType": [
- 92
+ 88
],
"aggregateFieldMetadataId": [
3
@@ -2129,7 +2085,7 @@ export default {
8
],
"numberFormat": [
- 93
+ 89
],
"description": [
1
@@ -2150,7 +2106,7 @@ export default {
1
],
"ratioAggregateConfig": [
- 80
+ 76
],
"__typename": [
1
@@ -2160,10 +2116,10 @@ export default {
"ChartNumberFormat": {},
"StandaloneRichTextConfiguration": {
"configurationType": [
- 92
+ 88
],
"body": [
- 81
+ 77
],
"__typename": [
1
@@ -2171,7 +2127,7 @@ export default {
},
"PieChartConfiguration": {
"configurationType": [
- 92
+ 88
],
"aggregateFieldMetadataId": [
3
@@ -2186,10 +2142,10 @@ export default {
1
],
"dateGranularity": [
- 96
+ 92
],
"orderBy": [
- 97
+ 93
],
"manualSortOrder": [
1
@@ -2207,7 +2163,7 @@ export default {
8
],
"numberFormat": [
- 93
+ 89
],
"splitMultiValueFields": [
8
@@ -2235,7 +2191,7 @@ export default {
"GraphOrderBy": {},
"LineChartConfiguration": {
"configurationType": [
- 92
+ 88
],
"aggregateFieldMetadataId": [
3
@@ -2250,10 +2206,10 @@ export default {
1
],
"primaryAxisDateGranularity": [
- 96
+ 92
],
"primaryAxisOrderBy": [
- 97
+ 93
],
"primaryAxisManualSortOrder": [
1
@@ -2265,10 +2221,10 @@ export default {
1
],
"secondaryAxisGroupByDateGranularity": [
- 96
+ 92
],
"secondaryAxisOrderBy": [
- 97
+ 93
],
"secondaryAxisManualSortOrder": [
1
@@ -2280,7 +2236,7 @@ export default {
8
],
"axisNameDisplay": [
- 99
+ 95
],
"displayDataLabel": [
8
@@ -2289,7 +2245,7 @@ export default {
8
],
"numberFormat": [
- 93
+ 89
],
"rangeMin": [
15
@@ -2325,7 +2281,7 @@ export default {
"AxisNameDisplay": {},
"IframeConfiguration": {
"configurationType": [
- 92
+ 88
],
"url": [
1
@@ -2336,7 +2292,7 @@ export default {
},
"BarChartConfiguration": {
"configurationType": [
- 92
+ 88
],
"aggregateFieldMetadataId": [
3
@@ -2351,10 +2307,10 @@ export default {
1
],
"primaryAxisDateGranularity": [
- 96
+ 92
],
"primaryAxisOrderBy": [
- 97
+ 93
],
"primaryAxisManualSortOrder": [
1
@@ -2366,10 +2322,10 @@ export default {
1
],
"secondaryAxisGroupByDateGranularity": [
- 96
+ 92
],
"secondaryAxisOrderBy": [
- 97
+ 93
],
"secondaryAxisManualSortOrder": [
1
@@ -2381,7 +2337,7 @@ export default {
8
],
"axisNameDisplay": [
- 99
+ 95
],
"displayDataLabel": [
8
@@ -2390,7 +2346,7 @@ export default {
8
],
"numberFormat": [
- 93
+ 89
],
"rangeMin": [
15
@@ -2408,10 +2364,10 @@ export default {
9
],
"groupMode": [
- 102
+ 98
],
"layout": [
- 103
+ 99
],
"isCumulative": [
8
@@ -2430,7 +2386,7 @@ export default {
"BarChartLayout": {},
"CalendarConfiguration": {
"configurationType": [
- 92
+ 88
],
"__typename": [
1
@@ -2438,7 +2394,7 @@ export default {
},
"FrontComponentConfiguration": {
"configurationType": [
- 92
+ 88
],
"frontComponentId": [
3
@@ -2452,7 +2408,7 @@ export default {
},
"EmailsConfiguration": {
"configurationType": [
- 92
+ 88
],
"__typename": [
1
@@ -2460,7 +2416,7 @@ export default {
},
"EmailThreadConfiguration": {
"configurationType": [
- 92
+ 88
],
"__typename": [
1
@@ -2468,7 +2424,7 @@ export default {
},
"CallRecordingSummaryConfiguration": {
"configurationType": [
- 92
+ 88
],
"__typename": [
1
@@ -2476,7 +2432,7 @@ export default {
},
"CallRecordingTranscriptConfiguration": {
"configurationType": [
- 92
+ 88
],
"__typename": [
1
@@ -2484,7 +2440,7 @@ export default {
},
"MessageCampaignBodyConfiguration": {
"configurationType": [
- 92
+ 88
],
"__typename": [
1
@@ -2492,7 +2448,7 @@ export default {
},
"MessageCampaignDetailsConfiguration": {
"configurationType": [
- 92
+ 88
],
"__typename": [
1
@@ -2500,13 +2456,13 @@ export default {
},
"FieldConfiguration": {
"configurationType": [
- 92
+ 88
],
"fieldMetadataId": [
1
],
"fieldDisplayMode": [
- 113
+ 109
],
"viewId": [
1
@@ -2524,7 +2480,7 @@ export default {
"FieldDisplayMode": {},
"FieldRichTextConfiguration": {
"configurationType": [
- 92
+ 88
],
"__typename": [
1
@@ -2532,7 +2488,7 @@ export default {
},
"FieldsConfiguration": {
"configurationType": [
- 92
+ 88
],
"viewId": [
1
@@ -2549,7 +2505,7 @@ export default {
},
"FormFieldConfiguration": {
"configurationType": [
- 92
+ 88
],
"fieldMetadataId": [
1
@@ -2560,7 +2516,7 @@ export default {
},
"FilesConfiguration": {
"configurationType": [
- 92
+ 88
],
"__typename": [
1
@@ -2568,7 +2524,7 @@ export default {
},
"NotesConfiguration": {
"configurationType": [
- 92
+ 88
],
"__typename": [
1
@@ -2576,7 +2532,7 @@ export default {
},
"TasksConfiguration": {
"configurationType": [
- 92
+ 88
],
"__typename": [
1
@@ -2584,7 +2540,7 @@ export default {
},
"TimelineConfiguration": {
"configurationType": [
- 92
+ 88
],
"__typename": [
1
@@ -2592,7 +2548,7 @@ export default {
},
"ViewConfiguration": {
"configurationType": [
- 92
+ 88
],
"__typename": [
1
@@ -2600,7 +2556,7 @@ export default {
},
"RecordTableConfiguration": {
"configurationType": [
- 92
+ 88
],
"viewId": [
1
@@ -2617,7 +2573,7 @@ export default {
},
"WorkflowConfiguration": {
"configurationType": [
- 92
+ 88
],
"__typename": [
1
@@ -2625,7 +2581,7 @@ export default {
},
"WorkflowRunConfiguration": {
"configurationType": [
- 92
+ 88
],
"__typename": [
1
@@ -2633,7 +2589,7 @@ export default {
},
"WorkflowVersionConfiguration": {
"configurationType": [
- 92
+ 88
],
"__typename": [
1
@@ -2662,13 +2618,13 @@ export default {
3
],
"widgets": [
- 83
+ 79
],
"icon": [
1
],
"layoutMode": [
- 87
+ 83
],
"createdAt": [
4
@@ -2697,13 +2653,13 @@ export default {
1
],
"type": [
- 128
+ 124
],
"objectMetadataId": [
3
],
"tabs": [
- 126
+ 122
],
"defaultTabToFocusOnMobileAndSidePanelId": [
3
@@ -2762,7 +2718,7 @@ export default {
1
],
"oauth": [
- 129
+ 125
],
"__typename": [
1
@@ -2787,7 +2743,7 @@ export default {
15
],
"items": [
- 131
+ 127
],
"__typename": [
1
@@ -2795,13 +2751,13 @@ export default {
},
"BillingProductMetadata": {
"planKey": [
- 134
+ 130
],
"priceUsageBased": [
- 135
+ 131
],
"productKey": [
- 136
+ 132
],
"__typename": [
1
@@ -2812,7 +2768,7 @@ export default {
"BillingProductKey": {},
"BillingPriceLicensed": {
"recurringInterval": [
- 138
+ 134
],
"unitAmount": [
15
@@ -2821,7 +2777,7 @@ export default {
1
],
"priceUsageType": [
- 135
+ 131
],
"creditAmount": [
15
@@ -2847,16 +2803,16 @@ export default {
},
"BillingPriceMetered": {
"tiers": [
- 139
+ 135
],
"recurringInterval": [
- 138
+ 134
],
"stripePriceId": [
1
],
"priceUsageType": [
- 135
+ 131
],
"__typename": [
1
@@ -2873,7 +2829,7 @@ export default {
1
],
"metadata": [
- 133
+ 129
],
"__typename": [
1
@@ -2890,10 +2846,10 @@ export default {
1
],
"metadata": [
- 133
+ 129
],
"prices": [
- 137
+ 133
],
"__typename": [
1
@@ -2910,10 +2866,10 @@ export default {
1
],
"metadata": [
- 133
+ 129
],
"prices": [
- 140
+ 136
],
"__typename": [
1
@@ -2955,13 +2911,13 @@ export default {
3
],
"status": [
- 147
+ 143
],
"interval": [
- 138
+ 134
],
"billingSubscriptionItems": [
- 144
+ 140
],
"currentPeriodEnd": [
4
@@ -2970,7 +2926,7 @@ export default {
9
],
"phases": [
- 132
+ 128
],
"cancelAt": [
4
@@ -2991,7 +2947,7 @@ export default {
15
],
"status": [
- 149
+ 145
],
"error": [
9
@@ -3109,7 +3065,7 @@ export default {
3
],
"type": [
- 156
+ 152
],
"name": [
1
@@ -3142,7 +3098,7 @@ export default {
4
],
"targetRecordIdentifier": [
- 154
+ 150
],
"__typename": [
1
@@ -3168,7 +3124,7 @@ export default {
},
"MetadataEvent": {
"type": [
- 159
+ 155
],
"metadataName": [
1
@@ -3177,7 +3133,7 @@ export default {
1
],
"properties": [
- 157
+ 153
],
"updatedCollectionHash": [
1
@@ -3189,7 +3145,7 @@ export default {
"MetadataEventAction": {},
"ObjectRecordEvent": {
"action": [
- 161
+ 157
],
"objectNameSingular": [
1
@@ -3204,7 +3160,7 @@ export default {
1
],
"properties": [
- 157
+ 153
],
"__typename": [
1
@@ -3216,7 +3172,7 @@ export default {
1
],
"objectRecordEvent": [
- 160
+ 156
],
"__typename": [
1
@@ -3227,10 +3183,10 @@ export default {
1
],
"objectRecordEventsWithQueryIds": [
- 162
+ 158
],
"metadataEvents": [
- 158
+ 154
],
"__typename": [
1
@@ -3273,7 +3229,7 @@ export default {
},
"BillingEndTrialPeriod": {
"status": [
- 147
+ 143
],
"hasPaymentMethod": [
8
@@ -3282,10 +3238,10 @@ export default {
1
],
"currentBillingSubscription": [
- 146
+ 142
],
"billingSubscriptions": [
- 146
+ 142
],
"__typename": [
1
@@ -3293,7 +3249,7 @@ export default {
},
"BillingResourceCreditUsage": {
"productKey": [
- 136
+ 132
],
"periodStart": [
4
@@ -3322,16 +3278,16 @@ export default {
},
"BillingPlan": {
"planKey": [
- 134
+ 130
],
"baseProducts": [
- 142
+ 138
],
"resourceCreditProducts": [
- 142
+ 138
],
"meteredProducts": [
- 143
+ 139
],
"__typename": [
1
@@ -3358,10 +3314,10 @@ export default {
},
"BillingUpdate": {
"currentBillingSubscription": [
- 146
+ 142
],
"billingSubscriptions": [
- 146
+ 142
],
"__typename": [
1
@@ -3397,7 +3353,7 @@ export default {
1
],
"dailyUsage": [
- 172
+ 168
],
"__typename": [
1
@@ -3405,19 +3361,19 @@ export default {
},
"UsageAnalytics": {
"usageByUser": [
- 171
+ 167
],
"usageByOperationType": [
- 171
+ 167
],
"usageByApplication": [
- 171
+ 167
],
"usageByModel": [
- 171
+ 167
],
"timeSeries": [
- 172
+ 168
],
"periodStart": [
4
@@ -3426,7 +3382,7 @@ export default {
4
],
"userDailyUsage": [
- 173
+ 169
],
"__typename": [
1
@@ -3504,7 +3460,7 @@ export default {
1
],
"result": [
- 179
+ 175
],
"__typename": [
1
@@ -3521,7 +3477,7 @@ export default {
1
],
"connectionSecurity": [
- 182
+ 178
],
"__typename": [
1
@@ -3530,13 +3486,13 @@ export default {
"EmailConnectionSecurity": {},
"PublicImapSmtpCaldavConnectionParameters": {
"IMAP": [
- 181
+ 177
],
"SMTP": [
- 181
+ 177
],
"CALDAV": [
- 181
+ 177
],
"__typename": [
1
@@ -3592,12 +3548,59 @@ export default {
4
],
"connectionParameters": [
+ 179
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "UsageLimit": {
+ "id": [
+ 3
+ ],
+ "resourceType": [
+ 182
+ ],
+ "operationType": [
183
],
+ "spenderType": [
+ 1
+ ],
+ "spenderId": [
+ 1
+ ],
+ "limitKind": [
+ 1
+ ],
+ "periodCount": [
+ 26
+ ],
+ "periodUnit": [
+ 1
+ ],
+ "meter": [
+ 1
+ ],
+ "limitValue": [
+ 184
+ ],
+ "burstValue": [
+ 184
+ ],
+ "createdAt": [
+ 4
+ ],
+ "updatedAt": [
+ 4
+ ],
"__typename": [
1
]
},
+ "UsageResourceType": {},
+ "UsageOperationType": {},
+ "BigInt": {},
"FeatureFlag": {
"key": [
186
@@ -5431,7 +5434,7 @@ export default {
4
],
"connectedAccount": [
- 184
+ 180
],
"__typename": [
1
@@ -5630,7 +5633,7 @@ export default {
1
],
"connectionSecurity": [
- 182
+ 178
],
"__typename": [
1
@@ -5907,10 +5910,10 @@ export default {
8
],
"layout": [
- 103
+ 99
],
"groupMode": [
- 102
+ 98
],
"hasTooManyGroups": [
8
@@ -6706,10 +6709,10 @@ export default {
},
"Query": {
"navigationMenuItems": [
- 155
+ 151
],
"navigationMenuItem": [
- 155,
+ 151,
{
"id": [
3,
@@ -6718,7 +6721,7 @@ export default {
}
],
"applicationSdkClientChecksums": [
- 79,
+ 75,
{
"applicationId": [
3,
@@ -6752,10 +6755,10 @@ export default {
}
],
"enterpriseSubscriptionStatus": [
- 151
+ 147
],
"getUsageAnalytics": [
- 174,
+ 170,
{
"input": [
382
@@ -6763,7 +6766,7 @@ export default {
}
],
"usageLimits": [
- 75
+ 181
],
"getViewFilterGroups": [
54,
@@ -6889,13 +6892,13 @@ export default {
}
],
"currentUserSessions": [
- 164
+ 160
],
"myConnectedAccounts": [
- 184
+ 180
],
"applicationConnectionProviders": [
- 130,
+ 126,
{
"applicationId": [
3,
@@ -6904,7 +6907,7 @@ export default {
}
],
"billingPortalSession": [
- 169,
+ 165,
{
"returnUrlPath": [
1
@@ -6915,22 +6918,22 @@ export default {
}
],
"listPlans": [
- 167
+ 163
],
"getResourceCreditUsage": [
- 166
+ 162
],
"getInviteSuggestions": [
- 176
+ 172
],
"findWorkspaceInvitations": [
- 179
+ 175
],
"getApprovedAccessDomains": [
- 175
+ 171
],
"getPageLayoutTabs": [
- 126,
+ 122,
{
"pageLayoutId": [
1,
@@ -6939,7 +6942,7 @@ export default {
}
],
"getPageLayoutTab": [
- 126,
+ 122,
{
"id": [
1,
@@ -6948,18 +6951,18 @@ export default {
}
],
"getPageLayouts": [
- 127,
+ 123,
{
"objectMetadataId": [
1
],
"pageLayoutType": [
- 128
+ 124
]
}
],
"getPageLayout": [
- 127,
+ 123,
{
"id": [
1,
@@ -6968,7 +6971,7 @@ export default {
}
],
"getPageLayoutWidgets": [
- 83,
+ 79,
{
"pageLayoutTabId": [
1,
@@ -6977,7 +6980,7 @@ export default {
}
],
"getPageLayoutWidget": [
- 83,
+ 79,
{
"id": [
1,
@@ -7620,7 +7623,7 @@ export default {
1
],
"operationTypes": [
- 77
+ 183
],
"__typename": [
1
@@ -7849,7 +7852,7 @@ export default {
}
],
"createManyNavigationMenuItems": [
- 155,
+ 151,
{
"inputs": [
401,
@@ -7858,7 +7861,7 @@ export default {
}
],
"createNavigationMenuItem": [
- 155,
+ 151,
{
"input": [
401,
@@ -7867,7 +7870,7 @@ export default {
}
],
"updateManyNavigationMenuItems": [
- 155,
+ 151,
{
"inputs": [
402,
@@ -7876,7 +7879,7 @@ export default {
}
],
"updateNavigationMenuItem": [
- 155,
+ 151,
{
"input": [
402,
@@ -7885,7 +7888,7 @@ export default {
}
],
"deleteManyNavigationMenuItems": [
- 155,
+ 151,
{
"ids": [
3,
@@ -7894,7 +7897,7 @@ export default {
}
],
"deleteNavigationMenuItem": [
- 155,
+ 151,
{
"id": [
3,
@@ -7903,7 +7906,7 @@ export default {
}
],
"createFileUpload": [
- 153,
+ 149,
{
"filename": [
1,
@@ -7926,7 +7929,7 @@ export default {
}
],
"completeFileUpload": [
- 152,
+ 148,
{
"fileId": [
1,
@@ -7938,10 +7941,10 @@ export default {
8
],
"releaseEnterpriseServerBinding": [
- 150
+ 146
],
"setEnterpriseKey": [
- 150,
+ 146,
{
"enterpriseKey": [
1,
@@ -7950,7 +7953,7 @@ export default {
}
],
"uploadEmailAttachmentFile": [
- 152,
+ 148,
{
"file": [
404,
@@ -7959,7 +7962,7 @@ export default {
}
],
"uploadAiChatFile": [
- 152,
+ 148,
{
"file": [
404,
@@ -7968,7 +7971,7 @@ export default {
}
],
"uploadWorkflowFile": [
- 152,
+ 148,
{
"file": [
404,
@@ -7977,7 +7980,7 @@ export default {
}
],
"uploadWorkspaceLogo": [
- 152,
+ 148,
{
"file": [
404,
@@ -7986,7 +7989,7 @@ export default {
}
],
"uploadWorkspaceMemberProfilePicture": [
- 152,
+ 148,
{
"file": [
404,
@@ -7995,7 +7998,7 @@ export default {
}
],
"uploadFilesFieldFile": [
- 152,
+ 148,
{
"file": [
404,
@@ -8008,7 +8011,7 @@ export default {
}
],
"uploadFilesFieldFileByUniversalIdentifier": [
- 152,
+ 148,
{
"file": [
404,
@@ -8021,7 +8024,7 @@ export default {
}
],
"upsertUsageLimit": [
- 75,
+ 181,
{
"input": [
405,
@@ -8351,7 +8354,7 @@ export default {
26
],
"deleteConnectedAccount": [
- 184,
+ 180,
{
"id": [
3,
@@ -8377,14 +8380,14 @@ export default {
}
],
"checkoutSession": [
- 169,
+ 165,
{
"recurringInterval": [
- 138,
+ 134,
"SubscriptionInterval!"
],
"plan": [
- 134,
+ 130,
"BillingPlanKey!"
],
"requirePaymentMethod": [
@@ -8397,14 +8400,14 @@ export default {
}
],
"createSubscriptionPaymentIntent": [
- 168,
+ 164,
{
"recurringInterval": [
- 138,
+ 134,
"SubscriptionInterval!"
],
"plan": [
- 134,
+ 130,
"BillingPlanKey!"
],
"requirePaymentMethod": [
@@ -8421,22 +8424,22 @@ export default {
}
],
"createBillingPaymentMethodSetupIntent": [
- 168
+ 164
],
"switchSubscriptionInterval": [
- 170
+ 166
],
"switchBillingPlan": [
- 170
+ 166
],
"cancelSwitchBillingPlan": [
- 170
+ 166
],
"cancelSwitchBillingInterval": [
- 170
+ 166
],
"setResourceCreditSubscriptionPrice": [
- 170,
+ 166,
{
"priceId": [
1,
@@ -8445,13 +8448,13 @@ export default {
}
],
"endSubscriptionTrialPeriod": [
- 165
+ 161
],
"cancelSwitchResourceCreditPrice": [
- 170
+ 166
],
"skipSyncEmailOnboardingStep": [
- 178,
+ 174,
{
"isAutoSkipped": [
8,
@@ -8460,7 +8463,7 @@ export default {
}
],
"completeBookCallOnboardingStep": [
- 178,
+ 174,
{
"hasBookedCall": [
8,
@@ -8473,7 +8476,7 @@ export default {
}
],
"triggerInstallAppsOnboardingStep": [
- 178,
+ 174,
{
"universalIdentifiers": [
1,
@@ -8486,7 +8489,7 @@ export default {
}
],
"goBackToPreviousOnboardingStep": [
- 177
+ 173
],
"deleteWorkspaceInvitation": [
1,
@@ -8498,7 +8501,7 @@ export default {
}
],
"resendWorkspaceInvitation": [
- 180,
+ 176,
{
"appTokenId": [
1,
@@ -8507,7 +8510,7 @@ export default {
}
],
"sendInvitations": [
- 180,
+ 176,
{
"emails": [
1,
@@ -8519,7 +8522,7 @@ export default {
}
],
"createApprovedAccessDomain": [
- 175,
+ 171,
{
"input": [
442,
@@ -8537,7 +8540,7 @@ export default {
}
],
"validateApprovedAccessDomain": [
- 175,
+ 171,
{
"input": [
444,
@@ -8546,7 +8549,7 @@ export default {
}
],
"createPageLayoutTab": [
- 126,
+ 122,
{
"input": [
445,
@@ -8555,7 +8558,7 @@ export default {
}
],
"updatePageLayoutTab": [
- 126,
+ 122,
{
"id": [
1,
@@ -8577,7 +8580,7 @@ export default {
}
],
"createPageLayout": [
- 127,
+ 123,
{
"input": [
447,
@@ -8586,7 +8589,7 @@ export default {
}
],
"updatePageLayout": [
- 127,
+ 123,
{
"id": [
1,
@@ -8608,7 +8611,7 @@ export default {
}
],
"updatePageLayoutWithTabsAndWidgets": [
- 127,
+ 123,
{
"id": [
1,
@@ -8621,7 +8624,7 @@ export default {
}
],
"resetPageLayoutToDefault": [
- 127,
+ 123,
{
"id": [
1,
@@ -8630,7 +8633,7 @@ export default {
}
],
"resetPageLayoutWidgetToDefault": [
- 83,
+ 79,
{
"id": [
1,
@@ -8639,7 +8642,7 @@ export default {
}
],
"resetPageLayoutTabToDefault": [
- 126,
+ 122,
{
"id": [
1,
@@ -8648,7 +8651,7 @@ export default {
}
],
"createPageLayoutWidget": [
- 83,
+ 79,
{
"input": [
452,
@@ -8657,7 +8660,7 @@ export default {
}
],
"updatePageLayoutWidget": [
- 83,
+ 79,
{
"id": [
1,
@@ -8769,7 +8772,7 @@ export default {
}
],
"executeOneLogicFunction": [
- 148,
+ 144,
{
"input": [
467,
@@ -9855,7 +9858,7 @@ export default {
}
],
"uploadNewWorkspaceLogo": [
- 152,
+ 148,
{
"workspaceId": [
1,
@@ -10388,7 +10391,7 @@ export default {
3
],
"type": [
- 156
+ 152
],
"name": [
1
@@ -10455,10 +10458,10 @@ export default {
"Upload": {},
"UpsertUsageLimitInput": {
"resourceType": [
- 76
+ 182
],
"operationType": [
- 77
+ 183
],
"spenderType": [
1
@@ -10469,14 +10472,20 @@ export default {
"limitKind": [
1
],
- "windowSeconds": [
+ "periodCount": [
26
],
+ "periodUnit": [
+ 1
+ ],
+ "meter": [
+ 1
+ ],
"limitValue": [
- 78
+ 184
],
"burstValue": [
- 78
+ 184
],
"__typename": [
1
@@ -11198,7 +11207,7 @@ export default {
3
],
"layoutMode": [
- 87
+ 83
],
"__typename": [
1
@@ -11215,7 +11224,7 @@ export default {
1
],
"layoutMode": [
- 87
+ 83
],
"__typename": [
1
@@ -11226,7 +11235,7 @@ export default {
1
],
"type": [
- 128
+ 124
],
"objectMetadataId": [
3
@@ -11240,7 +11249,7 @@ export default {
1
],
"type": [
- 128
+ 124
],
"objectMetadataId": [
3
@@ -11254,7 +11263,7 @@ export default {
1
],
"type": [
- 128
+ 124
],
"objectMetadataId": [
3
@@ -11283,7 +11292,7 @@ export default {
1
],
"layoutMode": [
- 87
+ 83
],
"widgets": [
451
@@ -11303,7 +11312,7 @@ export default {
1
],
"type": [
- 84
+ 80
],
"objectMetadataId": [
3
@@ -11332,7 +11341,7 @@ export default {
1
],
"type": [
- 84
+ 80
],
"objectMetadataId": [
3
@@ -11355,7 +11364,7 @@ export default {
1
],
"type": [
- 84
+ 80
],
"objectMetadataId": [
3
@@ -13180,7 +13189,7 @@ export default {
1
],
"connectionSecurity": [
- 182
+ 178
],
"__typename": [
1
@@ -13213,7 +13222,7 @@ export default {
},
"Subscription": {
"onEventSubscription": [
- 163,
+ 159,
{
"eventStreamId": [
1,
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index 3ede928a8f6..49071c8e35c 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -6406,11 +6406,13 @@ export type UpsertUsageLimitInput = {
burstValue?: InputMaybe<Scalars['BigInt']['input']>;
limitKind: Scalars['String']['input'];
limitValue: Scalars['BigInt']['input'];
+ meter: Scalars['String']['input'];
operationType: UsageOperationType;
+ periodCount: Scalars['Int']['input'];
+ periodUnit: Scalars['String']['input'];
resourceType: UsageResourceType;
spenderId?: InputMaybe<Scalars['String']['input']>;
spenderType: Scalars['String']['input'];
- windowSeconds?: Scalars['Int']['input'];
};
export type UpsertViewWidgetInput = {
@@ -6511,18 +6513,20 @@ export type UsageLimit = {
id: Scalars['UUID']['output'];
limitKind: Scalars['String']['output'];
limitValue: Scalars['BigInt']['output'];
- limitValueType: Scalars['String']['output'];
+ meter: Scalars['String']['output'];
operationType: UsageOperationType;
+ periodCount: Scalars['Int']['output'];
+ periodUnit: Scalars['String']['output'];
resourceType: UsageResourceType;
- spenderId: Scalars['String']['output'];
+ spenderId?: Maybe<Scalars['String']['output']>;
spenderType: Scalars['String']['output'];
updatedAt: Scalars['DateTime']['output'];
- windowSeconds: Scalars['Int']['output'];
};
export enum UsageOperationType {
AI_CHAT_TOKEN = 'AI_CHAT_TOKEN',
AI_WORKFLOW_TOKEN = 'AI_WORKFLOW_TOKEN',
+ ALL = 'ALL',
API_REQUEST = 'API_REQUEST',
CALL_RECORDING = 'CALL_RECORDING',
CODE_EXECUTION = 'CODE_EXECUTION',
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 7a880cdb092..be2a0d5a352 100644
--- a/packages/twenty-front/src/modules/settings/usage/constants/UsageOperationTypeLabels.ts
+++ b/packages/twenty-front/src/modules/settings/usage/constants/UsageOperationTypeLabels.ts
@@ -9,6 +9,7 @@ export const USAGE_OPERATION_TYPE_LABELS: Record<
UsageOperationType,
MessageDescriptor
> = {
+ [UsageOperationType.ALL]: msg`All operations`,
[UsageOperationType.AI_CHAT_TOKEN]: msg`AI Chat`,
[UsageOperationType.AI_WORKFLOW_TOKEN]: msg`AI Workflow`,
[UsageOperationType.WORKFLOW_EXECUTION]: msg`Workflow Execution`,
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1788367160891-reshape-usage-limit-period.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1788367160891-reshape-usage-limit-period.ts
new file mode 100644
index 00000000000..09ff9b43a43
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1788367160891-reshape-usage-limit-period.ts
@@ -0,0 +1,64 @@
+import { QueryRunner } from 'typeorm';
+
+import { RegisteredInstanceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-instance-command.decorator';
+import { FastInstanceCommand } from 'src/engine/core-modules/upgrade/interfaces/fast-instance-command.interface';
+
+@RegisteredInstanceCommand('2.38.0', 1788367160891)
+export class ReshapeUsageLimitPeriodFastInstanceCommand implements FastInstanceCommand {
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ `ALTER TABLE "core"."usageLimit" DROP CONSTRAINT "UQ_USAGE_LIMIT_SCOPE"`,
+ );
+ await queryRunner.query(
+ `ALTER TABLE "core"."usageLimit" RENAME COLUMN "windowSeconds" TO "periodCount"`,
+ );
+ await queryRunner.query(
+ `ALTER TABLE "core"."usageLimit" ALTER COLUMN "periodCount" DROP DEFAULT`,
+ );
+ await queryRunner.query(
+ `ALTER TABLE "core"."usageLimit" ADD COLUMN "periodUnit" character varying NOT NULL DEFAULT 'second'`,
+ );
+ await queryRunner.query(
+ `ALTER TABLE "core"."usageLimit" ALTER COLUMN "periodUnit" DROP DEFAULT`,
+ );
+ await queryRunner.query(
+ `ALTER TABLE "core"."usageLimit" ADD COLUMN "meter" character varying NOT NULL DEFAULT 'quantity'`,
+ );
+ await queryRunner.query(
+ `ALTER TABLE "core"."usageLimit" ALTER COLUMN "meter" DROP DEFAULT`,
+ );
+ await queryRunner.query(
+ `ALTER TABLE "core"."usageLimit" DROP COLUMN "limitValueType"`,
+ );
+ await queryRunner.query(
+ `ALTER TABLE "core"."usageLimit" ADD CONSTRAINT "UQ_USAGE_LIMIT_SCOPE" UNIQUE ("workspaceId", "resourceType", "operationType", "spenderType", "spenderId", "limitKind", "periodCount", "periodUnit", "meter")`,
+ );
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ `ALTER TABLE "core"."usageLimit" DROP CONSTRAINT "UQ_USAGE_LIMIT_SCOPE"`,
+ );
+ await queryRunner.query(
+ `DELETE FROM "core"."usageLimit" WHERE "limitKind" = 'quota'`,
+ );
+ await queryRunner.query(
+ `ALTER TABLE "core"."usageLimit" ADD COLUMN "limitValueType" character varying NOT NULL DEFAULT 'absolute'`,
+ );
+ await queryRunner.query(
+ `ALTER TABLE "core"."usageLimit" DROP COLUMN "periodUnit"`,
+ );
+ await queryRunner.query(
+ `ALTER TABLE "core"."usageLimit" DROP COLUMN "meter"`,
+ );
+ await queryRunner.query(
+ `ALTER TABLE "core"."usageLimit" ALTER COLUMN "periodCount" SET DEFAULT 0`,
+ );
+ await queryRunner.query(
+ `ALTER TABLE "core"."usageLimit" RENAME COLUMN "periodCount" TO "windowSeconds"`,
+ );
+ await queryRunner.query(
+ `ALTER TABLE "core"."usageLimit" ADD CONSTRAINT "UQ_USAGE_LIMIT_SCOPE" UNIQUE ("workspaceId", "resourceType", "operationType", "spenderType", "spenderId", "limitKind", "windowSeconds")`,
+ );
+ }
+}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
index 9113b2a2679..a4482994dc8 100644
--- a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
@@ -173,6 +173,7 @@ import { AddStateToApplicationFastInstanceCommand } from 'src/database/commands/
import { RenameEmailingDomainPermanentlySuspendedToSandboxFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1788272351966-rename-emailing-domain-permanently-suspended-to-sandbox';
import { RelaxNavigationPayloadCheckFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1788272351970-relax-navigation-payload-check';
import { EraseObjectNavigationCommandMenuItemPayloadsSlowInstanceCommand } from 'src/database/commands/upgrade-version-command/2-38/2-38-instance-command-slow-1788272351971-erase-object-navigation-command-menu-item-payloads';
+import { ReshapeUsageLimitPeriodFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1788367160891-reshape-usage-limit-period';
export const INSTANCE_COMMANDS = [
AddViewFieldGroupIdIndexOnViewFieldFastInstanceCommand,
@@ -348,4 +349,5 @@ export const INSTANCE_COMMANDS = [
RenameEmailingDomainPermanentlySuspendedToSandboxFastInstanceCommand,
RelaxNavigationPayloadCheckFastInstanceCommand,
EraseObjectNavigationCommandMenuItemPayloadsSlowInstanceCommand,
+ ReshapeUsageLimitPeriodFastInstanceCommand,
];
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 61348a953d4..8a2404df073 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
@@ -602,7 +602,7 @@ export abstract class CommonBaseQueryRunnerService<
if (
error instanceof UsageLimitException &&
isDefined(error.exhaustedScope) &&
- error.exhaustedScope.isFallback
+ error.exhaustedScope.isDefault
) {
await this.incrementApiSpeedCeilingMetrics({
authContext,
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 8a509f78f30..26b88d0e477 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
@@ -18,7 +18,10 @@ import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/works
// Each operation type has one canonical counting unit — matches how
// `ai-billing.service.ts` emits native usage events.
-const USAGE_UNIT_BY_OPERATION_TYPE: Record<UsageOperationType, UsageUnit> = {
+const USAGE_UNIT_BY_OPERATION_TYPE: Record<
+ Exclude<UsageOperationType, UsageOperationType.ALL>,
+ UsageUnit
+> = {
[UsageOperationType.AI_CHAT_TOKEN]: UsageUnit.TOKEN,
[UsageOperationType.AI_WORKFLOW_TOKEN]: UsageUnit.TOKEN,
[UsageOperationType.WORKFLOW_EXECUTION]: UsageUnit.INVOCATION,
@@ -91,7 +94,7 @@ export class AppBillingService {
workspaceId: string;
applicationId: string;
charge: ChargeDto;
- }): Promise<UsageOperationType> {
+ }): Promise<Exclude<UsageOperationType, UsageOperationType.ALL>> {
if (!isDefined(charge.operation)) {
if (!isDefined(charge.operationType)) {
throw new BadRequestException(
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/limit-kinds.constant.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/limit-kinds.constant.ts
index edab95433b5..4fcb508bcdd 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/limit-kinds.constant.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/limit-kinds.constant.ts
@@ -1 +1 @@
-export const LIMIT_KINDS = ['speed'] as const;
+export const LIMIT_KINDS = ['speed', 'quota'] as const;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/limit-value-types.constant.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/limit-value-types.constant.ts
deleted file mode 100644
index ca7e83b94e9..00000000000
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/limit-value-types.constant.ts
+++ /dev/null
@@ -1 +0,0 @@
-export const LIMIT_VALUE_TYPES = ['absolute'] as const;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/period-units.constant.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/period-units.constant.ts
new file mode 100644
index 00000000000..0eed2f39ee2
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/period-units.constant.ts
@@ -0,0 +1 @@
+export const PERIOD_UNITS = ['second', 'day', 'week', 'month'] as const;
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 50dbf5c98c0..1efddf90107 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
@@ -1,17 +1,16 @@
-import { type LimitKind } from 'src/engine/core-modules/usage-limit/types/limit-kind.type';
-import { type UsageLimitDefinition } from 'src/engine/core-modules/usage-limit/types/usage-limit-definition.type';
+import { type UsageLimitDefinitions } from 'src/engine/core-modules/usage-limit/types/usage-limit-definition.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';
export const USAGE_LIMIT_DEFINITIONS: Record<
UsageResourceType,
- Partial<Record<LimitKind, UsageLimitDefinition>>
+ UsageLimitDefinitions
> = {
[UsageResourceType.API]: {
speed: {
allowedOperationTypes: [UsageOperationType.API_REQUEST],
allowedSpenderTypes: ['apiKey', 'application'],
- fallbacks: [
+ defaults: [
{
spenderType: 'apiKey',
counterScope: 'perWorkspace',
@@ -36,7 +35,23 @@ export const USAGE_LIMIT_DEFINITIONS: Record<
],
},
},
- [UsageResourceType.AI]: {},
+ [UsageResourceType.AI]: {
+ quota: {
+ allowedOperationTypes: [
+ UsageOperationType.AI_CHAT_TOKEN,
+ UsageOperationType.AI_WORKFLOW_TOKEN,
+ UsageOperationType.WEB_SEARCH,
+ ],
+ allowedSpenderTypes: [
+ 'workspace',
+ 'userWorkspace',
+ 'apiKey',
+ 'application',
+ 'agent',
+ ],
+ allowedMeters: ['creditsUsedMicro', 'quantity'],
+ },
+ },
[UsageResourceType.WORKFLOW]: {},
[UsageResourceType.APP]: {},
[UsageResourceType.STORAGE]: {},
@@ -45,7 +60,7 @@ export const USAGE_LIMIT_DEFINITIONS: Record<
speed: {
allowedOperationTypes: [UsageOperationType.EMAIL_SEND],
allowedSpenderTypes: ['workspace'],
- fallbacks: [
+ defaults: [
{
spenderType: 'workspace',
counterScope: 'crossWorkspace',
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-meters.constant.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-meters.constant.ts
new file mode 100644
index 00000000000..e5097521957
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-meters.constant.ts
@@ -0,0 +1 @@
+export const USAGE_METERS = ['creditsUsedMicro', 'quantity'] as const;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/upsert-usage-limit.input.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/upsert-usage-limit.input.ts
index a0580f42f0e..3a1acc3c239 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/upsert-usage-limit.input.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/upsert-usage-limit.input.ts
@@ -12,8 +12,12 @@ import {
} from 'class-validator';
import { LIMIT_KINDS } from 'src/engine/core-modules/usage-limit/constants/limit-kinds.constant';
+import { PERIOD_UNITS } from 'src/engine/core-modules/usage-limit/constants/period-units.constant';
+import { USAGE_METERS } from 'src/engine/core-modules/usage-limit/constants/usage-meters.constant';
import { SPENDER_TYPES } from 'src/engine/core-modules/usage-limit/constants/spender-types.constant';
import { type LimitKind } from 'src/engine/core-modules/usage-limit/types/limit-kind.type';
+import { type PeriodUnit } from 'src/engine/core-modules/usage-limit/types/period-unit.type';
+import { type UsageMeter } from 'src/engine/core-modules/usage-limit/types/usage-meter.type';
import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.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';
@@ -41,10 +45,18 @@ export class UpsertUsageLimitInput {
@IsIn(LIMIT_KINDS)
limitKind: LimitKind;
- @Field(() => Int, { defaultValue: 0 })
+ @Field(() => Int)
@IsInt()
- @Min(0)
- windowSeconds: number;
+ @Min(1)
+ periodCount: number;
+
+ @Field(() => String)
+ @IsIn(PERIOD_UNITS)
+ periodUnit: PeriodUnit;
+
+ @Field(() => String)
+ @IsIn(USAGE_METERS)
+ meter: UsageMeter;
@Field(() => GraphQLBigInt)
@IsInt()
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/usage-limit.dto.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/usage-limit.dto.ts
new file mode 100644
index 00000000000..287763d7dde
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/usage-limit.dto.ts
@@ -0,0 +1,53 @@
+import { Field, Int, ObjectType } from '@nestjs/graphql';
+
+import { GraphQLBigInt } from 'graphql-scalars';
+
+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+import { type LimitKind } from 'src/engine/core-modules/usage-limit/types/limit-kind.type';
+import { type PeriodUnit } from 'src/engine/core-modules/usage-limit/types/period-unit.type';
+import { type UsageMeter } from 'src/engine/core-modules/usage-limit/types/usage-meter.type';
+import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.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';
+
+@ObjectType('UsageLimit')
+export class UsageLimitDTO {
+ @Field(() => UUIDScalarType)
+ id: string;
+
+ @Field(() => UsageResourceType)
+ resourceType: UsageResourceType;
+
+ @Field(() => UsageOperationType)
+ operationType: UsageOperationType;
+
+ @Field(() => String)
+ spenderType: SpenderType;
+
+ @Field(() => String, { nullable: true })
+ spenderId: string | null;
+
+ @Field(() => String)
+ limitKind: LimitKind;
+
+ @Field(() => Int)
+ periodCount: number;
+
+ @Field(() => String)
+ periodUnit: PeriodUnit;
+
+ @Field(() => String)
+ meter: UsageMeter;
+
+ @Field(() => GraphQLBigInt)
+ limitValue: number;
+
+ @Field(() => GraphQLBigInt, { nullable: true })
+ burstValue: number | null;
+
+ @Field(() => Date)
+ createdAt: Date;
+
+ @Field(() => Date)
+ updatedAt: Date;
+}
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
index ee0262df33b..310935ae0d6 100644
--- 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
@@ -1,4 +1,4 @@
-import { HttpException, HttpStatus } from '@nestjs/common';
+import { HttpException } 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';
@@ -11,7 +11,7 @@ export class UsageLimitHttpException
private readonly responseBody: UsageLimitRestResponseBody,
private readonly responseHeaders: Record<string, string>,
) {
- super(responseBody, HttpStatus.TOO_MANY_REQUESTS);
+ super(responseBody, responseBody.statusCode);
this.message = responseBody.messages[0];
}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/exceptions/usage-limit.exception.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/exceptions/usage-limit.exception.ts
index 1edd9a7959d..95bf031d24a 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/exceptions/usage-limit.exception.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/exceptions/usage-limit.exception.ts
@@ -9,7 +9,7 @@ import { type ExhaustedScope } from 'src/engine/core-modules/usage-limit/types/e
export enum UsageLimitExceptionCode {
RATE_LIMITED = 'RATE_LIMITED',
QUOTA_EXHAUSTED = 'QUOTA_EXHAUSTED',
- LIMIT_RULE_INVALID = 'LIMIT_RULE_INVALID',
+ LIMIT_INVALID = 'LIMIT_INVALID',
}
const getUsageLimitExceptionUserFriendlyMessage = (
@@ -20,7 +20,7 @@ const getUsageLimitExceptionUserFriendlyMessage = (
return msg`Rate limit reached. Please try again later.`;
case UsageLimitExceptionCode.QUOTA_EXHAUSTED:
return msg`Usage quota exhausted for this period.`;
- case UsageLimitExceptionCode.LIMIT_RULE_INVALID:
+ case UsageLimitExceptionCode.LIMIT_INVALID:
return msg`This limit cannot be saved.`;
default:
assertUnreachable(code);
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 bcd6e100874..cae4db2d426 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
@@ -21,11 +21,11 @@ const catchAsGraphQLError = (exception: UsageLimitException) => {
};
describe('UsageLimitGraphqlApiExceptionFilter', () => {
- it('surfaces an invalid limit rule as a user input error rather than a server error', () => {
+ it('surfaces an invalid limit as a user input error rather than a server error', () => {
const graphqlError = catchAsGraphQLError(
new UsageLimitException(
'API speed limits cannot target the EMAIL_SEND operation',
- UsageLimitExceptionCode.LIMIT_RULE_INVALID,
+ UsageLimitExceptionCode.LIMIT_INVALID,
),
);
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 a716a52744d..b927f53d91b 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
@@ -13,7 +13,7 @@ import { usageLimitToGraphqlApiExceptionHandler } from 'src/engine/core-modules/
export class UsageLimitGraphqlApiExceptionFilter implements ExceptionFilter {
catch(exception: UsageLimitException) {
switch (exception.code) {
- case UsageLimitExceptionCode.LIMIT_RULE_INVALID:
+ case UsageLimitExceptionCode.LIMIT_INVALID:
throw new UserInputError(exception);
case UsageLimitExceptionCode.RATE_LIMITED:
case UsageLimitExceptionCode.QUOTA_EXHAUSTED:
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/filters/usage-limit-rest-api-exception.filter.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/filters/usage-limit-rest-api-exception.filter.ts
new file mode 100644
index 00000000000..caaf12503ff
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/filters/usage-limit-rest-api-exception.filter.ts
@@ -0,0 +1,32 @@
+import {
+ type ArgumentsHost,
+ Catch,
+ type ExceptionFilter,
+} from '@nestjs/common';
+
+import type { Response } from 'express';
+
+import { UsageLimitHttpException } from 'src/engine/core-modules/usage-limit/exceptions/usage-limit-http.exception';
+import { UsageLimitException } from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';
+import { buildUsageLimitHttpException } from 'src/engine/core-modules/usage-limit/utils/usage-limit-to-rest-api-exception-handler.util';
+
+@Catch(UsageLimitException)
+export class UsageLimitRestApiExceptionFilter implements ExceptionFilter {
+ catch(exception: UsageLimitException, host: ArgumentsHost) {
+ const response = host.switchToHttp().getResponse<Response>();
+ const httpException = buildUsageLimitHttpException(exception);
+
+ if (httpException instanceof UsageLimitHttpException) {
+ response.set(httpException.getResponseHeaders());
+
+ return response
+ .status(httpException.getStatus())
+ .json(httpException.getResponseBody());
+ }
+
+ return response.status(httpException.getStatus()).json({
+ statusCode: httpException.getStatus(),
+ messages: [exception.message],
+ });
+ }
+}
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
index 5c743359d8d..153d4b36d1e 100644
--- 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
@@ -32,7 +32,7 @@ describe('UsageLimitSpeedService', () => {
const workspaceCacheService = {
getOrRecompute: jest
.fn()
- .mockResolvedValue({ usageLimitRules: { byResourceType: {} } }),
+ .mockResolvedValue({ usageLimits: { byResourceType: {} } }),
};
const twentyConfigService = {
@@ -64,7 +64,7 @@ describe('UsageLimitSpeedService', () => {
service = module.get<UsageLimitSpeedService>(UsageLimitSpeedService);
});
- it('admits the request when the rules cannot be read from storage', async () => {
+ it('admits the request when the limits cannot be read from storage', async () => {
workspaceCacheService.getOrRecompute.mockRejectedValueOnce(
new Error('Socket closed unexpectedly'),
);
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
index c37d92bd5fd..66eea6c816a 100644
--- 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
@@ -16,7 +16,7 @@ import {
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 { type UsageLimits } from 'src/engine/core-modules/usage-limit/types/usage-limits.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';
@@ -66,13 +66,16 @@ export class UsageLimitSpeedService {
exhaustedScope: {
resourceType,
limitKind: 'speed',
+ exhaustedKind: 'limit',
spenderType: outcome.exhausted.spenderType,
spenderId: outcome.exhausted.spenderId,
+ operationType,
limitValue: outcome.exhausted.refillPerWindow,
remaining: 0,
- windowSeconds: Math.ceil(outcome.exhausted.windowMs / 1000),
+ periodCount: Math.ceil(outcome.exhausted.windowMs / 1000),
+ periodUnit: 'second',
retryAfterMs: outcome.retryAfterMs,
- isFallback: outcome.exhausted.isFallback,
+ isDefault: outcome.exhausted.isDefault,
},
},
);
@@ -167,45 +170,49 @@ export class UsageLimitSpeedService {
return [];
}
- const rules = await this.findRulesAdmittingOnFailure({
+ const limits = await this.findLimitsAdmittingOnFailure({
workspaceId: authContext.workspace.id,
resourceType,
});
- if (!isDefined(rules)) {
+ if (!isDefined(limits)) {
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,
+ speedLimitDefaults: definition.defaults.map(
+ (speedLimitDefaultDefinition) => ({
+ spenderType: speedLimitDefaultDefinition.spenderType,
+ counterScope: speedLimitDefaultDefinition.counterScope,
+ isOverridable: speedLimitDefaultDefinition.isOverridable,
+ maxTokens: this.twentyConfigService.get(
+ speedLimitDefaultDefinition.limitValueConfigVariable,
+ ),
+ windowMs: this.twentyConfigService.get(
+ speedLimitDefaultDefinition.windowMsConfigVariable,
+ ),
+ }),
+ ),
+ limits,
authContext,
resourceType,
operationType,
});
}
- private async findRulesAdmittingOnFailure({
+ private async findLimitsAdmittingOnFailure({
workspaceId,
resourceType,
}: {
workspaceId: string;
resourceType: UsageResourceType;
}): Promise<FlatUsageLimit[] | null> {
- let usageLimitRules: UsageLimitRules;
+ let usageLimits: UsageLimits;
try {
- ({ usageLimitRules } = await this.workspaceCacheService.getOrRecompute(
+ ({ usageLimits } = await this.workspaceCacheService.getOrRecompute(
workspaceId,
- ['usageLimitRules'],
+ ['usageLimits'],
));
} catch (error) {
if (error instanceof WorkspaceCacheException) {
@@ -213,13 +220,13 @@ export class UsageLimitSpeedService {
}
this.logger.error(
- 'Usage limit rules unavailable, enforcement degraded',
+ 'Usage limits unavailable, enforcement degraded',
error,
);
return null;
}
- return usageLimitRules.byResourceType[resourceType] ?? [];
+ return usageLimits.byResourceType[resourceType] ?? [];
}
}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit.service.ts
index fb8ea50dfbd..26231945cc8 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit.service.ts
@@ -65,7 +65,9 @@ export class UsageLimitService {
spenderType: input.spenderType,
spenderId: input.spenderId ?? '',
limitKind: input.limitKind,
- windowSeconds: input.windowSeconds,
+ periodCount: input.periodCount,
+ periodUnit: input.periodUnit,
+ meter: input.meter,
};
await this.usageLimitRepository.upsert(
@@ -73,7 +75,6 @@ export class UsageLimitService {
{
workspaceId,
...scope,
- limitValueType: 'absolute',
limitValue: input.limitValue,
burstValue: input.burstValue ?? null,
},
@@ -81,7 +82,7 @@ export class UsageLimitService {
);
await this.workspaceCacheService.invalidateAndRecompute(workspaceId, [
- 'usageLimitRules',
+ 'usageLimits',
]);
return this.usageLimitRepository.findOneOrFail(workspaceId, {
@@ -105,7 +106,7 @@ export class UsageLimitService {
}
await this.workspaceCacheService.invalidateAndRecompute(workspaceId, [
- 'usageLimitRules',
+ 'usageLimits',
]);
return true;
@@ -129,7 +130,7 @@ export class UsageLimitService {
if (!spenderExists) {
throw new UsageLimitException(
`No ${spenderType} ${spenderId} in this workspace`,
- UsageLimitExceptionCode.LIMIT_RULE_INVALID,
+ UsageLimitExceptionCode.LIMIT_INVALID,
);
}
}
@@ -163,7 +164,7 @@ export class UsageLimitService {
default:
throw new UsageLimitException(
`A ${spenderType} spender id cannot be checked against the workspace`,
- UsageLimitExceptionCode.LIMIT_RULE_INVALID,
+ UsageLimitExceptionCode.LIMIT_INVALID,
);
}
}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-rules-cache.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limits-cache.service.ts
similarity index 59%
rename from packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-rules-cache.service.ts
rename to packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limits-cache.service.ts
index 641524c6068..bbf136ac2ad 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-rules-cache.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limits-cache.service.ts
@@ -2,38 +2,38 @@ import { Injectable } from '@nestjs/common';
import { WorkspaceCacheProvider } from 'src/engine/workspace-cache/interfaces/workspace-cache-provider.service';
-import { type UsageLimitRules } from 'src/engine/core-modules/usage-limit/types/usage-limit-rules.type';
+import { type UsageLimits } from 'src/engine/core-modules/usage-limit/types/usage-limits.type';
import { fromUsageLimitEntityToFlat } from 'src/engine/core-modules/usage-limit/utils/from-usage-limit-entity-to-flat.util';
import { WorkspaceCache } from 'src/engine/workspace-cache/decorators/workspace-cache.decorator';
import { type WorkspaceCacheProviderContext } from 'src/engine/workspace-cache/types/workspace-cache-provider-context.type';
import { type WorkspaceCacheRowsRequirement } from 'src/engine/workspace-cache/types/workspace-cache-rows-requirement.type';
-const USAGE_LIMIT_RULES_ROWS_REQUIREMENT = {
+const USAGE_LIMITS_ROWS_REQUIREMENT = {
usageLimit: true,
} as const satisfies WorkspaceCacheRowsRequirement;
@Injectable()
-@WorkspaceCache('usageLimitRules', { packingPonderation: 1 })
-export class UsageLimitRulesCacheService extends WorkspaceCacheProvider<UsageLimitRules> {
- override readonly rowsRequirement = USAGE_LIMIT_RULES_ROWS_REQUIREMENT;
+@WorkspaceCache('usageLimits', { packingPonderation: 1 })
+export class UsageLimitsCacheService extends WorkspaceCacheProvider<UsageLimits> {
+ override readonly rowsRequirement = USAGE_LIMITS_ROWS_REQUIREMENT;
computeForCache({
rows,
}: WorkspaceCacheProviderContext<
- typeof USAGE_LIMIT_RULES_ROWS_REQUIREMENT
- >): UsageLimitRules {
+ typeof USAGE_LIMITS_ROWS_REQUIREMENT
+ >): UsageLimits {
const { usageLimit: usageLimits } = rows;
- return usageLimits.reduce<UsageLimitRules>(
- (rules, usageLimit) => {
+ return usageLimits.reduce<UsageLimits>(
+ (limits, usageLimit) => {
const flat = fromUsageLimitEntityToFlat(usageLimit);
- rules.byResourceType[flat.resourceType] = [
- ...(rules.byResourceType[flat.resourceType] ?? []),
+ limits.byResourceType[flat.resourceType] = [
+ ...(limits.byResourceType[flat.resourceType] ?? []),
flat,
];
- return rules;
+ return limits;
},
{ byResourceType: {} },
);
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/anchored-period-unit.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/anchored-period-unit.type.ts
new file mode 100644
index 00000000000..b86fca474f8
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/anchored-period-unit.type.ts
@@ -0,0 +1,3 @@
+import { type PeriodUnit } from 'src/engine/core-modules/usage-limit/types/period-unit.type';
+
+export type AnchoredPeriodUnit = Exclude<PeriodUnit, 'second'>;
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
deleted file mode 100644
index 0deef6f2358..00000000000
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/default-usage-limit-fallback.type.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-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-kind.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/exhausted-kind.type.ts
new file mode 100644
index 00000000000..7d89d9be716
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/exhausted-kind.type.ts
@@ -0,0 +1 @@
+export type ExhaustedKind = 'limit' | 'allowance';
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 2de44606eb1..f0083d94534 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
@@ -1,15 +1,21 @@
+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 { type ExhaustedKind } from 'src/engine/core-modules/usage-limit/types/exhausted-kind.type';
import { type LimitKind } from 'src/engine/core-modules/usage-limit/types/limit-kind.type';
+import { type PeriodUnit } from 'src/engine/core-modules/usage-limit/types/period-unit.type';
import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
export type ExhaustedScope = {
resourceType: UsageResourceType;
limitKind: LimitKind;
+ exhaustedKind: ExhaustedKind;
spenderType: SpenderType;
spenderId: string | null;
+ operationType: UsageOperationType;
limitValue: number;
remaining: number;
- windowSeconds: number;
+ periodCount: number | null;
+ periodUnit: PeriodUnit | null;
retryAfterMs: number;
- isFallback: boolean;
+ isDefault?: boolean;
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/flat-usage-limit.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/flat-usage-limit.type.ts
index fbd91bf6110..7694b9e1a2a 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/flat-usage-limit.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/flat-usage-limit.type.ts
@@ -1,8 +1,9 @@
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 { type LimitKind } from 'src/engine/core-modules/usage-limit/types/limit-kind.type';
-import { type LimitValueType } from 'src/engine/core-modules/usage-limit/types/limit-value-type.type';
+import { type PeriodUnit } from 'src/engine/core-modules/usage-limit/types/period-unit.type';
import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
+import { type UsageMeter } from 'src/engine/core-modules/usage-limit/types/usage-meter.type';
export type FlatUsageLimit = {
id: string;
@@ -11,8 +12,9 @@ export type FlatUsageLimit = {
spenderType: SpenderType;
spenderId: string;
limitKind: LimitKind;
- windowSeconds: number;
- limitValueType: LimitValueType;
+ periodCount: number;
+ periodUnit: PeriodUnit;
+ meter: UsageMeter;
limitValue: number;
burstValue: number | null;
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-value-type.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-value-type.type.ts
deleted file mode 100644
index e223e3bd41c..00000000000
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-value-type.type.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import { type LIMIT_VALUE_TYPES } from 'src/engine/core-modules/usage-limit/constants/limit-value-types.constant';
-
-export type LimitValueType = (typeof LIMIT_VALUE_TYPES)[number];
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/period-unit.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/period-unit.type.ts
new file mode 100644
index 00000000000..b01e0bc920e
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/period-unit.type.ts
@@ -0,0 +1,3 @@
+import { type PERIOD_UNITS } from 'src/engine/core-modules/usage-limit/constants/period-units.constant';
+
+export type PeriodUnit = (typeof PERIOD_UNITS)[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
index 9412d6f4bff..d0c2248038c 100644
--- 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
@@ -7,5 +7,5 @@ export type SpeedBucketRequest = {
windowMs: number;
spenderType: SpenderType;
spenderId: string | null;
- isFallback: boolean;
+ isDefault: boolean;
};
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/speed-limit-default-definition.type.ts
similarity index 92%
rename from packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-fallback.type.ts
rename to packages/twenty-server/src/engine/core-modules/usage-limit/types/speed-limit-default-definition.type.ts
index 42b6c601a75..6dc45372ab2 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/speed-limit-default-definition.type.ts
@@ -2,7 +2,7 @@ import { type NumericConfigVariableKey } from 'src/engine/core-modules/twenty-co
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 = {
+export type SpeedLimitDefaultDefinition = {
spenderType: SpenderType;
counterScope: CounterScope;
isOverridable: boolean;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/speed-limit-default.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/speed-limit-default.type.ts
new file mode 100644
index 00000000000..04e8e38f050
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/speed-limit-default.type.ts
@@ -0,0 +1,9 @@
+import { type SpeedLimitDefaultDefinition } from 'src/engine/core-modules/usage-limit/types/speed-limit-default-definition.type';
+
+export type SpeedLimitDefault = Pick<
+ SpeedLimitDefaultDefinition,
+ 'spenderType' | 'counterScope' | 'isOverridable'
+> & {
+ maxTokens: number;
+ windowMs: number;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-definition.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-definition.type.ts
index 4ffab1bb620..c2539d1581a 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-definition.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-definition.type.ts
@@ -1,9 +1,21 @@
import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
-import { type UsageLimitFallback } from 'src/engine/core-modules/usage-limit/types/usage-limit-fallback.type';
+import { type SpeedLimitDefaultDefinition } from 'src/engine/core-modules/usage-limit/types/speed-limit-default-definition.type';
+import { type UsageMeter } from 'src/engine/core-modules/usage-limit/types/usage-meter.type';
import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
-export type UsageLimitDefinition = {
+export type SpeedLimitDefinition = {
allowedOperationTypes: UsageOperationType[];
allowedSpenderTypes: SpenderType[];
- fallbacks: UsageLimitFallback[];
+ defaults: SpeedLimitDefaultDefinition[];
+};
+
+export type QuotaLimitDefinition = {
+ allowedOperationTypes: UsageOperationType[];
+ allowedSpenderTypes: SpenderType[];
+ allowedMeters: UsageMeter[];
+};
+
+export type UsageLimitDefinitions = {
+ speed?: SpeedLimitDefinition;
+ quota?: QuotaLimitDefinition;
};
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
index 6bcaaedcf28..e2b4f0aaf22 100644
--- 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
@@ -1,17 +1,23 @@
+import { type ExhaustedKind } from 'src/engine/core-modules/usage-limit/types/exhausted-kind.type';
import { type LimitKind } from 'src/engine/core-modules/usage-limit/types/limit-kind.type';
+import { type PeriodUnit } from 'src/engine/core-modules/usage-limit/types/period-unit.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';
export type UsageLimitRestResponseBody = {
statusCode: number;
error: string;
messages: string[];
limitKind: LimitKind;
+ exhaustedKind: ExhaustedKind;
scope: {
spenderType: SpenderType;
spenderId: string | null;
+ operationType: UsageOperationType;
};
limit: number;
remaining: number;
- windowSeconds: number;
+ periodCount: number | null;
+ periodUnit: PeriodUnit | null;
retryAfterSeconds: number;
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-rules.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limits.type.ts
similarity index 89%
rename from packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-rules.type.ts
rename to packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limits.type.ts
index 4ab9e039719..74a29b65807 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-rules.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limits.type.ts
@@ -1,6 +1,6 @@
import { type 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';
-export type UsageLimitRules = {
+export type UsageLimits = {
byResourceType: Partial<Record<UsageResourceType, FlatUsageLimit[]>>;
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-meter.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-meter.type.ts
new file mode 100644
index 00000000000..9f15e9cbc67
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-meter.type.ts
@@ -0,0 +1,3 @@
+import { type USAGE_METERS } from 'src/engine/core-modules/usage-limit/constants/usage-meters.constant';
+
+export type UsageMeter = (typeof USAGE_METERS)[number];
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.entity.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.entity.ts
index 27e8349eb0f..ad8f70b685a 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.entity.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.entity.ts
@@ -1,7 +1,3 @@
-import { Field, Int, ObjectType } from '@nestjs/graphql';
-
-import { GraphQLBigInt } from 'graphql-scalars';
-
import {
Column,
CreateDateColumn,
@@ -11,13 +7,13 @@ import {
UpdateDateColumn,
} from 'typeorm';
-import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
import { type LimitKind } from 'src/engine/core-modules/usage-limit/types/limit-kind.type';
-import { type LimitValueType } from 'src/engine/core-modules/usage-limit/types/limit-value-type.type';
import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
+import { type PeriodUnit } from 'src/engine/core-modules/usage-limit/types/period-unit.type';
+import { type UsageMeter } from 'src/engine/core-modules/usage-limit/types/usage-meter.type';
import { nullableBigintColumnTransformer } from 'src/engine/core-modules/usage-limit/utils/nullable-bigint-column-transformer.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 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 { WorkspaceRelatedEntity } from 'src/engine/workspace-manager/types/workspace-related-entity';
@Unique('UQ_USAGE_LIMIT_SCOPE', [
@@ -27,48 +23,42 @@ import { WorkspaceRelatedEntity } from 'src/engine/workspace-manager/types/works
'spenderType',
'spenderId',
'limitKind',
- 'windowSeconds',
+ 'periodCount',
+ 'periodUnit',
+ 'meter',
])
@Entity({ name: 'usageLimit', schema: 'core' })
-@ObjectType('UsageLimit')
export class UsageLimitEntity extends WorkspaceRelatedEntity {
- @Field(() => UUIDScalarType)
@PrimaryGeneratedColumn('uuid')
id: string;
- @Field(() => UsageResourceType)
@Column({ type: 'varchar' })
resourceType: UsageResourceType;
- @Field(() => UsageOperationType)
@Column({ type: 'varchar' })
operationType: UsageOperationType;
- @Field(() => String)
@Column({ type: 'varchar' })
spenderType: SpenderType;
- @Field(() => String)
@Column({ type: 'varchar', default: '' })
spenderId: string;
- @Field(() => String)
@Column({ type: 'varchar' })
limitKind: LimitKind;
- @Field(() => Int)
- @Column({ type: 'int', default: 0 })
- windowSeconds: number;
+ @Column({ type: 'int' })
+ periodCount: number;
- @Field(() => String)
- @Column({ type: 'varchar', default: 'absolute' })
- limitValueType: LimitValueType;
+ @Column({ type: 'varchar' })
+ periodUnit: PeriodUnit;
+
+ @Column({ type: 'varchar' })
+ meter: UsageMeter;
- @Field(() => GraphQLBigInt)
@Column({ type: 'bigint', transformer: nullableBigintColumnTransformer })
limitValue: number;
- @Field(() => GraphQLBigInt, { nullable: true })
@Column({
type: 'bigint',
nullable: true,
@@ -76,11 +66,9 @@ export class UsageLimitEntity extends WorkspaceRelatedEntity {
})
burstValue: number | null;
- @Field(() => Date)
@CreateDateColumn({ type: 'timestamptz' })
createdAt: Date;
- @Field(() => Date)
@UpdateDateColumn({ type: 'timestamptz' })
updatedAt: Date;
}
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 909d32aa90e..da85a70df88 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
@@ -9,7 +9,7 @@ import { LogicFunctionEntity } from 'src/engine/metadata-modules/logic-function/
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';
+import { UsageLimitsCacheService } from 'src/engine/core-modules/usage-limit/services/usage-limits-cache.service';
import { UsageLimitEntity } from 'src/engine/core-modules/usage-limit/usage-limit.entity';
import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permissions.module';
import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/provide-workspace-scoped-repository';
@@ -30,7 +30,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
],
providers: [
UsageLimitSpeedService,
- UsageLimitRulesCacheService,
+ UsageLimitsCacheService,
UsageLimitService,
UsageLimitResolver,
provideWorkspaceScopedRepository(UsageLimitEntity),
@@ -40,6 +40,6 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
provideWorkspaceScopedRepository(AgentEntity),
provideWorkspaceScopedRepository(LogicFunctionEntity),
],
- exports: [UsageLimitSpeedService, UsageLimitRulesCacheService],
+ exports: [UsageLimitSpeedService, UsageLimitsCacheService],
})
export class UsageLimitModule {}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.resolver.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.resolver.ts
index f8c54666ec0..8640271d2bb 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.resolver.ts
@@ -8,15 +8,16 @@ import { MetadataResolver } from 'src/engine/api/graphql/graphql-config/decorato
import { PreventNestToAutoLogGraphqlErrorsFilter } from 'src/engine/core-modules/graphql/filters/prevent-nest-to-auto-log-graphql-errors.filter';
import { ResolverValidationPipe } from 'src/engine/core-modules/graphql/pipes/resolver-validation.pipe';
import { UpsertUsageLimitInput } from 'src/engine/core-modules/usage-limit/dtos/upsert-usage-limit.input';
+import { UsageLimitDTO } from 'src/engine/core-modules/usage-limit/dtos/usage-limit.dto';
import { UsageLimitGraphqlApiExceptionFilter } from 'src/engine/core-modules/usage-limit/filters/usage-limit-graphql-api-exception.filter';
import { UsageLimitService } from 'src/engine/core-modules/usage-limit/services/usage-limit.service';
-import { UsageLimitEntity } from 'src/engine/core-modules/usage-limit/usage-limit.entity';
+import { fromUsageLimitEntityToDto } from 'src/engine/core-modules/usage-limit/utils/from-usage-limit-entity-to-dto.util';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';
import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
-@MetadataResolver(() => UsageLimitEntity)
+@MetadataResolver(() => UsageLimitDTO)
@UseFilters(
UsageLimitGraphqlApiExceptionFilter,
PreventNestToAutoLogGraphqlErrorsFilter,
@@ -29,19 +30,26 @@ import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
export class UsageLimitResolver {
constructor(private readonly usageLimitService: UsageLimitService) {}
- @Query(() => [UsageLimitEntity])
+ @Query(() => [UsageLimitDTO])
async usageLimits(
@AuthWorkspace() workspace: WorkspaceEntity,
- ): Promise<UsageLimitEntity[]> {
- return this.usageLimitService.findAll(workspace.id);
+ ): Promise<UsageLimitDTO[]> {
+ const usageLimits = await this.usageLimitService.findAll(workspace.id);
+
+ return usageLimits.map(fromUsageLimitEntityToDto);
}
- @Mutation(() => UsageLimitEntity)
+ @Mutation(() => UsageLimitDTO)
async upsertUsageLimit(
@AuthWorkspace() workspace: WorkspaceEntity,
@Args('input') input: UpsertUsageLimitInput,
- ): Promise<UsageLimitEntity> {
- return this.usageLimitService.upsert({ workspaceId: workspace.id, input });
+ ): Promise<UsageLimitDTO> {
+ const usageLimit = await this.usageLimitService.upsert({
+ workspaceId: workspace.id,
+ input,
+ });
+
+ return fromUsageLimitEntityToDto(usageLimit);
}
@Mutation(() => Boolean)
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
index 5cd2ebf377c..22f09bb7b73 100644
--- 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
@@ -1,7 +1,7 @@
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 SpeedLimitDefault } from 'src/engine/core-modules/usage-limit/types/speed-limit-default.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';
@@ -9,7 +9,7 @@ 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[] = [
+const SPEED_LIMIT_DEFAULTS: SpeedLimitDefault[] = [
{
spenderType: 'apiKey',
counterScope: 'perWorkspace',
@@ -33,15 +33,16 @@ const DEFAULT_USAGE_LIMIT_FALLBACKS: DefaultUsageLimitFallback[] = [
},
];
-const buildRule = (overrides: Partial<FlatUsageLimit>): FlatUsageLimit => ({
- id: 'rule-id',
+const buildLimit = (overrides: Partial<FlatUsageLimit>): FlatUsageLimit => ({
+ id: 'limit-id',
resourceType: UsageResourceType.API,
operationType: UsageOperationType.API_REQUEST,
spenderType: 'apiKey',
spenderId: '',
limitKind: 'speed',
- windowSeconds: 60,
- limitValueType: 'absolute',
+ periodCount: 60,
+ periodUnit: 'second',
+ meter: 'quantity',
limitValue: 100,
burstValue: null,
...overrides,
@@ -49,16 +50,16 @@ const buildRule = (overrides: Partial<FlatUsageLimit>): FlatUsageLimit => ({
const buildBuckets = ({
authContext,
- rules = [],
- defaultUsageLimitFallbacks = DEFAULT_USAGE_LIMIT_FALLBACKS,
+ limits = [],
+ speedLimitDefaults = SPEED_LIMIT_DEFAULTS,
}: {
authContext: WorkspaceAuthContext;
- rules?: FlatUsageLimit[];
- defaultUsageLimitFallbacks?: DefaultUsageLimitFallback[];
+ limits?: FlatUsageLimit[];
+ speedLimitDefaults?: SpeedLimitDefault[];
}) =>
buildSpeedBuckets({
- defaultUsageLimitFallbacks,
- rules,
+ speedLimitDefaults,
+ limits,
authContext,
resourceType: UsageResourceType.API,
operationType: UsageOperationType.API_REQUEST,
@@ -94,7 +95,7 @@ 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', () => {
+describe('buildSpeedBuckets with no limits configured', () => {
it('meters an api key against one shared counter per window', () => {
expect(buildBuckets({ authContext: apiKeyContext })).toEqual([
expect.objectContaining({
@@ -136,7 +137,7 @@ describe('buildSpeedBuckets with no rules configured', () => {
});
describe('buildSpeedBuckets for a spender no application identifies', () => {
- const WORKSPACE_FALLBACKS: DefaultUsageLimitFallback[] = [
+ const WORKSPACE_DEFAULTS: SpeedLimitDefault[] = [
{
spenderType: 'workspace',
counterScope: 'crossWorkspace',
@@ -150,7 +151,7 @@ describe('buildSpeedBuckets for a spender no application identifies', () => {
expect(
buildBuckets({
authContext: systemContext,
- defaultUsageLimitFallbacks: WORKSPACE_FALLBACKS,
+ speedLimitDefaults: WORKSPACE_DEFAULTS,
}),
).toEqual([
expect.objectContaining({
@@ -165,7 +166,7 @@ describe('buildSpeedBuckets for a spender no application identifies', () => {
it('meters a user request against that same counter', () => {
const [bucket] = buildBuckets({
authContext: userContext,
- defaultUsageLimitFallbacks: WORKSPACE_FALLBACKS,
+ speedLimitDefaults: WORKSPACE_DEFAULTS,
});
expect(bucket.key).toBe('{server}:speed:API:API_REQUEST:workspace:-:10');
@@ -181,7 +182,7 @@ describe('buildSpeedBuckets for a spender no application identifies', () => {
expect(
buildBuckets({
authContext: unidentifiedApplicationContext,
- defaultUsageLimitFallbacks: [
+ speedLimitDefaults: [
{
spenderType: 'application',
counterScope: 'crossWorkspace',
@@ -195,11 +196,11 @@ describe('buildSpeedBuckets for a spender no application identifies', () => {
});
});
-describe('buildSpeedBuckets with rules configured', () => {
- it('shares one counter between every api key when the rule names none', () => {
+describe('buildSpeedBuckets with limits configured', () => {
+ it('shares one counter between every api key when the limit names none', () => {
const [bucket] = buildBuckets({
authContext: apiKeyContext,
- rules: [buildRule({ spenderId: '', limitValue: 10, windowSeconds: 1 })],
+ limits: [buildLimit({ spenderId: '', limitValue: 10, periodCount: 1 })],
});
expect(bucket).toMatchObject({
@@ -212,9 +213,9 @@ describe('buildSpeedBuckets with rules configured', () => {
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 }),
+ limits: [
+ buildLimit({ id: 'shared', spenderId: '', limitValue: 10 }),
+ buildLimit({ id: 'own', spenderId: 'key-1', limitValue: 5 }),
],
});
@@ -227,7 +228,7 @@ describe('buildSpeedBuckets with rules configured', () => {
it('keeps a named api key charged for the defaults', () => {
const buckets = buildBuckets({
authContext: apiKeyContext,
- rules: [buildRule({ spenderId: 'key-1', limitValue: 5 })],
+ limits: [buildLimit({ spenderId: 'key-1', limitValue: 5 })],
});
expect(buckets.map((bucket) => bucket.key)).toEqual([
@@ -237,10 +238,10 @@ describe('buildSpeedBuckets with rules configured', () => {
]);
});
- it('replaces every default once a rule covers the spender type', () => {
+ it('replaces every default once a limit covers the spender type', () => {
const buckets = buildBuckets({
authContext: apiKeyContext,
- rules: [buildRule({ spenderId: '', windowSeconds: 60, limitValue: 10 })],
+ limits: [buildLimit({ spenderId: '', periodCount: 60, limitValue: 10 })],
});
expect(
@@ -248,13 +249,13 @@ describe('buildSpeedBuckets with rules configured', () => {
).toEqual([[60_000, 10]]);
});
- it('tells the platform default apart from a configured rule', () => {
+ it('tells the platform default apart from a configured limit', () => {
const buckets = buildBuckets({
authContext: apiKeyContext,
- rules: [buildRule({ spenderId: 'key-1', limitValue: 5 })],
+ limits: [buildLimit({ spenderId: 'key-1', limitValue: 5 })],
});
- expect(buckets.map((bucket) => bucket.isFallback)).toEqual([
+ expect(buckets.map((bucket) => bucket.isDefault)).toEqual([
false,
true,
true,
@@ -264,7 +265,7 @@ describe('buildSpeedBuckets with rules configured', () => {
it('keeps an application charged for the ceiling every workspace shares', () => {
const buckets = buildBuckets({
authContext: applicationContext,
- rules: [buildRule({ spenderType: 'application', spenderId: '' })],
+ limits: [buildLimit({ spenderType: 'application', spenderId: '' })],
});
expect(buckets.map((bucket) => bucket.key)).toEqual([
@@ -273,11 +274,49 @@ describe('buildSpeedBuckets with rules configured', () => {
]);
});
- it('applies a workspace rule to a caller that no other rule covers', () => {
+ it('gives a limit covering every operation its own counter next to a specific one', () => {
+ const buckets = buildBuckets({
+ authContext: apiKeyContext,
+ limits: [
+ buildLimit({
+ id: 'every-operation',
+ operationType: UsageOperationType.ALL,
+ spenderId: '',
+ limitValue: 20,
+ }),
+ buildLimit({ id: 'specific', spenderId: '', limitValue: 10 }),
+ ],
+ });
+
+ expect(buckets.map((bucket) => bucket.key)).toEqual([
+ '{workspace-1}:speed:API:ALL:apiKey:-:60',
+ '{workspace-1}:speed:API:API_REQUEST:apiKey:-:60',
+ ]);
+ });
+
+ it('ignores a quota limit covering every spender', () => {
+ const buckets = buildBuckets({
+ authContext: apiKeyContext,
+ limits: [
+ buildLimit({
+ id: 'quota',
+ limitKind: 'quota',
+ spenderId: '',
+ periodCount: 1,
+ periodUnit: 'month',
+ meter: 'creditsUsedMicro',
+ }),
+ ],
+ });
+
+ expect(buckets.map((bucket) => bucket.isDefault)).toEqual([true, true]);
+ });
+
+ it('applies a workspace limit to a caller that no other limit covers', () => {
const buckets = buildBuckets({
authContext: userContext,
- rules: [
- buildRule({
+ limits: [
+ buildLimit({
spenderType: 'workspace',
spenderId: '',
limitValue: 1000,
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-spenders-from-usage-spenders.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-spenders-from-usage-spenders.util.spec.ts
new file mode 100644
index 00000000000..28e9c26c832
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-spenders-from-usage-spenders.util.spec.ts
@@ -0,0 +1,43 @@
+import { buildSpendersFromUsageSpenders } from 'src/engine/core-modules/usage-limit/utils/build-spenders-from-usage-spenders.util';
+
+describe('buildSpendersFromUsageSpenders', () => {
+ it('always charges the workspace', () => {
+ expect(buildSpendersFromUsageSpenders({})).toEqual([
+ { spenderType: 'workspace', spenderId: '' },
+ ]);
+ });
+
+ it('maps every defined id to its spender type', () => {
+ const spenders = buildSpendersFromUsageSpenders({
+ userWorkspaceId: 'user-1',
+ apiKeyId: 'api-key-1',
+ applicationId: 'app-1',
+ agentId: 'agent-1',
+ workflowId: 'workflow-1',
+ logicFunctionId: 'logic-function-1',
+ });
+
+ expect(spenders).toEqual([
+ { spenderType: 'userWorkspace', spenderId: 'user-1' },
+ { spenderType: 'apiKey', spenderId: 'api-key-1' },
+ { spenderType: 'application', spenderId: 'app-1' },
+ { spenderType: 'agent', spenderId: 'agent-1' },
+ { spenderType: 'workflow', spenderId: 'workflow-1' },
+ { spenderType: 'logicFunction', spenderId: 'logic-function-1' },
+ { spenderType: 'workspace', spenderId: '' },
+ ]);
+ });
+
+ it('ignores null and empty ids', () => {
+ const spenders = buildSpendersFromUsageSpenders({
+ userWorkspaceId: null,
+ apiKeyId: '',
+ workflowId: 'workflow-1',
+ });
+
+ expect(spenders).toEqual([
+ { spenderType: 'workflow', spenderId: 'workflow-1' },
+ { spenderType: 'workspace', spenderId: '' },
+ ]);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-limits-for-spender.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-limits-for-spender.util.spec.ts
new file mode 100644
index 00000000000..a3550b71a52
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-limits-for-spender.util.spec.ts
@@ -0,0 +1,142 @@
+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 { findLimitsForSpender } from 'src/engine/core-modules/usage-limit/utils/find-limits-for-spender.util';
+
+const buildLimit = (overrides: Partial<FlatUsageLimit>): FlatUsageLimit => ({
+ id: 'limit-id',
+ resourceType: UsageResourceType.API,
+ operationType: UsageOperationType.API_REQUEST,
+ spenderType: 'apiKey',
+ spenderId: '',
+ limitKind: 'speed',
+ periodCount: 60,
+ periodUnit: 'second',
+ meter: 'creditsUsedMicro',
+ limitValue: 100,
+ burstValue: null,
+ ...overrides,
+});
+
+describe('findLimitsForSpender', () => {
+ const spender = { spenderType: 'apiKey' as const, spenderId: 'key-1' };
+
+ it('charges a named spender against its own limit and the shared one', () => {
+ const shared = buildLimit({ id: 'shared', spenderId: '' });
+ const own = buildLimit({ id: 'own', spenderId: 'key-1', limitValue: 50 });
+
+ expect(
+ findLimitsForSpender({
+ limits: [shared, own],
+ spender,
+ operationType: UsageOperationType.API_REQUEST,
+ }),
+ ).toEqual([shared, own]);
+ });
+
+ it('charges a spender with no limit of its own against the shared limit', () => {
+ const shared = buildLimit({ id: 'shared', spenderId: '' });
+
+ expect(
+ findLimitsForSpender({
+ limits: [shared],
+ spender,
+ operationType: UsageOperationType.API_REQUEST,
+ }),
+ ).toEqual([shared]);
+ });
+
+ it('applies a limit covering every operation of the resource', () => {
+ const wildcard = buildLimit({
+ id: 'wildcard',
+ operationType: UsageOperationType.ALL,
+ });
+ const specific = buildLimit({ id: 'specific' });
+
+ expect(
+ findLimitsForSpender({
+ limits: [wildcard, specific],
+ spender,
+ operationType: UsageOperationType.API_REQUEST,
+ }),
+ ).toEqual([wildcard, specific]);
+ });
+
+ it('ignores a limit belonging to another spender', () => {
+ const otherKey = buildLimit({ id: 'other', spenderId: 'key-2' });
+
+ expect(
+ findLimitsForSpender({
+ limits: [otherKey],
+ spender,
+ operationType: UsageOperationType.API_REQUEST,
+ }),
+ ).toEqual([]);
+ });
+
+ it('ignores a limit scoped to another spender type', () => {
+ const application = buildLimit({
+ id: 'application',
+ spenderType: 'application',
+ spenderId: '',
+ });
+
+ expect(
+ findLimitsForSpender({
+ limits: [application],
+ spender,
+ operationType: UsageOperationType.API_REQUEST,
+ }),
+ ).toEqual([]);
+ });
+
+ it('ignores a limit scoped to a different operation', () => {
+ const otherOperation = buildLimit({
+ spenderId: 'key-1',
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ });
+
+ expect(
+ findLimitsForSpender({
+ limits: [otherOperation],
+ spender,
+ operationType: UsageOperationType.API_REQUEST,
+ }),
+ ).toEqual([]);
+ });
+
+ it('returns a burst and a sustained limit together', () => {
+ const burst = buildLimit({ id: 'burst', periodCount: 1, limitValue: 20 });
+ const sustained = buildLimit({ id: 'sustained', periodCount: 60 });
+
+ expect(
+ findLimitsForSpender({
+ limits: [burst, sustained],
+ spender,
+ operationType: UsageOperationType.API_REQUEST,
+ }),
+ ).toEqual([burst, sustained]);
+ });
+
+ it('keeps every window of the shared limits when the spender has its own limit', () => {
+ const sharedBurst = buildLimit({
+ id: 'shared-burst',
+ periodCount: 1,
+ limitValue: 20,
+ });
+ const sharedSustained = buildLimit({ id: 'shared-sustained' });
+ const own = buildLimit({
+ id: 'own',
+ spenderId: 'key-1',
+ limitValue: 5000,
+ });
+
+ expect(
+ findLimitsForSpender({
+ limits: [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__/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
deleted file mode 100644
index ad25cf31eb9..00000000000
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-rules-for-spender.util.spec.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-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__/from-usage-limit-entity-to-dto.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/from-usage-limit-entity-to-dto.util.spec.ts
new file mode 100644
index 00000000000..1e02ba16b81
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/from-usage-limit-entity-to-dto.util.spec.ts
@@ -0,0 +1,43 @@
+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 UsageLimitEntity } from 'src/engine/core-modules/usage-limit/usage-limit.entity';
+import { fromUsageLimitEntityToDto } from 'src/engine/core-modules/usage-limit/utils/from-usage-limit-entity-to-dto.util';
+
+const buildEntity = (overrides: Partial<UsageLimitEntity>): UsageLimitEntity =>
+ ({
+ id: 'usage-limit-id',
+ workspaceId: 'workspace-1',
+ resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.ALL,
+ spenderType: 'userWorkspace',
+ spenderId: '',
+ limitKind: 'quota',
+ periodCount: 1,
+ periodUnit: 'month',
+ meter: 'creditsUsedMicro',
+ limitValue: 3000,
+ burstValue: null,
+ createdAt: new Date('2026-01-01'),
+ updatedAt: new Date('2026-01-01'),
+ ...overrides,
+ }) as UsageLimitEntity;
+
+describe('fromUsageLimitEntityToDto', () => {
+ it('exposes the every-spender rule with a null spender id', () => {
+ expect(fromUsageLimitEntityToDto(buildEntity({ spenderId: '' }))).toEqual(
+ expect.objectContaining({ spenderId: null }),
+ );
+ });
+
+ it('keeps a named spender id', () => {
+ expect(
+ fromUsageLimitEntityToDto(
+ buildEntity({ spenderId: '20202020-1c25-4d02-bf25-6aeccf7ea419' }),
+ ),
+ ).toEqual(
+ expect.objectContaining({
+ spenderId: '20202020-1c25-4d02-bf25-6aeccf7ea419',
+ }),
+ );
+ });
+});
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
index 0d069991dc9..ff132b947bc 100644
--- 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
@@ -2,6 +2,7 @@ import {
BaseGraphQLError,
ErrorCode,
} from 'src/engine/core-modules/graphql/utils/graphql-errors.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 {
UsageLimitException,
@@ -16,13 +17,16 @@ const buildExhaustedScope = (
): ExhaustedScope => ({
resourceType: UsageResourceType.API,
limitKind: 'speed',
+ exhaustedKind: 'limit',
spenderType: 'apiKey',
spenderId: 'key-1',
+ operationType: UsageOperationType.API_REQUEST,
limitValue: 3,
remaining: 0,
- windowSeconds: 60,
+ periodCount: 60,
+ periodUnit: 'second',
retryAfterMs: 11983,
- isFallback: true,
+ isDefault: true,
...overrides,
});
@@ -59,9 +63,11 @@ describe('usageLimitToGraphqlApiExceptionHandler', () => {
expect(error.extensions).toMatchObject({
limitKind: 'speed',
+ exhaustedKind: 'limit',
limit: 3,
remaining: 0,
- windowSeconds: 60,
+ periodCount: 60,
+ periodUnit: 'second',
retryAfterMs: 11983,
scope: { spenderType: 'apiKey', spenderId: 'key-1' },
});
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
index a0f40bb33f5..e4076d305ce 100644
--- 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
@@ -1,5 +1,6 @@
import { HttpStatus } from '@nestjs/common';
+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 { UsageLimitHttpException } from 'src/engine/core-modules/usage-limit/exceptions/usage-limit-http.exception';
import {
@@ -14,26 +15,29 @@ const buildExhaustedScope = (
): ExhaustedScope => ({
resourceType: UsageResourceType.API,
limitKind: 'speed',
+ exhaustedKind: 'limit',
spenderType: 'apiKey',
spenderId: 'key-1',
+ operationType: UsageOperationType.API_REQUEST,
limitValue: 3,
remaining: 0,
- windowSeconds: 60,
+ periodCount: 60,
+ periodUnit: 'second',
retryAfterMs: 11983,
- isFallback: true,
+ isDefault: true,
...overrides,
});
const catchThrown = (
exhaustedScope?: ExhaustedScope,
+ {
+ message = 'Rate limit exceeded for apiKey: 3 requests per 60s.',
+ code = UsageLimitExceptionCode.RATE_LIMITED,
+ }: { message?: string; code?: UsageLimitExceptionCode } = {},
): UsageLimitHttpException => {
try {
usageLimitToRestApiExceptionHandler(
- new UsageLimitException(
- 'Rate limit exceeded for apiKey: 3 requests per 60s.',
- UsageLimitExceptionCode.RATE_LIMITED,
- { exhaustedScope },
- ),
+ new UsageLimitException(message, code, { exhaustedScope }),
);
} catch (error) {
return error as UsageLimitHttpException;
@@ -52,10 +56,16 @@ describe('usageLimitToRestApiExceptionHandler', () => {
error: 'RATE_LIMITED',
messages: ['Rate limit exceeded for apiKey: 3 requests per 60s.'],
limitKind: 'speed',
- scope: { spenderType: 'apiKey', spenderId: 'key-1' },
+ exhaustedKind: 'limit',
+ scope: {
+ spenderType: 'apiKey',
+ spenderId: 'key-1',
+ operationType: UsageOperationType.API_REQUEST,
+ },
limit: 3,
remaining: 0,
- windowSeconds: 60,
+ periodCount: 60,
+ periodUnit: 'second',
retryAfterSeconds: 12,
});
});
@@ -78,6 +88,64 @@ describe('usageLimitToRestApiExceptionHandler', () => {
).toBe('1');
});
+ it('answers 429 with retry headers when a configured quota is exhausted', () => {
+ const error = catchThrown(
+ buildExhaustedScope({
+ resourceType: UsageResourceType.AI,
+ limitKind: 'quota',
+ operationType: UsageOperationType.ALL,
+ periodCount: 1,
+ periodUnit: 'month',
+ }),
+ {
+ message: 'Usage limit reached for apiKey',
+ code: UsageLimitExceptionCode.QUOTA_EXHAUSTED,
+ },
+ );
+
+ expect(error.getStatus()).toBe(HttpStatus.TOO_MANY_REQUESTS);
+ expect(error.getResponseBody()).toEqual(
+ expect.objectContaining({
+ statusCode: HttpStatus.TOO_MANY_REQUESTS,
+ error: 'QUOTA_EXHAUSTED',
+ limitKind: 'quota',
+ exhaustedKind: 'limit',
+ }),
+ );
+ expect(error.getResponseHeaders()).toEqual(
+ expect.objectContaining({ 'Retry-After': '12' }),
+ );
+ });
+
+ it('answers 402 without retry headers when the credit allowance is exhausted', () => {
+ const error = catchThrown(
+ buildExhaustedScope({
+ resourceType: UsageResourceType.AI,
+ limitKind: 'quota',
+ exhaustedKind: 'allowance',
+ spenderType: 'workspace',
+ spenderId: null,
+ operationType: UsageOperationType.ALL,
+ periodCount: null,
+ periodUnit: null,
+ }),
+ {
+ message: 'Credit allowance exhausted for this billing period',
+ code: UsageLimitExceptionCode.QUOTA_EXHAUSTED,
+ },
+ );
+
+ expect(error.getStatus()).toBe(HttpStatus.PAYMENT_REQUIRED);
+ expect(error.getResponseBody()).toEqual(
+ expect.objectContaining({
+ statusCode: HttpStatus.PAYMENT_REQUIRED,
+ error: 'QUOTA_EXHAUSTED',
+ exhaustedKind: 'allowance',
+ }),
+ );
+ expect(error.getResponseHeaders()).toEqual({});
+ });
+
it('keeps the message readable for logs', () => {
expect(catchThrown(buildExhaustedScope()).message).toBe(
'Rate limit exceeded for apiKey: 3 requests per 60s.',
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 454a0fc7f64..61c8c4d958f 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
@@ -4,32 +4,46 @@ import { type UpsertUsageLimitInput } from 'src/engine/core-modules/usage-limit/
import { UsageLimitExceptionCode } from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';
import { validateUsageLimitAgainstDefinition } from 'src/engine/core-modules/usage-limit/utils/validate-usage-limit-against-definition.util';
-const validSpeedRule: UpsertUsageLimitInput = {
+const validSpeedLimit: UpsertUsageLimitInput = {
resourceType: UsageResourceType.API,
operationType: UsageOperationType.API_REQUEST,
spenderType: 'apiKey',
spenderId: '20202020-1c25-4d02-bf25-6aeccf7ea419',
limitKind: 'speed',
- windowSeconds: 60,
+ periodCount: 60,
+ periodUnit: 'second',
+ meter: 'quantity',
limitValue: 100,
};
+const validQuotaLimit: UpsertUsageLimitInput = {
+ resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ spenderType: 'workspace',
+ spenderId: null,
+ limitKind: 'quota',
+ periodCount: 1,
+ periodUnit: 'month',
+ meter: 'creditsUsedMicro',
+ limitValue: 1_000_000,
+};
+
describe('validateUsageLimitAgainstDefinition', () => {
- it('accepts a rule the definition allows', () => {
+ it('accepts a limit the definition allows', () => {
expect(() =>
- validateUsageLimitAgainstDefinition(validSpeedRule),
+ validateUsageLimitAgainstDefinition(validSpeedLimit),
).not.toThrow();
});
it('rejects a resource that has no definition', () => {
expect(() =>
validateUsageLimitAgainstDefinition({
- ...validSpeedRule,
+ ...validSpeedLimit,
resourceType: UsageResourceType.STORAGE,
}),
).toThrow(
expect.objectContaining({
- code: UsageLimitExceptionCode.LIMIT_RULE_INVALID,
+ code: UsageLimitExceptionCode.LIMIT_INVALID,
}),
);
});
@@ -37,12 +51,12 @@ describe('validateUsageLimitAgainstDefinition', () => {
it('rejects an operation the resource does not meter', () => {
expect(() =>
validateUsageLimitAgainstDefinition({
- ...validSpeedRule,
+ ...validSpeedLimit,
operationType: UsageOperationType.EMAIL_SEND,
}),
).toThrow(
expect.objectContaining({
- code: UsageLimitExceptionCode.LIMIT_RULE_INVALID,
+ code: UsageLimitExceptionCode.LIMIT_INVALID,
}),
);
});
@@ -50,39 +64,52 @@ describe('validateUsageLimitAgainstDefinition', () => {
it('refuses to rate-limit a human, because the definition does not allow that scope', () => {
expect(() =>
validateUsageLimitAgainstDefinition({
- ...validSpeedRule,
+ ...validSpeedLimit,
spenderType: 'userWorkspace',
}),
).toThrow(
expect.objectContaining({
- code: UsageLimitExceptionCode.LIMIT_RULE_INVALID,
+ code: UsageLimitExceptionCode.LIMIT_INVALID,
+ }),
+ );
+ });
+
+ it('rejects a speed limit without a rolling window', () => {
+ expect(() =>
+ validateUsageLimitAgainstDefinition({
+ ...validSpeedLimit,
+ periodUnit: 'month',
+ }),
+ ).toThrow(
+ expect.objectContaining({
+ code: UsageLimitExceptionCode.LIMIT_INVALID,
}),
);
});
- it('rejects a speed rule with no window', () => {
+ it('rejects a speed limit metered on credits', () => {
expect(() =>
validateUsageLimitAgainstDefinition({
- ...validSpeedRule,
- windowSeconds: 0,
+ ...validSpeedLimit,
+ meter: 'creditsUsedMicro',
}),
).toThrow(
expect.objectContaining({
- code: UsageLimitExceptionCode.LIMIT_RULE_INVALID,
+ code: UsageLimitExceptionCode.LIMIT_INVALID,
}),
);
});
- it('rejects a workspace rule, because the definition does not allow that scope', () => {
+ it('rejects a workspace limit, because the definition does not allow that scope', () => {
expect(() =>
validateUsageLimitAgainstDefinition({
- ...validSpeedRule,
+ ...validSpeedLimit,
spenderType: 'workspace',
spenderId: null,
}),
).toThrow(
expect.objectContaining({
- code: UsageLimitExceptionCode.LIMIT_RULE_INVALID,
+ code: UsageLimitExceptionCode.LIMIT_INVALID,
}),
);
});
@@ -90,22 +117,135 @@ describe('validateUsageLimitAgainstDefinition', () => {
it('rejects a spender id that is not a uuid', () => {
expect(() =>
validateUsageLimitAgainstDefinition({
- ...validSpeedRule,
+ ...validSpeedLimit,
spenderId: 'key-1',
}),
).toThrow(
expect.objectContaining({
- code: UsageLimitExceptionCode.LIMIT_RULE_INVALID,
+ code: UsageLimitExceptionCode.LIMIT_INVALID,
}),
);
});
- it('accepts a rule targeting every spender of a type', () => {
+ it('accepts a limit targeting every spender of a type', () => {
expect(() =>
validateUsageLimitAgainstDefinition({
- ...validSpeedRule,
+ ...validSpeedLimit,
spenderId: null,
}),
).not.toThrow();
});
+
+ it('accepts a monthly credit quota on the workspace', () => {
+ expect(() =>
+ validateUsageLimitAgainstDefinition(validQuotaLimit),
+ ).not.toThrow();
+ });
+
+ it('accepts a quota scoped to one agent', () => {
+ expect(() =>
+ validateUsageLimitAgainstDefinition({
+ ...validQuotaLimit,
+ spenderType: 'agent',
+ spenderId: '20202020-1c25-4d02-bf25-6aeccf7ea419',
+ }),
+ ).not.toThrow();
+ });
+
+ it('accepts a quota covering every operation of the resource', () => {
+ expect(() =>
+ validateUsageLimitAgainstDefinition({
+ ...validQuotaLimit,
+ operationType: UsageOperationType.ALL,
+ }),
+ ).not.toThrow();
+ });
+
+ it('rejects a quota on a rolling window', () => {
+ expect(() =>
+ validateUsageLimitAgainstDefinition({
+ ...validQuotaLimit,
+ periodUnit: 'second',
+ }),
+ ).toThrow(
+ expect.objectContaining({
+ code: UsageLimitExceptionCode.LIMIT_INVALID,
+ }),
+ );
+ });
+
+ it('rejects a quota with a burst value', () => {
+ expect(() =>
+ validateUsageLimitAgainstDefinition({
+ ...validQuotaLimit,
+ burstValue: 200,
+ }),
+ ).toThrow(
+ expect.objectContaining({
+ code: UsageLimitExceptionCode.LIMIT_INVALID,
+ }),
+ );
+ });
+
+ it('accepts an absolute weekly quota', () => {
+ expect(() =>
+ validateUsageLimitAgainstDefinition({
+ ...validQuotaLimit,
+ periodUnit: 'week',
+ limitValue: 5_000_000,
+ }),
+ ).not.toThrow();
+ });
+
+ it('rejects a quota spanning several periods', () => {
+ expect(() =>
+ validateUsageLimitAgainstDefinition({
+ ...validQuotaLimit,
+ periodUnit: 'week',
+ periodCount: 2,
+ }),
+ ).toThrow(
+ expect.objectContaining({
+ code: UsageLimitExceptionCode.LIMIT_INVALID,
+ }),
+ );
+ });
+
+ it('accepts a token quota on one operation', () => {
+ expect(() =>
+ validateUsageLimitAgainstDefinition({
+ ...validQuotaLimit,
+ meter: 'quantity',
+ limitValue: 1_000_000,
+ }),
+ ).not.toThrow();
+ });
+
+ it('rejects a quantity quota covering every operation', () => {
+ expect(() =>
+ validateUsageLimitAgainstDefinition({
+ ...validQuotaLimit,
+ operationType: UsageOperationType.ALL,
+ meter: 'quantity',
+ limitValue: 1_000_000,
+ }),
+ ).toThrow(
+ expect.objectContaining({
+ code: UsageLimitExceptionCode.LIMIT_INVALID,
+ }),
+ );
+ });
+
+ it('rejects a quota on a spender type the resource does not allow', () => {
+ expect(() =>
+ validateUsageLimitAgainstDefinition({
+ ...validQuotaLimit,
+ spenderType: 'workflow',
+ }),
+ ).toThrow(
+ expect.objectContaining({
+ code: UsageLimitExceptionCode.LIMIT_INVALID,
+ }),
+ );
+ });
});
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-default-speed-bucket.util.ts
similarity index 75%
rename from packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-fallback-speed-bucket.util.ts
rename to packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-default-speed-bucket.util.ts
index 325eb50eb03..81377a048a8 100644
--- 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-default-speed-bucket.util.ts
@@ -1,7 +1,7 @@
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 SpeedLimitDefault } from 'src/engine/core-modules/usage-limit/types/speed-limit-default.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';
@@ -9,20 +9,20 @@ import { getApplicationUniversalIdentifier } from 'src/engine/core-modules/usage
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,
+export const buildDefaultSpeedBucket = ({
+ speedLimitDefault,
spender,
authContext,
resourceType,
operationType,
}: {
- fallback: DefaultUsageLimitFallback;
+ speedLimitDefault: SpeedLimitDefault;
spender: Spender;
authContext: WorkspaceAuthContext;
resourceType: UsageResourceType;
operationType: UsageOperationType;
}): SpeedBucketRequest | null => {
- const isCrossWorkspace = fallback.counterScope === 'crossWorkspace';
+ const isCrossWorkspace = speedLimitDefault.counterScope === 'crossWorkspace';
const isIdentifiedAcrossWorkspaces = spender.spenderType === 'application';
const universalIdentifier = getApplicationUniversalIdentifier(authContext);
@@ -41,19 +41,19 @@ export const buildFallbackSpeedBucket = ({
return {
key: buildSpeedBucketKey({
- counterScope: fallback.counterScope,
+ counterScope: speedLimitDefault.counterScope,
workspaceId: authContext.workspace.id,
resourceType,
operationType,
spenderType: spender.spenderType,
spenderId,
- windowSeconds: Math.ceil(fallback.windowMs / 1000),
+ windowSeconds: Math.ceil(speedLimitDefault.windowMs / 1000),
}),
- burst: fallback.maxTokens,
- refillPerWindow: fallback.maxTokens,
- windowMs: fallback.windowMs,
+ burst: speedLimitDefault.maxTokens,
+ refillPerWindow: speedLimitDefault.maxTokens,
+ windowMs: speedLimitDefault.windowMs,
spenderType: spender.spenderType,
spenderId,
- isFallback: true,
+ isDefault: true,
};
};
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
index 36f6e8d31f5..657a073473b 100644
--- 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
@@ -2,13 +2,14 @@ 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 SpeedLimitDefault } from 'src/engine/core-modules/usage-limit/types/speed-limit-default.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 { buildDefaultSpeedBucket } from 'src/engine/core-modules/usage-limit/utils/build-default-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 { findLimitsForSpender } from 'src/engine/core-modules/usage-limit/utils/find-limits-for-spender.util';
+import { normalizeSpenderId } from 'src/engine/core-modules/usage-limit/utils/normalize-spender-id.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';
@@ -17,14 +18,14 @@ const bucketSpecificity = (bucket: SpeedBucketRequest): number =>
(isDefined(bucket.spenderId) ? 0 : 1);
export const buildSpeedBuckets = ({
- defaultUsageLimitFallbacks,
- rules,
+ speedLimitDefaults,
+ limits,
authContext,
resourceType,
operationType,
}: {
- defaultUsageLimitFallbacks: DefaultUsageLimitFallback[];
- rules: FlatUsageLimit[];
+ speedLimitDefaults: SpeedLimitDefault[];
+ limits: FlatUsageLimit[];
authContext: WorkspaceAuthContext;
resourceType: UsageResourceType;
operationType: UsageOperationType;
@@ -32,39 +33,43 @@ export const buildSpeedBuckets = ({
const spenders = buildSpendersFromAuthContext(authContext);
const buckets = spenders.flatMap((spender) => {
- const spenderRules = findRulesForSpender({ rules, spender, operationType });
+ const spenderLimits = findLimitsForSpender({
+ limits,
+ spender,
+ operationType,
+ }).filter((limit) => limit.limitKind === 'speed');
- const ruleBuckets = spenderRules.map((rule) => ({
+ const limitBuckets = spenderLimits.map((limit) => ({
key: buildSpeedBucketKey({
counterScope: 'perWorkspace',
workspaceId: authContext.workspace.id,
resourceType,
- operationType,
+ operationType: limit.operationType,
spenderType: spender.spenderType,
- spenderId: rule.spenderId,
- windowSeconds: rule.windowSeconds,
+ spenderId: limit.spenderId,
+ windowSeconds: limit.periodCount,
}),
- burst: rule.burstValue ?? rule.limitValue,
- refillPerWindow: rule.limitValue,
- windowMs: rule.windowSeconds * 1000,
+ burst: limit.burstValue ?? limit.limitValue,
+ refillPerWindow: limit.limitValue,
+ windowMs: limit.periodCount * 1000,
spenderType: spender.spenderType,
- spenderId: rule.spenderId === '' ? null : rule.spenderId,
- isFallback: false,
+ spenderId: normalizeSpenderId(limit.spenderId),
+ isDefault: false,
}));
- const hasRuleForEverySpender = spenderRules.some(
- (rule) => rule.spenderId === '',
+ const hasLimitForEverySpender = spenderLimits.some(
+ (limit) => limit.spenderId === '',
);
- const fallbackBuckets = defaultUsageLimitFallbacks
+ const defaultBuckets = speedLimitDefaults
.filter(
- (fallback) =>
- fallback.spenderType === spender.spenderType &&
- !(fallback.isOverridable && hasRuleForEverySpender),
+ (speedLimitDefault) =>
+ speedLimitDefault.spenderType === spender.spenderType &&
+ !(speedLimitDefault.isOverridable && hasLimitForEverySpender),
)
- .map((fallback) =>
- buildFallbackSpeedBucket({
- fallback,
+ .map((speedLimitDefault) =>
+ buildDefaultSpeedBucket({
+ speedLimitDefault,
spender,
authContext,
resourceType,
@@ -73,7 +78,7 @@ export const buildSpeedBuckets = ({
)
.filter(isDefined);
- return [...ruleBuckets, ...fallbackBuckets];
+ return [...limitBuckets, ...defaultBuckets];
});
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-usage-spenders.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-spenders-from-usage-spenders.util.ts
new file mode 100644
index 00000000000..92010bcc38b
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-spenders-from-usage-spenders.util.ts
@@ -0,0 +1,30 @@
+import { isNonEmptyString } from '@sniptt/guards';
+
+import { type Spender } from 'src/engine/core-modules/usage-limit/types/spender.type';
+import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
+import { type UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';
+
+const SPENDER_TYPE_BY_USAGE_SPENDERS_KEY: Record<
+ keyof UsageSpenders,
+ SpenderType
+> = {
+ userWorkspaceId: 'userWorkspace',
+ apiKeyId: 'apiKey',
+ applicationId: 'application',
+ agentId: 'agent',
+ workflowId: 'workflow',
+ logicFunctionId: 'logicFunction',
+};
+
+export const buildSpendersFromUsageSpenders = (
+ usageSpenders: UsageSpenders,
+): Spender[] => [
+ ...Object.entries(SPENDER_TYPE_BY_USAGE_SPENDERS_KEY).flatMap(
+ ([usageSpendersKey, spenderType]) => {
+ const spenderId = usageSpenders[usageSpendersKey as keyof UsageSpenders];
+
+ return isNonEmptyString(spenderId) ? [{ spenderType, spenderId }] : [];
+ },
+ ),
+ { spenderType: 'workspace', spenderId: '' },
+];
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-limits-for-spender.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-limits-for-spender.util.ts
new file mode 100644
index 00000000000..2070c40e744
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-limits-for-spender.util.ts
@@ -0,0 +1,20 @@
+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 { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+
+export const findLimitsForSpender = ({
+ limits,
+ spender,
+ operationType,
+}: {
+ limits: FlatUsageLimit[];
+ spender: Spender;
+ operationType: UsageOperationType;
+}): FlatUsageLimit[] =>
+ limits.filter(
+ (limit) =>
+ limit.spenderType === spender.spenderType &&
+ (limit.operationType === UsageOperationType.ALL ||
+ limit.operationType === operationType) &&
+ (limit.spenderId === '' || limit.spenderId === spender.spenderId),
+ );
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
deleted file mode 100644
index 18e90ae6757..00000000000
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-rules-for-spender.util.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-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/find-usage-limit-definition.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-usage-limit-definition.util.ts
index c7783d51a8f..6962a15c799 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-usage-limit-definition.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-usage-limit-definition.util.ts
@@ -1,13 +1,13 @@
import { USAGE_LIMIT_DEFINITIONS } from 'src/engine/core-modules/usage-limit/constants/usage-limit-definitions.constant';
import { type LimitKind } from 'src/engine/core-modules/usage-limit/types/limit-kind.type';
-import { type UsageLimitDefinition } from 'src/engine/core-modules/usage-limit/types/usage-limit-definition.type';
+import { type UsageLimitDefinitions } from 'src/engine/core-modules/usage-limit/types/usage-limit-definition.type';
import { type UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
-export const findUsageLimitDefinition = ({
+export const findUsageLimitDefinition = <TLimitKind extends LimitKind>({
resourceType,
limitKind,
}: {
resourceType: UsageResourceType;
- limitKind: LimitKind;
-}): UsageLimitDefinition | undefined =>
- USAGE_LIMIT_DEFINITIONS[resourceType]?.[limitKind];
+ limitKind: TLimitKind;
+}): UsageLimitDefinitions[TLimitKind] =>
+ USAGE_LIMIT_DEFINITIONS[resourceType][limitKind];
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/from-usage-limit-entity-to-dto.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/from-usage-limit-entity-to-dto.util.ts
new file mode 100644
index 00000000000..6ed4cd6405f
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/from-usage-limit-entity-to-dto.util.ts
@@ -0,0 +1,21 @@
+import { type UsageLimitDTO } from 'src/engine/core-modules/usage-limit/dtos/usage-limit.dto';
+import { type UsageLimitEntity } from 'src/engine/core-modules/usage-limit/usage-limit.entity';
+import { normalizeSpenderId } from 'src/engine/core-modules/usage-limit/utils/normalize-spender-id.util';
+
+export const fromUsageLimitEntityToDto = (
+ usageLimit: UsageLimitEntity,
+): UsageLimitDTO => ({
+ id: usageLimit.id,
+ resourceType: usageLimit.resourceType,
+ operationType: usageLimit.operationType,
+ spenderType: usageLimit.spenderType,
+ spenderId: normalizeSpenderId(usageLimit.spenderId),
+ limitKind: usageLimit.limitKind,
+ periodCount: usageLimit.periodCount,
+ periodUnit: usageLimit.periodUnit,
+ meter: usageLimit.meter,
+ limitValue: usageLimit.limitValue,
+ burstValue: usageLimit.burstValue,
+ createdAt: usageLimit.createdAt,
+ updatedAt: usageLimit.updatedAt,
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/from-usage-limit-entity-to-flat.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/from-usage-limit-entity-to-flat.util.ts
index e678e740345..39753b589b6 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/from-usage-limit-entity-to-flat.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/from-usage-limit-entity-to-flat.util.ts
@@ -10,8 +10,9 @@ export const fromUsageLimitEntityToFlat = (
spenderType: usageLimit.spenderType,
spenderId: usageLimit.spenderId,
limitKind: usageLimit.limitKind,
- windowSeconds: usageLimit.windowSeconds,
- limitValueType: usageLimit.limitValueType,
+ periodCount: usageLimit.periodCount,
+ periodUnit: usageLimit.periodUnit,
+ meter: usageLimit.meter,
limitValue: usageLimit.limitValue,
burstValue: usageLimit.burstValue,
});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/normalize-spender-id.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/normalize-spender-id.util.ts
new file mode 100644
index 00000000000..03f4f981957
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/normalize-spender-id.util.ts
@@ -0,0 +1,4 @@
+// The entity stores '' for "every spender" so the unique index can match it;
+// outward shapes carry null instead.
+export const normalizeSpenderId = (spenderId: string): string | null =>
+ spenderId === '' ? null : spenderId;
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
index 3ab06ce3cba..0db3b284f04 100644
--- 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
@@ -28,13 +28,16 @@ export const usageLimitToGraphqlApiExceptionHandler = (
{
...commonExtensions,
limitKind: exhaustedScope.limitKind,
+ exhaustedKind: exhaustedScope.exhaustedKind,
limit: exhaustedScope.limitValue,
remaining: exhaustedScope.remaining,
- windowSeconds: exhaustedScope.windowSeconds,
+ periodCount: exhaustedScope.periodCount,
+ periodUnit: exhaustedScope.periodUnit,
retryAfterMs: exhaustedScope.retryAfterMs,
scope: {
spenderType: exhaustedScope.spenderType,
spenderId: exhaustedScope.spenderId,
+ operationType: exhaustedScope.operationType,
},
},
);
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
index ca4fbf33015..df8f40d5548 100644
--- 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
@@ -8,32 +8,51 @@ import { buildRateLimitResponseHeaders } from 'src/engine/core-modules/usage-lim
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 = (
+export const buildUsageLimitHttpException = (
error: UsageLimitException,
-): never => {
+): HttpException => {
const { exhaustedScope } = error;
+ // Paying only unblocks an exhausted allowance; configured limits reset with
+ // time, so they answer 429 with retry headers whatever their period length.
+ const isAllowanceExhausted = exhaustedScope?.exhaustedKind === 'allowance';
+
+ const statusCode = isAllowanceExhausted
+ ? HttpStatus.PAYMENT_REQUIRED
+ : HttpStatus.TOO_MANY_REQUESTS;
+
if (!isDefined(exhaustedScope)) {
- throw new HttpException(error.message, HttpStatus.TOO_MANY_REQUESTS);
+ return new HttpException(error.message, statusCode);
}
const retryAfterSeconds = getRetryAfterSeconds(exhaustedScope.retryAfterMs);
- throw new UsageLimitHttpException(
+ return new UsageLimitHttpException(
{
- statusCode: HttpStatus.TOO_MANY_REQUESTS,
+ statusCode,
error: getUsageLimitErrorCode(error.code),
messages: [error.message],
limitKind: exhaustedScope.limitKind,
+ exhaustedKind: exhaustedScope.exhaustedKind,
scope: {
spenderType: exhaustedScope.spenderType,
spenderId: exhaustedScope.spenderId,
+ operationType: exhaustedScope.operationType,
},
limit: exhaustedScope.limitValue,
remaining: exhaustedScope.remaining,
- windowSeconds: exhaustedScope.windowSeconds,
+ periodCount: exhaustedScope.periodCount,
+ periodUnit: exhaustedScope.periodUnit,
retryAfterSeconds,
},
- buildRateLimitResponseHeaders({ exhaustedScope, retryAfterSeconds }),
+ isAllowanceExhausted
+ ? {}
+ : buildRateLimitResponseHeaders({ exhaustedScope, retryAfterSeconds }),
);
};
+
+export const usageLimitToRestApiExceptionHandler = (
+ error: UsageLimitException,
+): never => {
+ throw buildUsageLimitHttpException(error);
+};
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 39720b15b73..b3048d5142f 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
@@ -7,6 +7,7 @@ import {
UsageLimitExceptionCode,
} from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';
import { findUsageLimitDefinition } from 'src/engine/core-modules/usage-limit/utils/find-usage-limit-definition.util';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
export const validateUsageLimitAgainstDefinition = (
input: UpsertUsageLimitInput,
@@ -19,35 +20,90 @@ export const validateUsageLimitAgainstDefinition = (
if (!isDefined(definition)) {
throw new UsageLimitException(
`No ${input.limitKind} limit is defined for ${input.resourceType}`,
- UsageLimitExceptionCode.LIMIT_RULE_INVALID,
+ UsageLimitExceptionCode.LIMIT_INVALID,
);
}
- if (!definition.allowedOperationTypes.includes(input.operationType)) {
+ if (
+ input.operationType !== UsageOperationType.ALL &&
+ !definition.allowedOperationTypes.includes(input.operationType)
+ ) {
throw new UsageLimitException(
`${input.resourceType} ${input.limitKind} limits cannot target the ${input.operationType} operation`,
- UsageLimitExceptionCode.LIMIT_RULE_INVALID,
+ UsageLimitExceptionCode.LIMIT_INVALID,
);
}
if (!definition.allowedSpenderTypes.includes(input.spenderType)) {
throw new UsageLimitException(
`${input.resourceType} ${input.limitKind} limits cannot be scoped to ${input.spenderType}`,
- UsageLimitExceptionCode.LIMIT_RULE_INVALID,
+ UsageLimitExceptionCode.LIMIT_INVALID,
);
}
if (isNonEmptyString(input.spenderId) && !isValidUuid(input.spenderId)) {
throw new UsageLimitException(
`${input.spenderId} is not a valid ${input.spenderType} id`,
- UsageLimitExceptionCode.LIMIT_RULE_INVALID,
+ UsageLimitExceptionCode.LIMIT_INVALID,
);
}
- if (input.limitKind === 'speed' && input.windowSeconds <= 0) {
- throw new UsageLimitException(
- 'A speed limit needs a window longer than zero seconds',
- UsageLimitExceptionCode.LIMIT_RULE_INVALID,
- );
+ if (input.limitKind === 'speed') {
+ if (input.periodUnit !== 'second') {
+ throw new UsageLimitException(
+ 'A speed limit needs a rolling window expressed in seconds',
+ UsageLimitExceptionCode.LIMIT_INVALID,
+ );
+ }
+
+ if (input.meter !== 'quantity') {
+ throw new UsageLimitException(
+ 'A speed limit counts requests, so it is metered on quantity',
+ UsageLimitExceptionCode.LIMIT_INVALID,
+ );
+ }
+ }
+
+ if (input.limitKind === 'quota') {
+ if (input.periodUnit === 'second') {
+ throw new UsageLimitException(
+ 'A quota anchors to a calendar period, not a rolling window',
+ UsageLimitExceptionCode.LIMIT_INVALID,
+ );
+ }
+
+ if (input.periodCount !== 1) {
+ throw new UsageLimitException(
+ 'A quota covers exactly one period',
+ UsageLimitExceptionCode.LIMIT_INVALID,
+ );
+ }
+
+ if (isDefined(input.burstValue)) {
+ throw new UsageLimitException(
+ 'A quota cannot hold a burst value',
+ UsageLimitExceptionCode.LIMIT_INVALID,
+ );
+ }
+
+ if (
+ 'allowedMeters' in definition &&
+ !definition.allowedMeters.includes(input.meter)
+ ) {
+ throw new UsageLimitException(
+ `${input.resourceType} quotas cannot be metered on ${input.meter}`,
+ UsageLimitExceptionCode.LIMIT_INVALID,
+ );
+ }
+
+ if (
+ input.meter === 'quantity' &&
+ input.operationType === UsageOperationType.ALL
+ ) {
+ throw new UsageLimitException(
+ 'A quantity quota needs an operation: only credits aggregate across operations',
+ UsageLimitExceptionCode.LIMIT_INVALID,
+ );
+ }
}
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage/dtos/inputs/usage-analytics.input.ts b/packages/twenty-server/src/engine/core-modules/usage/dtos/inputs/usage-analytics.input.ts
index 530816782ce..aa3bdbf26dd 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/dtos/inputs/usage-analytics.input.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/dtos/inputs/usage-analytics.input.ts
@@ -2,6 +2,8 @@
import { Field, InputType } from '@nestjs/graphql';
+import { ArrayNotContains, IsOptional } from 'class-validator';
+
import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
@InputType()
@@ -16,5 +18,7 @@ export class UsageAnalyticsInput {
userWorkspaceId?: string;
@Field(() => [UsageOperationType], { nullable: true })
+ @IsOptional()
+ @ArrayNotContains([UsageOperationType.ALL])
operationTypes?: UsageOperationType[];
}
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 651ba4f6135..e2ae48fb319 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
@@ -3,6 +3,7 @@
import { registerEnumType } from '@nestjs/graphql';
export enum UsageOperationType {
+ ALL = 'ALL',
AI_CHAT_TOKEN = 'AI_CHAT_TOKEN',
AI_WORKFLOW_TOKEN = 'AI_WORKFLOW_TOKEN',
WORKFLOW_EXECUTION = 'WORKFLOW_EXECUTION',
diff --git a/packages/twenty-server/src/engine/workspace-cache/types/workspace-cache-key.type.ts b/packages/twenty-server/src/engine/workspace-cache/types/workspace-cache-key.type.ts
index 350d16341bb..58ddb9e13be 100644
--- a/packages/twenty-server/src/engine/workspace-cache/types/workspace-cache-key.type.ts
+++ b/packages/twenty-server/src/engine/workspace-cache/types/workspace-cache-key.type.ts
@@ -20,7 +20,7 @@ import { type AllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/
import { type UserWorkspaceRoleMap } from 'src/engine/metadata-modules/role-target/types/user-workspace-role-map';
import { type FlatRowLevelPermissionPredicateGroupMaps } from 'src/engine/metadata-modules/row-level-permission-predicate/types/flat-row-level-permission-predicate-group-maps.type';
import { type FlatRowLevelPermissionPredicateMaps } from 'src/engine/metadata-modules/row-level-permission-predicate/types/flat-row-level-permission-predicate-maps.type';
-import { type UsageLimitRules } from 'src/engine/core-modules/usage-limit/types/usage-limit-rules.type';
+import { type UsageLimits } from 'src/engine/core-modules/usage-limit/types/usage-limits.type';
export type AdditionalCacheDataMaps = {
featureFlagsMap: Record<FeatureFlagKey, boolean>;
@@ -39,7 +39,7 @@ export type AdditionalCacheDataMaps = {
graphQLResolverNameMap: Record<string, ResolverNameMapEntry>;
currentBillingSubscription: CurrentBillingSubscription;
workflowAutomatedTriggerMaps: WorkflowAutomatedTriggerMaps;
- usageLimitRules: UsageLimitRules;
+ usageLimits: UsageLimits;
};
export type WorkspaceCacheDataMap = AllFlatEntityMaps<true> &
diff --git a/packages/twenty-server/src/modules/emailing/services/message-campaign-delivery.service.ts b/packages/twenty-server/src/modules/emailing/services/message-campaign-delivery.service.ts
index 4991de8a37a..f4530076c7c 100644
--- a/packages/twenty-server/src/modules/emailing/services/message-campaign-delivery.service.ts
+++ b/packages/twenty-server/src/modules/emailing/services/message-campaign-delivery.service.ts
@@ -187,7 +187,10 @@ export class MessageCampaignDeliveryService {
error.exhaustedScope?.retryAfterMs ?? 0,
SEND_SLOT_RETRY.minDelayMs,
),
- windowMs: (error.exhaustedScope?.windowSeconds ?? 0) * 1000,
+ windowMs:
+ error.exhaustedScope?.periodUnit === 'second'
+ ? (error.exhaustedScope.periodCount ?? 0) * 1000
+ : 0,
};
}
}
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
index 8b3893c1258..af9eedcd6f1 100644
--- 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
@@ -56,7 +56,7 @@ describe('API rate limiting', () => {
const invalidateWorkspaceCaches = async () => {
const keys = [
...(await redis.keys(`*featureFlagsMap:${SEED_APPLE_WORKSPACE_ID}*`)),
- ...(await redis.keys(`*usageLimitRules:${SEED_APPLE_WORKSPACE_ID}*`)),
+ ...(await redis.keys(`*usageLimits:${SEED_APPLE_WORKSPACE_ID}*`)),
];
if (keys.length > 0) {
@@ -145,8 +145,9 @@ describe('API rate limiting', () => {
spenderType: 'apiKey',
spenderId: apiKeyId,
limitKind: 'speed',
- windowSeconds: WINDOW_SECONDS,
- limitValueType: 'absolute',
+ periodCount: WINDOW_SECONDS,
+ periodUnit: 'second',
+ meter: 'quantity',
limitValue: LIMIT_VALUE,
burstValue: LIMIT_VALUE,
},
@@ -203,9 +204,11 @@ describe('API rate limiting', () => {
expect(extensions).toMatchObject({
code: 'RATE_LIMITED',
limitKind: 'speed',
+ exhaustedKind: 'limit',
limit: LIMIT_VALUE,
remaining: 0,
- windowSeconds: WINDOW_SECONDS,
+ periodCount: WINDOW_SECONDS,
+ periodUnit: 'second',
scope: { spenderType: 'apiKey', spenderId: apiKeyId },
});
expect(extensions.retryAfterMs).toBeGreaterThan(0);
@@ -245,9 +248,11 @@ describe('API rate limiting', () => {
statusCode: 429,
error: 'RATE_LIMITED',
limitKind: 'speed',
+ exhaustedKind: 'limit',
limit: LIMIT_VALUE,
remaining: 0,
- windowSeconds: WINDOW_SECONDS,
+ periodCount: WINDOW_SECONDS,
+ periodUnit: 'second',
retryAfterSeconds: 1,
scope: { spenderType: 'apiKey', spenderId: apiKeyId },
});