Skip to content

The open alternative to Salesforce, designed for AI.

feat(usage-limit): cap workspace file storage with a stock limit kind (#26042)

Etienne2f56e242fe7a
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index a967348c167..4b9e685a481 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -1577,6 +1577,90 @@ type EnterpriseSubscriptionStatusDTO {
isCancellationScheduled: Boolean!
}
+type UsageQuotaDefinition {
+ resourceType: UsageResourceType!
+ limitKind: String!
+ allowedOperationTypes: [UsageOperationType!]!
+ allowedSpenderTypes: [String!]!
+ allowedMeters: [String!]!
+}
+
+enum UsageResourceType {
+ AI
+ WORKFLOW
+ APP
+ STORAGE
+ API
+ LOGIC_FUNCTION
+ EMAIL
+ WEBHOOK
+}
+
+enum UsageOperationType {
+ ALL
+ AI_CHAT_TOKEN
+ AI_WORKFLOW_TOKEN
+ WORKFLOW_EXECUTION
+ CODE_EXECUTION
+ WEB_SEARCH
+ CALL_RECORDING
+ EMAIL_SEND
+ API_REQUEST
+ WEBHOOK_CALL
+ STORAGE_FILE
+ SUBSCRIPTION
+}
+
+type UsageQuotaDefinitions {
+ definitions: [UsageQuotaDefinition!]!
+ isIntraWorkspaceLimitEntitled: Boolean!
+ hasAllowancePeriod: Boolean!
+}
+
+type UsageQuotaWithConsumption {
+ id: UUID!
+ resourceType: UsageResourceType!
+ operationType: UsageOperationType!
+ spenderType: String!
+ spenderId: String
+ spenderLabel: String
+ periodUnit: String!
+ meter: String!
+ limitValue: BigInt!
+ isEnforced: Boolean!
+ consumedValue: BigInt
+ remainingValue: BigInt
+ periodStart: DateTime
+ periodEnd: DateTime
+}
+
+"""
+The `BigInt` scalar type represents non-fractional signed whole numeric values.
+"""
+scalar BigInt
+
+type UsageQuotaScopeConsumption {
+ consumedValue: BigInt
+ periodStart: DateTime!
+ periodEnd: DateTime!
+}
+
+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!
+}
+
type FileWithSignedUrl {
id: UUID!
path: String!
@@ -1795,88 +1879,6 @@ type UsageAnalytics {
userDailyUsage: UsageUserDaily
}
-type UsageQuotaDefinition {
- resourceType: UsageResourceType!
- allowedOperationTypes: [UsageOperationType!]!
- allowedSpenderTypes: [String!]!
- allowedMeters: [String!]!
-}
-
-enum UsageResourceType {
- AI
- WORKFLOW
- APP
- STORAGE
- API
- LOGIC_FUNCTION
- EMAIL
- WEBHOOK
-}
-
-enum UsageOperationType {
- ALL
- AI_CHAT_TOKEN
- AI_WORKFLOW_TOKEN
- WORKFLOW_EXECUTION
- CODE_EXECUTION
- WEB_SEARCH
- CALL_RECORDING
- EMAIL_SEND
- API_REQUEST
- WEBHOOK_CALL
- SUBSCRIPTION
-}
-
-type UsageQuotaDefinitions {
- definitions: [UsageQuotaDefinition!]!
- isIntraWorkspaceLimitEntitled: Boolean!
- hasAllowancePeriod: Boolean!
-}
-
-type UsageQuotaWithConsumption {
- id: UUID!
- resourceType: UsageResourceType!
- operationType: UsageOperationType!
- spenderType: String!
- spenderId: String
- spenderLabel: String
- periodUnit: String!
- meter: String!
- limitValue: BigInt!
- isEnforced: Boolean!
- consumedValue: BigInt
- remainingValue: BigInt
- periodStart: DateTime
- periodEnd: DateTime
-}
-
-"""
-The `BigInt` scalar type represents non-fractional signed whole numeric values.
-"""
-scalar BigInt
-
-type UsageQuotaScopeConsumption {
- consumedValue: BigInt
- periodStart: DateTime!
- periodEnd: DateTime!
-}
-
-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!
-}
-
type ApprovedAccessDomain {
id: UUID!
domain: String!
@@ -3647,11 +3649,11 @@ type Query {
enterprisePortalSession(returnUrlPath: String): String
enterpriseCheckoutSession(billingInterval: String): String
enterpriseSubscriptionStatus: EnterpriseSubscriptionStatusDTO
- getUsageAnalytics(input: UsageAnalyticsInput): UsageAnalytics!
usageLimits: [UsageLimit!]!
usageQuotasWithConsumption: [UsageQuotaWithConsumption!]!
usageQuotaDefinitions: UsageQuotaDefinitions!
usageQuotaScopeConsumption(input: UsageQuotaScopeInput!): UsageQuotaScopeConsumption
+ getUsageAnalytics(input: UsageAnalyticsInput): UsageAnalytics!
getViewFilterGroups(viewId: String): [ViewFilterGroup!]!
getViewFilterGroup(id: String!): ViewFilterGroup
getViewFilters(viewId: String): [ViewFilter!]!
@@ -3790,13 +3792,6 @@ type Query {
currentUserApplicationAuthorizations: [ApplicationAuthorization!]!
}
-input UsageAnalyticsInput {
- periodStart: DateTime
- periodEnd: DateTime
- userWorkspaceId: String
- operationTypes: [UsageOperationType!]
-}
-
input UsageQuotaScopeInput {
resourceType: UsageResourceType!
operationType: UsageOperationType!
@@ -3806,6 +3801,13 @@ input UsageQuotaScopeInput {
meter: String!
}
+input UsageAnalyticsInput {
+ periodStart: DateTime
+ periodEnd: DateTime
+ userWorkspaceId: String
+ operationTypes: [UsageOperationType!]
+}
+
input GetApiKeyInput {
id: UUID!
}
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index 8ae50fe1eb6..3d994fbde39 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -1225,6 +1225,68 @@ export interface EnterpriseSubscriptionStatusDTO {
__typename: 'EnterpriseSubscriptionStatusDTO'
}
+export interface UsageQuotaDefinition {
+ resourceType: UsageResourceType
+ limitKind: Scalars['String']
+ allowedOperationTypes: UsageOperationType[]
+ allowedSpenderTypes: Scalars['String'][]
+ allowedMeters: Scalars['String'][]
+ __typename: 'UsageQuotaDefinition'
+}
+
+export type UsageResourceType = 'AI' | 'WORKFLOW' | 'APP' | 'STORAGE' | 'API' | 'LOGIC_FUNCTION' | 'EMAIL' | 'WEBHOOK'
+
+export type UsageOperationType = 'ALL' | 'AI_CHAT_TOKEN' | 'AI_WORKFLOW_TOKEN' | 'WORKFLOW_EXECUTION' | 'CODE_EXECUTION' | 'WEB_SEARCH' | 'CALL_RECORDING' | 'EMAIL_SEND' | 'API_REQUEST' | 'WEBHOOK_CALL' | 'STORAGE_FILE' | 'SUBSCRIPTION'
+
+export interface UsageQuotaDefinitions {
+ definitions: UsageQuotaDefinition[]
+ isIntraWorkspaceLimitEntitled: Scalars['Boolean']
+ hasAllowancePeriod: Scalars['Boolean']
+ __typename: 'UsageQuotaDefinitions'
+}
+
+export interface UsageQuotaWithConsumption {
+ id: Scalars['UUID']
+ resourceType: UsageResourceType
+ operationType: UsageOperationType
+ spenderType: Scalars['String']
+ spenderId?: Scalars['String']
+ spenderLabel?: Scalars['String']
+ periodUnit: Scalars['String']
+ meter: Scalars['String']
+ limitValue: Scalars['BigInt']
+ isEnforced: Scalars['Boolean']
+ consumedValue?: Scalars['BigInt']
+ remainingValue?: Scalars['BigInt']
+ periodStart?: Scalars['DateTime']
+ periodEnd?: Scalars['DateTime']
+ __typename: 'UsageQuotaWithConsumption'
+}
+
+export interface UsageQuotaScopeConsumption {
+ consumedValue?: Scalars['BigInt']
+ periodStart: Scalars['DateTime']
+ periodEnd: Scalars['DateTime']
+ __typename: 'UsageQuotaScopeConsumption'
+}
+
+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 interface FileWithSignedUrl {
id: Scalars['UUID']
path: Scalars['String']
@@ -1434,67 +1496,6 @@ export interface UsageAnalytics {
__typename: 'UsageAnalytics'
}
-export interface UsageQuotaDefinition {
- resourceType: UsageResourceType
- allowedOperationTypes: UsageOperationType[]
- allowedSpenderTypes: Scalars['String'][]
- allowedMeters: Scalars['String'][]
- __typename: 'UsageQuotaDefinition'
-}
-
-export type UsageResourceType = 'AI' | 'WORKFLOW' | 'APP' | 'STORAGE' | 'API' | 'LOGIC_FUNCTION' | 'EMAIL' | 'WEBHOOK'
-
-export type UsageOperationType = 'ALL' | 'AI_CHAT_TOKEN' | 'AI_WORKFLOW_TOKEN' | 'WORKFLOW_EXECUTION' | 'CODE_EXECUTION' | 'WEB_SEARCH' | 'CALL_RECORDING' | 'EMAIL_SEND' | 'API_REQUEST' | 'WEBHOOK_CALL' | 'SUBSCRIPTION'
-
-export interface UsageQuotaDefinitions {
- definitions: UsageQuotaDefinition[]
- isIntraWorkspaceLimitEntitled: Scalars['Boolean']
- hasAllowancePeriod: Scalars['Boolean']
- __typename: 'UsageQuotaDefinitions'
-}
-
-export interface UsageQuotaWithConsumption {
- id: Scalars['UUID']
- resourceType: UsageResourceType
- operationType: UsageOperationType
- spenderType: Scalars['String']
- spenderId?: Scalars['String']
- spenderLabel?: Scalars['String']
- periodUnit: Scalars['String']
- meter: Scalars['String']
- limitValue: Scalars['BigInt']
- isEnforced: Scalars['Boolean']
- consumedValue?: Scalars['BigInt']
- remainingValue?: Scalars['BigInt']
- periodStart?: Scalars['DateTime']
- periodEnd?: Scalars['DateTime']
- __typename: 'UsageQuotaWithConsumption'
-}
-
-export interface UsageQuotaScopeConsumption {
- consumedValue?: Scalars['BigInt']
- periodStart: Scalars['DateTime']
- periodEnd: Scalars['DateTime']
- __typename: 'UsageQuotaScopeConsumption'
-}
-
-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 interface ApprovedAccessDomain {
id: Scalars['UUID']
domain: Scalars['String']
@@ -3204,11 +3205,11 @@ export interface Query {
enterprisePortalSession?: Scalars['String']
enterpriseCheckoutSession?: Scalars['String']
enterpriseSubscriptionStatus?: EnterpriseSubscriptionStatusDTO
- getUsageAnalytics: UsageAnalytics
usageLimits: UsageLimit[]
usageQuotasWithConsumption: UsageQuotaWithConsumption[]
usageQuotaDefinitions: UsageQuotaDefinitions
usageQuotaScopeConsumption?: UsageQuotaScopeConsumption
+ getUsageAnalytics: UsageAnalytics
getViewFilterGroups: ViewFilterGroup[]
getViewFilterGroup?: ViewFilterGroup
getViewFilters: ViewFilter[]
@@ -4863,6 +4864,69 @@ export interface EnterpriseSubscriptionStatusDTOGenqlSelection{
__scalar?: boolean | number
}
+export interface UsageQuotaDefinitionGenqlSelection{
+ resourceType?: boolean | number
+ limitKind?: boolean | number
+ allowedOperationTypes?: boolean | number
+ allowedSpenderTypes?: boolean | number
+ allowedMeters?: boolean | number
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
+export interface UsageQuotaDefinitionsGenqlSelection{
+ definitions?: UsageQuotaDefinitionGenqlSelection
+ isIntraWorkspaceLimitEntitled?: boolean | number
+ hasAllowancePeriod?: boolean | number
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
+export interface UsageQuotaWithConsumptionGenqlSelection{
+ id?: boolean | number
+ resourceType?: boolean | number
+ operationType?: boolean | number
+ spenderType?: boolean | number
+ spenderId?: boolean | number
+ spenderLabel?: boolean | number
+ periodUnit?: boolean | number
+ meter?: boolean | number
+ limitValue?: boolean | number
+ isEnforced?: boolean | number
+ consumedValue?: boolean | number
+ remainingValue?: boolean | number
+ periodStart?: boolean | number
+ periodEnd?: boolean | number
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
+export interface UsageQuotaScopeConsumptionGenqlSelection{
+ consumedValue?: boolean | number
+ periodStart?: boolean | number
+ periodEnd?: boolean | number
+ __typename?: boolean | number
+ __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 FileWithSignedUrlGenqlSelection{
id?: boolean | number
path?: boolean | number
@@ -5079,68 +5143,6 @@ export interface UsageAnalyticsGenqlSelection{
__scalar?: boolean | number
}
-export interface UsageQuotaDefinitionGenqlSelection{
- resourceType?: boolean | number
- allowedOperationTypes?: boolean | number
- allowedSpenderTypes?: boolean | number
- allowedMeters?: boolean | number
- __typename?: boolean | number
- __scalar?: boolean | number
-}
-
-export interface UsageQuotaDefinitionsGenqlSelection{
- definitions?: UsageQuotaDefinitionGenqlSelection
- isIntraWorkspaceLimitEntitled?: boolean | number
- hasAllowancePeriod?: boolean | number
- __typename?: boolean | number
- __scalar?: boolean | number
-}
-
-export interface UsageQuotaWithConsumptionGenqlSelection{
- id?: boolean | number
- resourceType?: boolean | number
- operationType?: boolean | number
- spenderType?: boolean | number
- spenderId?: boolean | number
- spenderLabel?: boolean | number
- periodUnit?: boolean | number
- meter?: boolean | number
- limitValue?: boolean | number
- isEnforced?: boolean | number
- consumedValue?: boolean | number
- remainingValue?: boolean | number
- periodStart?: boolean | number
- periodEnd?: boolean | number
- __typename?: boolean | number
- __scalar?: boolean | number
-}
-
-export interface UsageQuotaScopeConsumptionGenqlSelection{
- consumedValue?: boolean | number
- periodStart?: boolean | number
- periodEnd?: boolean | number
- __typename?: boolean | number
- __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 ApprovedAccessDomainGenqlSelection{
id?: boolean | number
domain?: boolean | number
@@ -6946,11 +6948,11 @@ export interface QueryGenqlSelection{
enterprisePortalSession?: { __args: {returnUrlPath?: (Scalars['String'] | null)} } | boolean | number
enterpriseCheckoutSession?: { __args: {billingInterval?: (Scalars['String'] | null)} } | boolean | number
enterpriseSubscriptionStatus?: EnterpriseSubscriptionStatusDTOGenqlSelection
- getUsageAnalytics?: (UsageAnalyticsGenqlSelection & { __args?: {input?: (UsageAnalyticsInput | null)} })
usageLimits?: UsageLimitGenqlSelection
usageQuotasWithConsumption?: UsageQuotaWithConsumptionGenqlSelection
usageQuotaDefinitions?: UsageQuotaDefinitionsGenqlSelection
usageQuotaScopeConsumption?: (UsageQuotaScopeConsumptionGenqlSelection & { __args: {input: UsageQuotaScopeInput} })
+ getUsageAnalytics?: (UsageAnalyticsGenqlSelection & { __args?: {input?: (UsageAnalyticsInput | null)} })
getViewFilterGroups?: (ViewFilterGroupGenqlSelection & { __args?: {viewId?: (Scalars['String'] | null)} })
getViewFilterGroup?: (ViewFilterGroupGenqlSelection & { __args: {id: Scalars['String']} })
getViewFilters?: (ViewFilterGenqlSelection & { __args?: {viewId?: (Scalars['String'] | null)} })
@@ -7085,10 +7087,10 @@ export interface QueryGenqlSelection{
__scalar?: boolean | number
}
-export interface UsageAnalyticsInput {periodStart?: (Scalars['DateTime'] | null),periodEnd?: (Scalars['DateTime'] | null),userWorkspaceId?: (Scalars['String'] | null),operationTypes?: (UsageOperationType[] | null)}
-
export interface UsageQuotaScopeInput {resourceType: UsageResourceType,operationType: UsageOperationType,spenderType: Scalars['String'],spenderId?: (Scalars['String'] | null),periodUnit: Scalars['String'],meter: Scalars['String']}
+export interface UsageAnalyticsInput {periodStart?: (Scalars['DateTime'] | null),periodEnd?: (Scalars['DateTime'] | null),userWorkspaceId?: (Scalars['String'] | null),operationTypes?: (UsageOperationType[] | null)}
+
export interface GetApiKeyInput {id: Scalars['UUID']}
export interface AgentIdInput {
@@ -8573,6 +8575,46 @@ export interface CreateRecordExportInput {objectMetadataId: Scalars['UUID'],fiel
+ const UsageQuotaDefinition_possibleTypes: string[] = ['UsageQuotaDefinition']
+ export const isUsageQuotaDefinition = (obj?: { __typename?: any } | null): obj is UsageQuotaDefinition => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isUsageQuotaDefinition"')
+ return UsageQuotaDefinition_possibleTypes.includes(obj.__typename)
+ }
+
+
+
+ const UsageQuotaDefinitions_possibleTypes: string[] = ['UsageQuotaDefinitions']
+ export const isUsageQuotaDefinitions = (obj?: { __typename?: any } | null): obj is UsageQuotaDefinitions => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isUsageQuotaDefinitions"')
+ return UsageQuotaDefinitions_possibleTypes.includes(obj.__typename)
+ }
+
+
+
+ const UsageQuotaWithConsumption_possibleTypes: string[] = ['UsageQuotaWithConsumption']
+ export const isUsageQuotaWithConsumption = (obj?: { __typename?: any } | null): obj is UsageQuotaWithConsumption => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isUsageQuotaWithConsumption"')
+ return UsageQuotaWithConsumption_possibleTypes.includes(obj.__typename)
+ }
+
+
+
+ const UsageQuotaScopeConsumption_possibleTypes: string[] = ['UsageQuotaScopeConsumption']
+ export const isUsageQuotaScopeConsumption = (obj?: { __typename?: any } | null): obj is UsageQuotaScopeConsumption => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isUsageQuotaScopeConsumption"')
+ return UsageQuotaScopeConsumption_possibleTypes.includes(obj.__typename)
+ }
+
+
+
+ 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 FileWithSignedUrl_possibleTypes: string[] = ['FileWithSignedUrl']
export const isFileWithSignedUrl = (obj?: { __typename?: any } | null): obj is FileWithSignedUrl => {
if (!obj?.__typename) throw new Error('__typename is missing in "isFileWithSignedUrl"')
@@ -8741,46 +8783,6 @@ export interface CreateRecordExportInput {objectMetadataId: Scalars['UUID'],fiel
- const UsageQuotaDefinition_possibleTypes: string[] = ['UsageQuotaDefinition']
- export const isUsageQuotaDefinition = (obj?: { __typename?: any } | null): obj is UsageQuotaDefinition => {
- if (!obj?.__typename) throw new Error('__typename is missing in "isUsageQuotaDefinition"')
- return UsageQuotaDefinition_possibleTypes.includes(obj.__typename)
- }
-
-
-
- const UsageQuotaDefinitions_possibleTypes: string[] = ['UsageQuotaDefinitions']
- export const isUsageQuotaDefinitions = (obj?: { __typename?: any } | null): obj is UsageQuotaDefinitions => {
- if (!obj?.__typename) throw new Error('__typename is missing in "isUsageQuotaDefinitions"')
- return UsageQuotaDefinitions_possibleTypes.includes(obj.__typename)
- }
-
-
-
- const UsageQuotaWithConsumption_possibleTypes: string[] = ['UsageQuotaWithConsumption']
- export const isUsageQuotaWithConsumption = (obj?: { __typename?: any } | null): obj is UsageQuotaWithConsumption => {
- if (!obj?.__typename) throw new Error('__typename is missing in "isUsageQuotaWithConsumption"')
- return UsageQuotaWithConsumption_possibleTypes.includes(obj.__typename)
- }
-
-
-
- const UsageQuotaScopeConsumption_possibleTypes: string[] = ['UsageQuotaScopeConsumption']
- export const isUsageQuotaScopeConsumption = (obj?: { __typename?: any } | null): obj is UsageQuotaScopeConsumption => {
- if (!obj?.__typename) throw new Error('__typename is missing in "isUsageQuotaScopeConsumption"')
- return UsageQuotaScopeConsumption_possibleTypes.includes(obj.__typename)
- }
-
-
-
- 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 ApprovedAccessDomain_possibleTypes: string[] = ['ApprovedAccessDomain']
export const isApprovedAccessDomain = (obj?: { __typename?: any } | null): obj is ApprovedAccessDomain => {
if (!obj?.__typename) throw new Error('__typename is missing in "isApprovedAccessDomain"')
@@ -10715,6 +10717,32 @@ export const enumLogicFunctionExecutionStatus = {
ERROR: 'ERROR' 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,
+ WEBHOOK: 'WEBHOOK' 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,
+ WEBHOOK_CALL: 'WEBHOOK_CALL' as const,
+ STORAGE_FILE: 'STORAGE_FILE' as const,
+ SUBSCRIPTION: 'SUBSCRIPTION' as const
+}
+
export const enumNavigationMenuItemType = {
VIEW: 'VIEW' as const,
FOLDER: 'FOLDER' as const,
@@ -10749,31 +10777,6 @@ export const enumDatabaseEventAction = {
UPSERTED: 'UPSERTED' 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,
- WEBHOOK: 'WEBHOOK' 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,
- WEBHOOK_CALL: 'WEBHOOK_CALL' as const,
- SUBSCRIPTION: 'SUBSCRIPTION' as const
-}
-
export const enumEmailConnectionSecurity = {
NONE: 'NONE' as const,
STARTTLS: 'STARTTLS' 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 98168dfff4a..bb141bb2ea6 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts
@@ -54,13 +54,13 @@ export default {
129,
144,
148,
- 155,
- 157,
- 160,
- 162,
- 177,
- 178,
- 181,
+ 152,
+ 153,
+ 156,
+ 163,
+ 165,
+ 168,
+ 170,
191,
196,
203,
@@ -3032,6 +3032,148 @@ export default {
1
]
},
+ "UsageQuotaDefinition": {
+ "resourceType": [
+ 152
+ ],
+ "limitKind": [
+ 1
+ ],
+ "allowedOperationTypes": [
+ 153
+ ],
+ "allowedSpenderTypes": [
+ 1
+ ],
+ "allowedMeters": [
+ 1
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "UsageResourceType": {},
+ "UsageOperationType": {},
+ "UsageQuotaDefinitions": {
+ "definitions": [
+ 151
+ ],
+ "isIntraWorkspaceLimitEntitled": [
+ 8
+ ],
+ "hasAllowancePeriod": [
+ 8
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "UsageQuotaWithConsumption": {
+ "id": [
+ 3
+ ],
+ "resourceType": [
+ 152
+ ],
+ "operationType": [
+ 153
+ ],
+ "spenderType": [
+ 1
+ ],
+ "spenderId": [
+ 1
+ ],
+ "spenderLabel": [
+ 1
+ ],
+ "periodUnit": [
+ 1
+ ],
+ "meter": [
+ 1
+ ],
+ "limitValue": [
+ 156
+ ],
+ "isEnforced": [
+ 8
+ ],
+ "consumedValue": [
+ 156
+ ],
+ "remainingValue": [
+ 156
+ ],
+ "periodStart": [
+ 4
+ ],
+ "periodEnd": [
+ 4
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "BigInt": {},
+ "UsageQuotaScopeConsumption": {
+ "consumedValue": [
+ 156
+ ],
+ "periodStart": [
+ 4
+ ],
+ "periodEnd": [
+ 4
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "UsageLimit": {
+ "id": [
+ 3
+ ],
+ "resourceType": [
+ 152
+ ],
+ "operationType": [
+ 153
+ ],
+ "spenderType": [
+ 1
+ ],
+ "spenderId": [
+ 1
+ ],
+ "limitKind": [
+ 1
+ ],
+ "periodCount": [
+ 28
+ ],
+ "periodUnit": [
+ 1
+ ],
+ "meter": [
+ 1
+ ],
+ "limitValue": [
+ 156
+ ],
+ "burstValue": [
+ 156
+ ],
+ "createdAt": [
+ 4
+ ],
+ "updatedAt": [
+ 4
+ ],
+ "__typename": [
+ 1
+ ]
+ },
"FileWithSignedUrl": {
"id": [
3
@@ -3100,7 +3242,7 @@ export default {
3
],
"type": [
- 155
+ 163
],
"name": [
1
@@ -3133,7 +3275,7 @@ export default {
4
],
"targetRecordIdentifier": [
- 153
+ 161
],
"__typename": [
1
@@ -3145,7 +3287,7 @@ export default {
1
],
"state": [
- 157
+ 165
],
"attemptsMade": [
28
@@ -3186,7 +3328,7 @@ export default {
},
"MetadataEvent": {
"type": [
- 160
+ 168
],
"metadataName": [
1
@@ -3195,7 +3337,7 @@ export default {
1
],
"properties": [
- 158
+ 166
],
"updatedCollectionHash": [
1
@@ -3207,7 +3349,7 @@ export default {
"MetadataEventAction": {},
"ObjectRecordEvent": {
"action": [
- 162
+ 170
],
"objectNameSingular": [
1
@@ -3222,7 +3364,7 @@ export default {
1
],
"properties": [
- 158
+ 166
],
"__typename": [
1
@@ -3234,7 +3376,7 @@ export default {
1
],
"objectRecordEvent": [
- 161
+ 169
],
"__typename": [
1
@@ -3245,13 +3387,13 @@ export default {
1
],
"objectRecordEventsWithQueryIds": [
- 163
+ 171
],
"metadataEvents": [
- 159
+ 167
],
"queueJobEvents": [
- 156
+ 164
],
"__typename": [
1
@@ -3418,7 +3560,7 @@ export default {
1
],
"dailyUsage": [
- 173
+ 181
],
"__typename": [
1
@@ -3426,116 +3568,18 @@ export default {
},
"UsageAnalytics": {
"usageByUser": [
- 172
+ 180
],
"usageByOperationType": [
- 172
+ 180
],
"usageByApplication": [
- 172
+ 180
],
"usageByModel": [
- 172
+ 180
],
"timeSeries": [
- 173
- ],
- "periodStart": [
- 4
- ],
- "periodEnd": [
- 4
- ],
- "userDailyUsage": [
- 174
- ],
- "__typename": [
- 1
- ]
- },
- "UsageQuotaDefinition": {
- "resourceType": [
- 177
- ],
- "allowedOperationTypes": [
- 178
- ],
- "allowedSpenderTypes": [
- 1
- ],
- "allowedMeters": [
- 1
- ],
- "__typename": [
- 1
- ]
- },
- "UsageResourceType": {},
- "UsageOperationType": {},
- "UsageQuotaDefinitions": {
- "definitions": [
- 176
- ],
- "isIntraWorkspaceLimitEntitled": [
- 8
- ],
- "hasAllowancePeriod": [
- 8
- ],
- "__typename": [
- 1
- ]
- },
- "UsageQuotaWithConsumption": {
- "id": [
- 3
- ],
- "resourceType": [
- 177
- ],
- "operationType": [
- 178
- ],
- "spenderType": [
- 1
- ],
- "spenderId": [
- 1
- ],
- "spenderLabel": [
- 1
- ],
- "periodUnit": [
- 1
- ],
- "meter": [
- 1
- ],
- "limitValue": [
- 181
- ],
- "isEnforced": [
- 8
- ],
- "consumedValue": [
- 181
- ],
- "remainingValue": [
- 181
- ],
- "periodStart": [
- 4
- ],
- "periodEnd": [
- 4
- ],
- "__typename": [
- 1
- ]
- },
- "BigInt": {},
- "UsageQuotaScopeConsumption": {
- "consumedValue": [
181
],
"periodStart": [
@@ -3544,49 +3588,8 @@ export default {
"periodEnd": [
4
],
- "__typename": [
- 1
- ]
- },
- "UsageLimit": {
- "id": [
- 3
- ],
- "resourceType": [
- 177
- ],
- "operationType": [
- 178
- ],
- "spenderType": [
- 1
- ],
- "spenderId": [
- 1
- ],
- "limitKind": [
- 1
- ],
- "periodCount": [
- 28
- ],
- "periodUnit": [
- 1
- ],
- "meter": [
- 1
- ],
- "limitValue": [
- 181
- ],
- "burstValue": [
- 181
- ],
- "createdAt": [
- 4
- ],
- "updatedAt": [
- 4
+ "userDailyUsage": [
+ 182
],
"__typename": [
1
@@ -6530,10 +6533,10 @@ export default {
},
"AiChatUsage": {
"limitValue": [
- 181
+ 156
],
"consumedValue": [
- 181
+ 156
],
"periodEnd": [
4
@@ -7124,10 +7127,10 @@ export default {
},
"Query": {
"navigationMenuItems": [
- 154
+ 162
],
"navigationMenuItem": [
- 154,
+ 162,
{
"id": [
3,
@@ -7172,32 +7175,32 @@ export default {
"enterpriseSubscriptionStatus": [
150
],
- "getUsageAnalytics": [
- 175,
- {
- "input": [
- 403
- ]
- }
- ],
"usageLimits": [
- 183
+ 158
],
"usageQuotasWithConsumption": [
- 180
+ 155
],
"usageQuotaDefinitions": [
- 179
+ 154
],
"usageQuotaScopeConsumption": [
- 182,
+ 157,
{
"input": [
- 404,
+ 403,
"UsageQuotaScopeInput!"
]
}
],
+ "getUsageAnalytics": [
+ 183,
+ {
+ "input": [
+ 404
+ ]
+ }
+ ],
"getViewFilterGroups": [
55,
{
@@ -7322,7 +7325,7 @@ export default {
}
],
"currentUserSessions": [
- 165
+ 173
],
"myConnectedAccounts": [
193
@@ -7346,7 +7349,7 @@ export default {
}
],
"billingPortalSession": [
- 170,
+ 178,
{
"returnUrlPath": [
1
@@ -7357,10 +7360,10 @@ export default {
}
],
"listPlans": [
- 168
+ 176
],
"getResourceCreditUsage": [
- 167
+ 175
],
"getInviteSuggestions": [
185
@@ -7639,7 +7642,7 @@ export default {
}
],
"findInstallApplicationJobStatus": [
- 156,
+ 164,
{
"universalIdentifier": [
1,
@@ -7648,7 +7651,7 @@ export default {
}
],
"findUninstallApplicationJobStatus": [
- 156,
+ 164,
{
"universalIdentifier": [
1,
@@ -7830,7 +7833,7 @@ export default {
}
],
"getJobs": [
- 156,
+ 164,
{
"jobIds": [
1,
@@ -8089,29 +8092,12 @@ export default {
1
]
},
- "UsageAnalyticsInput": {
- "periodStart": [
- 4
- ],
- "periodEnd": [
- 4
- ],
- "userWorkspaceId": [
- 1
- ],
- "operationTypes": [
- 178
- ],
- "__typename": [
- 1
- ]
- },
"UsageQuotaScopeInput": {
"resourceType": [
- 177
+ 152
],
"operationType": [
- 178
+ 153
],
"spenderType": [
1
@@ -8129,6 +8115,23 @@ export default {
1
]
},
+ "UsageAnalyticsInput": {
+ "periodStart": [
+ 4
+ ],
+ "periodEnd": [
+ 4
+ ],
+ "userWorkspaceId": [
+ 1
+ ],
+ "operationTypes": [
+ 153
+ ],
+ "__typename": [
+ 1
+ ]
+ },
"GetApiKeyInput": {
"id": [
3
@@ -8360,7 +8363,7 @@ export default {
}
],
"createManyNavigationMenuItems": [
- 154,
+ 162,
{
"inputs": [
424,
@@ -8369,7 +8372,7 @@ export default {
}
],
"createNavigationMenuItem": [
- 154,
+ 162,
{
"input": [
424,
@@ -8378,7 +8381,7 @@ export default {
}
],
"updateManyNavigationMenuItems": [
- 154,
+ 162,
{
"inputs": [
425,
@@ -8387,7 +8390,7 @@ export default {
}
],
"updateNavigationMenuItem": [
- 154,
+ 162,
{
"input": [
425,
@@ -8396,7 +8399,7 @@ export default {
}
],
"deleteManyNavigationMenuItems": [
- 154,
+ 162,
{
"ids": [
3,
@@ -8405,7 +8408,7 @@ export default {
}
],
"deleteNavigationMenuItem": [
- 154,
+ 162,
{
"id": [
3,
@@ -8414,7 +8417,7 @@ export default {
}
],
"createFileUpload": [
- 152,
+ 160,
{
"filename": [
1,
@@ -8437,7 +8440,7 @@ export default {
}
],
"completeFileUpload": [
- 151,
+ 159,
{
"fileId": [
1,
@@ -8461,7 +8464,7 @@ export default {
}
],
"uploadWorkspaceLogo": [
- 151,
+ 159,
{
"file": [
427,
@@ -8470,7 +8473,7 @@ export default {
}
],
"uploadWorkspaceMemberProfilePicture": [
- 151,
+ 159,
{
"file": [
427,
@@ -8479,7 +8482,7 @@ export default {
}
],
"uploadFilesFieldFileByUniversalIdentifier": [
- 151,
+ 159,
{
"file": [
427,
@@ -8492,7 +8495,7 @@ export default {
}
],
"createUsageLimit": [
- 183,
+ 158,
{
"input": [
428,
@@ -8501,7 +8504,7 @@ export default {
}
],
"updateUsageLimit": [
- 183,
+ 158,
{
"input": [
429,
@@ -8856,7 +8859,7 @@ export default {
}
],
"checkoutSession": [
- 170,
+ 178,
{
"recurringInterval": [
84,
@@ -8876,7 +8879,7 @@ export default {
}
],
"createSubscriptionPaymentIntent": [
- 169,
+ 177,
{
"recurringInterval": [
84,
@@ -8900,22 +8903,22 @@ export default {
}
],
"createBillingPaymentMethodSetupIntent": [
- 169
+ 177
],
"switchSubscriptionInterval": [
- 171
+ 179
],
"switchBillingPlan": [
- 171
+ 179
],
"cancelSwitchBillingPlan": [
- 171
+ 179
],
"cancelSwitchBillingInterval": [
- 171
+ 179
],
"setResourceCreditSubscriptionPrice": [
- 171,
+ 179,
{
"priceId": [
1,
@@ -8924,10 +8927,10 @@ export default {
}
],
"endSubscriptionTrialPeriod": [
- 166
+ 174
],
"cancelSwitchResourceCreditPrice": [
- 171
+ 179
],
"skipSyncEmailOnboardingStep": [
187,
@@ -10406,7 +10409,7 @@ export default {
}
],
"uploadNewWorkspaceLogo": [
- 151,
+ 159,
{
"workspaceId": [
1,
@@ -10939,7 +10942,7 @@ export default {
3
],
"type": [
- 155
+ 163
],
"name": [
1
@@ -11006,10 +11009,10 @@ export default {
"Upload": {},
"CreateUsageLimitInput": {
"resourceType": [
- 177
+ 152
],
"operationType": [
- 178
+ 153
],
"spenderType": [
1
@@ -11030,10 +11033,10 @@ export default {
1
],
"limitValue": [
- 181
+ 156
],
"burstValue": [
- 181
+ 156
],
"__typename": [
1
@@ -13923,7 +13926,7 @@ export default {
},
"Subscription": {
"onEventSubscription": [
- 164,
+ 172,
{
"eventStreamId": [
1,
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index 737399e55ee..54e317761a4 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -6862,6 +6862,7 @@ export enum UsageOperationType {
CALL_RECORDING = 'CALL_RECORDING',
CODE_EXECUTION = 'CODE_EXECUTION',
EMAIL_SEND = 'EMAIL_SEND',
+ STORAGE_FILE = 'STORAGE_FILE',
SUBSCRIPTION = 'SUBSCRIPTION',
WEBHOOK_CALL = 'WEBHOOK_CALL',
WEB_SEARCH = 'WEB_SEARCH',
@@ -6873,6 +6874,7 @@ export type UsageQuotaDefinition = {
allowedMeters: Array<Scalars['String']['output']>;
allowedOperationTypes: Array<UsageOperationType>;
allowedSpenderTypes: Array<Scalars['String']['output']>;
+ limitKind: Scalars['String']['output'];
resourceType: UsageResourceType;
};
diff --git a/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitOperationTypeIcons.ts b/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitOperationTypeIcons.ts
index f0cbc676551..c163a4f0c62 100644
--- a/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitOperationTypeIcons.ts
+++ b/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitOperationTypeIcons.ts
@@ -2,6 +2,7 @@ import {
IconApi,
IconCode,
type IconComponent,
+ IconFiles,
IconMail,
IconMessageCircle,
IconPhone,
@@ -29,5 +30,6 @@ export const USAGE_LIMIT_OPERATION_TYPE_ICONS: Record<
[UsageOperationType.EMAIL_SEND]: IconMail,
[UsageOperationType.API_REQUEST]: IconApi,
[UsageOperationType.WEBHOOK_CALL]: IconWebhook,
+ [UsageOperationType.STORAGE_FILE]: IconFiles,
[UsageOperationType.SUBSCRIPTION]: IconRepeat,
};
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 66dea4ea704..a57413a5248 100644
--- a/packages/twenty-front/src/modules/settings/usage/constants/UsageOperationTypeLabels.ts
+++ b/packages/twenty-front/src/modules/settings/usage/constants/UsageOperationTypeLabels.ts
@@ -19,5 +19,6 @@ export const USAGE_OPERATION_TYPE_LABELS: Record<
[UsageOperationType.EMAIL_SEND]: msg`Email Send`,
[UsageOperationType.API_REQUEST]: msg`API Request`,
[UsageOperationType.WEBHOOK_CALL]: msg`Webhook Call`,
+ [UsageOperationType.STORAGE_FILE]: msg`File Storage`,
[UsageOperationType.SUBSCRIPTION]: msg`Subscription`,
};
diff --git a/packages/twenty-server/src/engine/core-modules/application/application.service.ts b/packages/twenty-server/src/engine/core-modules/application/application.service.ts
index d828fbcd1e4..84b4281deea 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application.service.ts
@@ -734,6 +734,10 @@ export class ApplicationService {
} catch (error) {
if (queryRunner.isTransactionActive) {
await queryRunner.rollbackTransaction();
+ await this.fileStorageService.invalidateStorageStock({
+ workspaceId,
+ applicationId: application.id,
+ });
}
throw error;
diff --git a/packages/twenty-server/src/engine/core-modules/auth/services/sign-in-up.service.ts b/packages/twenty-server/src/engine/core-modules/auth/services/sign-in-up.service.ts
index 47ac1e0f082..16fd51c3488 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/services/sign-in-up.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/services/sign-in-up.service.ts
@@ -25,6 +25,7 @@ import {
AppTokenType,
} from 'src/engine/core-modules/app-token/app-token.entity';
import { ApplicationService } from 'src/engine/core-modules/application/application.service';
+import { FileStorageService } from 'src/engine/core-modules/file-storage/services/file-storage.service';
import { BillingCreditGrantType } from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';
import { BillingCreditService } from 'src/engine/core-modules/billing/services/billing-credit.service';
import { BillingService } from 'src/engine/core-modules/billing/services/billing.service';
@@ -96,6 +97,7 @@ export class SignInUpService {
private readonly workspaceCacheService: WorkspaceCacheService,
private readonly applicationService: ApplicationService,
private readonly fileCorePictureService: FileCorePictureService,
+ private readonly fileStorageService: FileStorageService,
private readonly exceptionHandlerService: ExceptionHandlerService,
private readonly enterprisePlanService: EnterprisePlanService,
private readonly eventLogEmitterService: EventLogEmitterService,
@@ -872,6 +874,11 @@ export class SignInUpService {
return { user, workspace };
} catch (error) {
+ await this.fileStorageService.invalidateStorageStock({
+ workspaceId,
+ applicationId: workspaceCustomApplicationId,
+ });
+
const isSubdomainConflict =
error instanceof QueryFailedError &&
(error as QueryFailedErrorWithCode).code ===
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 67d1f490740..c98ab27174c 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
@@ -31,6 +31,7 @@ const USAGE_UNIT_BY_OPERATION_TYPE: Record<
[UsageOperationType.EMAIL_SEND]: UsageUnit.INVOCATION,
[UsageOperationType.API_REQUEST]: UsageUnit.REQUEST,
[UsageOperationType.WEBHOOK_CALL]: UsageUnit.REQUEST,
+ [UsageOperationType.STORAGE_FILE]: UsageUnit.BYTE,
// Platform-raised only; ApplicationRecurringChargeService sets its own unit.
[UsageOperationType.SUBSCRIPTION]: UsageUnit.CREDIT,
};
diff --git a/packages/twenty-server/src/engine/core-modules/file-storage/file-storage.module.ts b/packages/twenty-server/src/engine/core-modules/file-storage/file-storage.module.ts
index 1445524ef66..6754ebfd872 100644
--- a/packages/twenty-server/src/engine/core-modules/file-storage/file-storage.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/file-storage/file-storage.module.ts
@@ -8,6 +8,7 @@ import { FileStorageService } from 'src/engine/core-modules/file-storage/service
import { ServerFileStorageService } from 'src/engine/core-modules/file-storage/services/server-file-storage.service';
import { FileEntity } from 'src/engine/core-modules/file/entities/file.entity';
import { TwentyConfigModule } from 'src/engine/core-modules/twenty-config/twenty-config.module';
+import { UsageLimitModule } from 'src/engine/core-modules/usage-limit/usage-limit.module';
import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/provide-workspace-scoped-repository';
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
@Global()
@@ -19,6 +20,7 @@ export class FileStorageModule {
TwentyConfigModule,
TypeOrmModule.forFeature([FileEntity]),
WorkspaceCacheModule,
+ UsageLimitModule,
],
providers: [
FileStorageDriverFactory,
diff --git a/packages/twenty-server/src/engine/core-modules/file-storage/services/__tests__/file-storage.service.spec.ts b/packages/twenty-server/src/engine/core-modules/file-storage/services/__tests__/file-storage.service.spec.ts
index ad28490b1cb..335db3ccb13 100644
--- a/packages/twenty-server/src/engine/core-modules/file-storage/services/__tests__/file-storage.service.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/file-storage/services/__tests__/file-storage.service.spec.ts
@@ -5,6 +5,7 @@ import { type FileStorageDriverFactory } from 'src/engine/core-modules/file-stor
import { FileStorageService } from 'src/engine/core-modules/file-storage/services/file-storage.service';
import { type FileEntity } from 'src/engine/core-modules/file/entities/file.entity';
import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+import { type UsageLimitStockService } from 'src/engine/core-modules/usage-limit/services/usage-limit-stock.service';
import { type WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
const WORKSPACE_ID = '20202020-1c25-4d02-bf25-6aeccf7ea419';
@@ -36,6 +37,10 @@ describe('FileStorageService', () => {
} as unknown as FileStorageDriverFactory,
fileRepository as unknown as WorkspaceScopedRepository<FileEntity>,
{} as WorkspaceCacheService,
+ {
+ assertStockAvailable: jest.fn().mockResolvedValue(undefined),
+ acquireStock: jest.fn().mockResolvedValue(undefined),
+ } as unknown as UsageLimitStockService,
);
return { service, fileRepository, transactionRepository };
diff --git a/packages/twenty-server/src/engine/core-modules/file-storage/services/file-storage.service.ts b/packages/twenty-server/src/engine/core-modules/file-storage/services/file-storage.service.ts
index f1cbbb57198..58551c83630 100644
--- a/packages/twenty-server/src/engine/core-modules/file-storage/services/file-storage.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/file-storage/services/file-storage.service.ts
@@ -1,22 +1,31 @@
import { Injectable } from '@nestjs/common';
+import { isString } from '@sniptt/guards';
import { basename, dirname, join } from 'path';
import { type Readable } from 'stream';
+import { v4 } from 'uuid';
import { FileFolder } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
-import { Like, type QueryRunner } from 'typeorm';
+import {
+ type FindOptionsWhere,
+ Like,
+ type QueryRunner,
+ type UpdateResult,
+} from 'typeorm';
import { ApplicationEntity } from 'src/engine/core-modules/application/application.entity';
import { findActiveFlatApplicationById } from 'src/engine/core-modules/application/utils/find-active-flat-application-by-id.util';
import { findActiveFlatApplicationByUniversalIdentifier } from 'src/engine/core-modules/application/utils/find-active-flat-application-by-universal-identifier.util';
-import { type FileStorageMetadata } from 'src/engine/core-modules/file-storage/types/file-storage-metadata.type';
import { FileStorageDriverFactory } from 'src/engine/core-modules/file-storage/file-storage-driver.factory';
-import { type ByteRange } from 'src/engine/core-modules/file-storage/types/byte-range.type';
import {
FileStorageException,
FileStorageExceptionCode,
} from 'src/engine/core-modules/file-storage/interfaces/file-storage-exception';
+import { type ByteRange } from 'src/engine/core-modules/file-storage/types/byte-range.type';
+import { type FileStorageMetadata } from 'src/engine/core-modules/file-storage/types/file-storage-metadata.type';
+import { buildReleasedStockByApplication } from 'src/engine/core-modules/file-storage/utils/build-released-stock-by-application.util';
+import { buildStockDelta } from 'src/engine/core-modules/file-storage/utils/build-stock-delta.util';
import { prepareFileForStorageOrThrow } from 'src/engine/core-modules/file-storage/utils/prepare-file-for-storage-or-throw.util';
import { validateFilePath } from 'src/engine/core-modules/file-storage/utils/validate-file-path.util';
import { validateFolderPath } from 'src/engine/core-modules/file-storage/utils/validate-folder-path.util';
@@ -25,6 +34,13 @@ import { FileEntity } from 'src/engine/core-modules/file/entities/file.entity';
import { FileSettings } from 'src/engine/core-modules/file/types/file-settings.types';
import { FILE_STATUS } from 'src/engine/core-modules/file/types/file-status.types';
import { removeFileFolderFromFileEntityPath } from 'src/engine/core-modules/file/utils/remove-file-folder-from-file-entity-path.utils';
+import { STOCK_METERS } from 'src/engine/core-modules/usage-limit/constants/usage-meters.constant';
+import { UsageLimitStockService } from 'src/engine/core-modules/usage-limit/services/usage-limit-stock.service';
+import { type StockCost } from 'src/engine/core-modules/usage-limit/types/stock-cost.type';
+import { type StockMeter } from 'src/engine/core-modules/usage-limit/types/stock-meter.type';
+import { type StockScope } from 'src/engine/core-modules/usage-limit/types/stock-scope.type';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
@@ -42,27 +58,162 @@ export class FileStorageService {
@InjectWorkspaceScopedRepository(FileEntity)
private readonly fileRepository: WorkspaceScopedRepository<FileEntity>,
private readonly workspaceCacheService: WorkspaceCacheService,
+ private readonly usageLimitStockService: UsageLimitStockService,
) {}
- private async resolveFileIdKeepingExistingRow({
+ async releaseStorageStock({
+ workspaceId,
+ applicationId,
+ bytes,
+ quantity,
+ }: {
+ workspaceId: string;
+ applicationId: string;
+ bytes: number;
+ quantity: number;
+ }): Promise<void> {
+ await this.usageLimitStockService.releaseStock({
+ workspaceId,
+ resourceType: UsageResourceType.STORAGE,
+ operationType: UsageOperationType.STORAGE_FILE,
+ spenders: { applicationId },
+ cost: { bytes, quantity },
+ });
+ }
+
+ async invalidateStorageStock({
+ workspaceId,
+ applicationId,
+ }: {
+ workspaceId: string;
+ applicationId?: string;
+ }): Promise<void> {
+ await this.usageLimitStockService.invalidateStock({
+ workspaceId,
+ resourceType: UsageResourceType.STORAGE,
+ operationType: UsageOperationType.STORAGE_FILE,
+ spenders: { applicationId },
+ });
+ }
+
+ private async assertStorageStockAvailable({
+ workspaceId,
+ applicationId,
+ delta,
+ }: {
+ workspaceId: string;
+ applicationId: string;
+ delta: StockCost;
+ }): Promise<void> {
+ if (STOCK_METERS.every((meter) => (delta[meter] ?? 0) <= 0)) {
+ return;
+ }
+
+ await this.usageLimitStockService.assertStockAvailable({
+ workspaceId,
+ resourceType: UsageResourceType.STORAGE,
+ operationType: UsageOperationType.STORAGE_FILE,
+ spenders: { applicationId },
+ cost: delta,
+ computeUsedStock: (scope) =>
+ this.computeStorageUsedStock({ workspaceId, ...scope }),
+ });
+ }
+
+ private async computeStorageUsedStock({
+ workspaceId,
+ spenderType,
+ spenderId,
+ }: StockScope & { workspaceId: string }): Promise<
+ Record<StockMeter, number>
+ > {
+ const query = this.fileRepository
+ .createQueryBuilder('file')
+ .select('COUNT(*)::bigint', 'quantity')
+ .addSelect('COALESCE(SUM(file.size), 0)::bigint', 'bytes')
+ .where('file.workspaceId = :workspaceId', { workspaceId })
+ .withDeleted();
+
+ if (spenderType === 'application') {
+ query.andWhere('file.applicationId = :applicationId', {
+ applicationId: spenderId,
+ });
+ }
+
+ const used = await query.getRawOne<{ quantity: string; bytes: string }>();
+
+ return {
+ quantity: Number(used?.quantity ?? 0),
+ bytes: Number(used?.bytes ?? 0),
+ };
+ }
+
+ private async deleteFileRows({
+ workspaceId,
+ where,
+ fileRepository,
+ }: {
+ workspaceId: string;
+ where: FindOptionsWhere<FileEntity>;
+ fileRepository: WorkspaceScopedRepository<FileEntity>;
+ }): Promise<void> {
+ const deletedRows = await fileRepository.deleteAndReturn(
+ workspaceId,
+ where,
+ );
+
+ const releasedByApplication = buildReleasedStockByApplication(deletedRows);
+
+ await Promise.all(
+ [...releasedByApplication.entries()].map(([applicationId, released]) =>
+ this.releaseStorageStock({ workspaceId, applicationId, ...released }),
+ ),
+ );
+ }
+
+ private findFileByPath({
fileRepository,
workspaceId,
filePath,
applicationId,
- fileId,
}: {
fileRepository: WorkspaceScopedRepository<FileEntity>;
workspaceId: string;
filePath: string;
applicationId: string;
- fileId: string | undefined;
- }): Promise<string | undefined> {
- const existingFile = await fileRepository.findOne(workspaceId, {
+ }): Promise<FileEntity | null> {
+ return fileRepository.findOne(workspaceId, {
where: { path: filePath, applicationId },
withDeleted: true,
});
+ }
- return existingFile?.id ?? fileId;
+ private async applyStorageStockDelta({
+ workspaceId,
+ applicationId,
+ delta,
+ }: {
+ workspaceId: string;
+ applicationId: string;
+ delta: StockCost;
+ }): Promise<void> {
+ const scope = {
+ workspaceId,
+ resourceType: UsageResourceType.STORAGE,
+ operationType: UsageOperationType.STORAGE_FILE,
+ spenders: { applicationId },
+ };
+
+ if ((delta.bytes ?? 0) < 0) {
+ return this.releaseStorageStock({
+ workspaceId,
+ applicationId,
+ bytes: -(delta.bytes ?? 0),
+ quantity: 0,
+ });
+ }
+
+ return this.usageLimitStockService.acquireStock({ ...scope, cost: delta });
}
private async resolveApplicationIdOrThrow({
@@ -261,33 +412,51 @@ export class FileStorageService {
resourcePath,
});
+ const size = isString(persistedSourceFile)
+ ? Buffer.byteLength(persistedSourceFile)
+ : persistedSourceFile.length;
+
+ const existingFile = await this.findFileByPath({
+ fileRepository: fileRepository,
+ workspaceId,
+ filePath,
+ applicationId: resolvedApplicationId,
+ });
+
+ const delta = buildStockDelta({ existingFile, size });
+
+ await this.assertStorageStockAvailable({
+ workspaceId,
+ applicationId: resolvedApplicationId,
+ delta,
+ });
+
await driver.writeFile({
filePath: onStorageFilePath,
mimeType,
sourceFile: persistedSourceFile,
});
- return fileRepository.upsertAndReturnOne(
+ const file = await fileRepository.upsertAndReturnOne(
workspaceId,
{
path: filePath,
applicationId: resolvedApplicationId,
- id: await this.resolveFileIdKeepingExistingRow({
- fileRepository,
- workspaceId,
- filePath,
- applicationId: resolvedApplicationId,
- fileId,
- }),
+ id: existingFile?.id ?? fileId,
mimeType,
- size:
- typeof persistedSourceFile === 'string'
- ? Buffer.byteLength(persistedSourceFile)
- : persistedSourceFile.length,
+ size,
settings,
},
['path', 'workspaceId', 'applicationId'],
);
+
+ await this.applyStorageStockDelta({
+ workspaceId,
+ applicationId: resolvedApplicationId,
+ delta,
+ });
+
+ return file;
}
// Creates the file record ahead of a direct client upload. The bytes are
@@ -324,18 +493,27 @@ export class FileStorageService {
resourcePath,
});
- return this.fileRepository.upsertAndReturnOne(
+ const existingFile = await this.findFileByPath({
+ fileRepository: this.fileRepository,
+ workspaceId,
+ filePath,
+ applicationId: resolvedApplicationId,
+ });
+
+ const delta = buildStockDelta({ existingFile, size });
+
+ await this.assertStorageStockAvailable({
+ workspaceId,
+ applicationId: resolvedApplicationId,
+ delta,
+ });
+
+ const file = await this.fileRepository.upsertAndReturnOne(
workspaceId,
{
path: filePath,
applicationId: resolvedApplicationId,
- id: await this.resolveFileIdKeepingExistingRow({
- fileRepository: this.fileRepository,
- workspaceId,
- filePath,
- applicationId: resolvedApplicationId,
- fileId,
- }),
+ id: existingFile?.id ?? fileId,
mimeType,
size,
settings,
@@ -343,6 +521,48 @@ export class FileStorageService {
},
['path', 'workspaceId', 'applicationId'],
);
+
+ await this.applyStorageStockDelta({
+ workspaceId,
+ applicationId: resolvedApplicationId,
+ delta,
+ });
+
+ return file;
+ }
+
+ async markFileUploaded({
+ workspaceId,
+ applicationId,
+ fileId,
+ chargedSize,
+ size,
+ mimeType,
+ }: {
+ workspaceId: string;
+ applicationId: string;
+ fileId: string;
+ chargedSize: number;
+ size: number;
+ mimeType: string;
+ }): Promise<UpdateResult> {
+ const updateResult = await this.fileRepository.update(
+ workspaceId,
+ { id: fileId },
+ { status: FILE_STATUS.UPLOADED, mimeType, size },
+ );
+
+ if (updateResult.affected === 0 || size === chargedSize) {
+ return updateResult;
+ }
+
+ await this.applyStorageStockDelta({
+ workspaceId,
+ applicationId,
+ delta: { bytes: size - chargedSize, quantity: 0 },
+ });
+
+ return updateResult;
}
async writeFileStream(
@@ -466,7 +686,11 @@ export class FileStorageService {
? this.fileRepository.withManager(queryRunner.manager)
: this.fileRepository;
- await fileRepository.delete(workspaceId, { applicationId });
+ await this.deleteFileRows({
+ workspaceId,
+ where: { applicationId },
+ fileRepository,
+ });
}
async deleteApplicationFilesFromStorage({
@@ -502,9 +726,10 @@ export class FileStorageService {
workspaceId: params.workspaceId,
}));
- await this.fileRepository.delete(params.workspaceId, {
- path: filePath,
- applicationId,
+ await this.deleteFileRows({
+ workspaceId: params.workspaceId,
+ where: { path: filePath, applicationId },
+ fileRepository: this.fileRepository,
});
}
@@ -551,9 +776,10 @@ export class FileStorageService {
workspaceId,
});
- await this.fileRepository.delete(workspaceId, {
- path: Like(`${validatedFolderPath}%`),
- applicationId,
+ await this.deleteFileRows({
+ workspaceId,
+ where: { path: Like(`${validatedFolderPath}%`), applicationId },
+ fileRepository: this.fileRepository,
});
}
@@ -609,6 +835,92 @@ export class FileStorageService {
return driver.copy(params);
}
+ async copyFile({
+ from,
+ to,
+ applicationId,
+ fileId,
+ size,
+ mimeType,
+ settings,
+ }: {
+ from: ResourceIdentifier;
+ to: ResourceIdentifier;
+ applicationId: string;
+ fileId: string;
+ size: number;
+ mimeType: string;
+ settings: FileSettings | null;
+ }): Promise<FileEntity> {
+ const { filePath } = this.validateAndBuildFileStoragePathOrThrow(to);
+ const delta = { bytes: size, quantity: 1 };
+
+ await this.assertStorageStockAvailable({
+ workspaceId: to.workspaceId,
+ applicationId,
+ delta,
+ });
+
+ await this.copy({ from, to });
+
+ const file = await this.fileRepository.insertAndReturnOne(to.workspaceId, {
+ id: fileId,
+ path: filePath,
+ applicationId,
+ mimeType,
+ size,
+ status: FILE_STATUS.UPLOADED,
+ settings,
+ });
+
+ await this.applyStorageStockDelta({
+ workspaceId: to.workspaceId,
+ applicationId,
+ delta,
+ });
+
+ return file;
+ }
+
+ async copyFileByPath({
+ from,
+ to,
+ }: {
+ from: ResourceIdentifier;
+ to: ResourceIdentifier;
+ }): Promise<FileEntity> {
+ const { filePath } = this.validateAndBuildFileStoragePathOrThrow(from);
+
+ const [sourceApplicationId, destinationApplicationId] = await Promise.all([
+ this.resolveApplicationIdOrThrow(from),
+ this.resolveApplicationIdOrThrow(to),
+ ]);
+
+ const sourceFile = await this.findFileByPath({
+ fileRepository: this.fileRepository,
+ workspaceId: from.workspaceId,
+ filePath,
+ applicationId: sourceApplicationId,
+ });
+
+ if (!isDefined(sourceFile)) {
+ throw new FileStorageException(
+ `File not found at path "${filePath}"`,
+ FileStorageExceptionCode.FILE_NOT_FOUND,
+ );
+ }
+
+ return this.copyFile({
+ from,
+ to,
+ applicationId: destinationApplicationId,
+ fileId: v4(),
+ mimeType: sourceFile.mimeType,
+ size: sourceFile.size,
+ settings: sourceFile.settings,
+ });
+ }
+
async copy({
from,
to,
diff --git a/packages/twenty-server/src/engine/core-modules/file-storage/utils/__tests__/build-released-stock-by-application.util.spec.ts b/packages/twenty-server/src/engine/core-modules/file-storage/utils/__tests__/build-released-stock-by-application.util.spec.ts
new file mode 100644
index 00000000000..964ba36e68a
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/file-storage/utils/__tests__/build-released-stock-by-application.util.spec.ts
@@ -0,0 +1,25 @@
+import { buildReleasedStockByApplication } from 'src/engine/core-modules/file-storage/utils/build-released-stock-by-application.util';
+
+const APPLICATION_ID = 'b30a4560-fedb-4ccd-904a-3788762c7d33';
+const ANOTHER_APPLICATION_ID = 'c41b5671-0fec-4dde-a15b-4899873d8e44';
+
+describe('buildReleasedStockByApplication', () => {
+ it('sums the bytes and counts the rows of each application', () => {
+ expect(
+ buildReleasedStockByApplication([
+ { size: 1000, applicationId: APPLICATION_ID },
+ { size: 2000, applicationId: APPLICATION_ID },
+ { size: 40, applicationId: ANOTHER_APPLICATION_ID },
+ ]),
+ ).toEqual(
+ new Map([
+ [APPLICATION_ID, { bytes: 3000, quantity: 2 }],
+ [ANOTHER_APPLICATION_ID, { bytes: 40, quantity: 1 }],
+ ]),
+ );
+ });
+
+ it('gives back nothing when the delete removed no row', () => {
+ expect(buildReleasedStockByApplication([])).toEqual(new Map());
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/file-storage/utils/__tests__/build-stock-delta.util.spec.ts b/packages/twenty-server/src/engine/core-modules/file-storage/utils/__tests__/build-stock-delta.util.spec.ts
new file mode 100644
index 00000000000..0525872ea9c
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/file-storage/utils/__tests__/build-stock-delta.util.spec.ts
@@ -0,0 +1,37 @@
+import { buildStockDelta } from 'src/engine/core-modules/file-storage/utils/build-stock-delta.util';
+
+const existingFile = (size: number) => ({ size });
+
+describe('buildStockDelta', () => {
+ it('charges the bytes and the row of a file at a free path', () => {
+ expect(buildStockDelta({ existingFile: null, size: 12 })).toEqual({
+ bytes: 12,
+ quantity: 1,
+ });
+ });
+
+ it('charges the row of an empty file, which still occupies one', () => {
+ expect(buildStockDelta({ existingFile: null, size: 0 })).toEqual({
+ bytes: 0,
+ quantity: 1,
+ });
+ });
+
+ it('moves nothing when a replacement is the same size', () => {
+ expect(
+ buildStockDelta({ existingFile: existingFile(500), size: 500 }),
+ ).toEqual({ bytes: 0, quantity: 0 });
+ });
+
+ it('charges a growing replacement only for what it adds', () => {
+ expect(buildStockDelta({ existingFile: existingFile(1), size: 2 })).toEqual(
+ { bytes: 1, quantity: 0 },
+ );
+ });
+
+ it('gives back what a shrinking replacement frees', () => {
+ expect(
+ buildStockDelta({ existingFile: existingFile(500), size: 2 }),
+ ).toEqual({ bytes: -498, quantity: 0 });
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/file-storage/utils/build-released-stock-by-application.util.ts b/packages/twenty-server/src/engine/core-modules/file-storage/utils/build-released-stock-by-application.util.ts
new file mode 100644
index 00000000000..f39982cd0d3
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/file-storage/utils/build-released-stock-by-application.util.ts
@@ -0,0 +1,19 @@
+import { type FileEntity } from 'src/engine/core-modules/file/entities/file.entity';
+import { type StockCost } from 'src/engine/core-modules/usage-limit/types/stock-cost.type';
+
+export const buildReleasedStockByApplication = (
+ deletedRows: Pick<FileEntity, 'applicationId' | 'size'>[],
+): Map<string, Required<Pick<StockCost, 'bytes' | 'quantity'>>> =>
+ deletedRows.reduce((byApplication, row) => {
+ const released = byApplication.get(row.applicationId) ?? {
+ bytes: 0,
+ quantity: 0,
+ };
+
+ byApplication.set(row.applicationId, {
+ bytes: released.bytes + row.size,
+ quantity: released.quantity + 1,
+ });
+
+ return byApplication;
+ }, new Map<string, Required<Pick<StockCost, 'bytes' | 'quantity'>>>());
diff --git a/packages/twenty-server/src/engine/core-modules/file-storage/utils/build-stock-delta.util.ts b/packages/twenty-server/src/engine/core-modules/file-storage/utils/build-stock-delta.util.ts
new file mode 100644
index 00000000000..e68caa31d90
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/file-storage/utils/build-stock-delta.util.ts
@@ -0,0 +1,15 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type FileEntity } from 'src/engine/core-modules/file/entities/file.entity';
+import { type StockCost } from 'src/engine/core-modules/usage-limit/types/stock-cost.type';
+
+export const buildStockDelta = ({
+ existingFile,
+ size,
+}: {
+ existingFile: Pick<FileEntity, 'size'> | null;
+ size: number;
+}): StockCost => ({
+ bytes: size - (existingFile?.size ?? 0),
+ quantity: isDefined(existingFile) ? 0 : 1,
+});
diff --git a/packages/twenty-server/src/engine/core-modules/file/entities/file.entity.ts b/packages/twenty-server/src/engine/core-modules/file/entities/file.entity.ts
index d8fddcac199..9b1eabc793c 100644
--- a/packages/twenty-server/src/engine/core-modules/file/entities/file.entity.ts
+++ b/packages/twenty-server/src/engine/core-modules/file/entities/file.entity.ts
@@ -24,6 +24,7 @@ import {
} from 'src/engine/core-modules/file/types/file-status.types';
import { WasIntroducedInUpgrade } from 'src/engine/core-modules/upgrade/decorators/was-introduced-in-upgrade.decorator';
import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
+import { nullableBigintColumnTransformer } from 'src/engine/twenty-orm/utils/nullable-bigint-column-transformer.util';
@Entity('file')
@Check(
@@ -89,7 +90,11 @@ export class FileEntity {
@Column({ nullable: false })
path: string;
- @Column({ nullable: false, type: 'bigint' })
+ @Column({
+ nullable: false,
+ type: 'bigint',
+ transformer: nullableBigintColumnTransformer,
+ })
size: number;
@CreateDateColumn({ type: 'timestamptz' })
diff --git a/packages/twenty-server/src/engine/core-modules/file/file-core-picture/resolvers/file-core-picture.resolver.ts b/packages/twenty-server/src/engine/core-modules/file/file-core-picture/resolvers/file-core-picture.resolver.ts
index 8c283ba8e7d..649fc51d7ab 100644
--- a/packages/twenty-server/src/engine/core-modules/file/file-core-picture/resolvers/file-core-picture.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/file/file-core-picture/resolvers/file-core-picture.resolver.ts
@@ -21,10 +21,12 @@ import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
import { PermissionsGraphqlApiExceptionFilter } from 'src/engine/metadata-modules/permissions/utils/permissions-graphql-api-exception.filter';
import { streamToBuffer } from 'src/utils/stream-to-buffer';
import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filters/auth-graphql-api-exception.filter';
+import { UsageLimitGraphqlApiExceptionFilter } from 'src/engine/core-modules/usage-limit/filters/usage-limit-graphql-api-exception.filter';
@UseGuards(WorkspaceAuthGuard)
@UsePipes(ResolverValidationPipe)
@UseFilters(
+ UsageLimitGraphqlApiExceptionFilter,
PermissionsGraphqlApiExceptionFilter,
PreventNestToAutoLogGraphqlErrorsFilter,
AuthGraphqlApiExceptionFilter,
diff --git a/packages/twenty-server/src/engine/core-modules/file/file-upload/resolvers/file-upload.resolver.ts b/packages/twenty-server/src/engine/core-modules/file/file-upload/resolvers/file-upload.resolver.ts
index 933f1ed8475..0a9143eb1d0 100644
--- a/packages/twenty-server/src/engine/core-modules/file/file-upload/resolvers/file-upload.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/file/file-upload/resolvers/file-upload.resolver.ts
@@ -15,10 +15,12 @@ import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorat
import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';
import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filters/auth-graphql-api-exception.filter';
+import { UsageLimitGraphqlApiExceptionFilter } from 'src/engine/core-modules/usage-limit/filters/usage-limit-graphql-api-exception.filter';
@UseGuards(WorkspaceAuthGuard)
@UsePipes(ResolverValidationPipe)
@UseFilters(
+ UsageLimitGraphqlApiExceptionFilter,
PreventNestToAutoLogGraphqlErrorsFilter,
AuthGraphqlApiExceptionFilter,
)
diff --git a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/__tests__/file-upload-completion.service.spec.ts b/packages/twenty-server/src/engine/core-modules/file/file-upload/services/__tests__/file-upload-completion.service.spec.ts
index 1c22575a85d..63e9012a23d 100644
--- a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/__tests__/file-upload-completion.service.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/file/file-upload/services/__tests__/file-upload-completion.service.spec.ts
@@ -9,7 +9,6 @@ import { FileUploadExceptionCode } from 'src/engine/core-modules/file/file-uploa
import { FileUploadCompletionService } from 'src/engine/core-modules/file/file-upload/services/file-upload-completion.service';
import { buildPendingUploadResourcePath } from 'src/engine/core-modules/file/file-upload/utils/build-pending-upload-resource-path.util';
import { FILE_STATUS } from 'src/engine/core-modules/file/types/file-status.types';
-import { type WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
describe('FileUploadCompletionService.completeUploadedFile', () => {
const workspaceId = '20202020-0000-4000-8000-000000000001';
@@ -23,7 +22,6 @@ describe('FileUploadCompletionService.completeUploadedFile', () => {
]);
let fileStorageService: jest.Mocked<FileStorageService>;
- let fileRepository: jest.Mocked<WorkspaceScopedRepository<FileEntity>>;
const buildStorageLocation = (ext: string) => ({
fileFolder: FileFolder.FilesField,
@@ -43,7 +41,7 @@ describe('FileUploadCompletionService.completeUploadedFile', () => {
}) as FileEntity;
const buildService = () =>
- new FileUploadCompletionService(fileStorageService, fileRepository);
+ new FileUploadCompletionService(fileStorageService);
beforeEach(() => {
fileStorageService = {
@@ -55,11 +53,8 @@ describe('FileUploadCompletionService.completeUploadedFile', () => {
writeFileStream: jest.fn().mockResolvedValue(undefined),
move: jest.fn().mockResolvedValue(undefined),
deleteFileObject: jest.fn().mockResolvedValue(undefined),
+ markFileUploaded: jest.fn().mockResolvedValue({ affected: 1 }),
} as unknown as jest.Mocked<FileStorageService>;
-
- fileRepository = {
- update: jest.fn().mockResolvedValue({ affected: 1 }),
- } as unknown as jest.Mocked<WorkspaceScopedRepository<FileEntity>>;
});
afterEach(() => {
@@ -85,7 +80,7 @@ describe('FileUploadCompletionService.completeUploadedFile', () => {
});
expect(fileStorageService.readFile).not.toHaveBeenCalled();
- expect(fileRepository.update).not.toHaveBeenCalled();
+ expect(fileStorageService.markFileUploaded).not.toHaveBeenCalled();
});
it('should report an oversized read as FILE_TOO_LARGE when storage understated the size', async () => {
@@ -109,7 +104,7 @@ describe('FileUploadCompletionService.completeUploadedFile', () => {
code: FileUploadExceptionCode.FILE_TOO_LARGE,
});
- expect(fileRepository.update).not.toHaveBeenCalled();
+ expect(fileStorageService.markFileUploaded).not.toHaveBeenCalled();
});
it('should refuse to promote a sanitized SVG whose new identity is unreadable', async () => {
@@ -187,11 +182,11 @@ describe('FileUploadCompletionService.completeUploadedFile', () => {
expect(completedFile.mimeType).toBe('image/svg+xml');
expect(completedFile.size).toBeLessThan(size);
expect(fileStorageService.writeFileStream).toHaveBeenCalledTimes(1);
- expect(fileRepository.update).toHaveBeenCalledWith(
- workspaceId,
- { id: fileId },
+ expect(fileStorageService.markFileUploaded).toHaveBeenCalledWith(
expect.objectContaining({
- status: FILE_STATUS.UPLOADED,
+ workspaceId,
+ fileId,
+ chargedSize: size,
mimeType: 'image/svg+xml',
size: completedFile.size,
}),
@@ -273,7 +268,7 @@ describe('FileUploadCompletionService.completeUploadedFile', () => {
});
expect(fileStorageService.move).not.toHaveBeenCalled();
- expect(fileRepository.update).not.toHaveBeenCalled();
+ expect(fileStorageService.markFileUploaded).not.toHaveBeenCalled();
});
it('should fail without touching storage when the row was reaped mid-completion', async () => {
@@ -284,7 +279,7 @@ describe('FileUploadCompletionService.completeUploadedFile', () => {
checksum: '"etag-a"',
});
fileStorageService.readFilePrefix.mockResolvedValue(pngContent);
- fileRepository.update.mockResolvedValue({
+ fileStorageService.markFileUploaded.mockResolvedValue({
affected: 0,
raw: [],
generatedMaps: [],
diff --git a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload-completion.service.ts b/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload-completion.service.ts
index 78daf9b20ea..c3167c1464a 100644
--- a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload-completion.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload-completion.service.ts
@@ -5,8 +5,8 @@ import { Readable } from 'stream';
import { FileFolder } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
-import { type FileStorageMetadata } from 'src/engine/core-modules/file-storage/types/file-storage-metadata.type';
import { FileStorageService } from 'src/engine/core-modules/file-storage/services/file-storage.service';
+import { type FileStorageMetadata } from 'src/engine/core-modules/file-storage/types/file-storage-metadata.type';
import { FileDTO } from 'src/engine/core-modules/file/dtos/file.dto';
import { FileEntity } from 'src/engine/core-modules/file/entities/file.entity';
import { FILE_CONTENT_SNIFF_BYTE_COUNT } from 'src/engine/core-modules/file/file-upload/constants/file-content-sniff.constant';
@@ -23,12 +23,9 @@ import {
ANY_MIME_TYPE,
fileFolderConfigs,
} from 'src/engine/core-modules/file/interfaces/file-folder.interface';
-import { FILE_STATUS } from 'src/engine/core-modules/file/types/file-status.types';
import { extractFileInfoOrThrow } from 'src/engine/core-modules/file/utils/extract-file-info-or-throw.utils';
import { removeFileFolderFromFileEntityPath } from 'src/engine/core-modules/file/utils/remove-file-folder-from-file-entity-path.utils';
import { sanitizeFile } from 'src/engine/core-modules/file/utils/sanitize-file.utils';
-import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
-import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
import { StreamSizeExceededError } from 'src/utils/stream-size-exceeded-error';
import { streamToBuffer } from 'src/utils/stream-to-buffer';
@@ -51,11 +48,7 @@ type CompletedUploadedFile = FileDTO & Pick<FileEntity, 'mimeType'>;
export class FileUploadCompletionService {
private readonly logger = new Logger(FileUploadCompletionService.name);
- constructor(
- private readonly fileStorageService: FileStorageService,
- @InjectWorkspaceScopedRepository(FileEntity)
- private readonly fileRepository: WorkspaceScopedRepository<FileEntity>,
- ) {}
+ constructor(private readonly fileStorageService: FileStorageService) {}
async completeUploadsBatch(
requests: BatchCompleteUploadRequest[],
@@ -146,11 +139,14 @@ export class FileUploadCompletionService {
ifMatchChecksum: checksum,
});
- const { affected } = await this.fileRepository.update(
+ const { affected } = await this.fileStorageService.markFileUploaded({
workspaceId,
- { id: file.id },
- { status: FILE_STATUS.UPLOADED, mimeType, size },
- );
+ applicationId: file.applicationId,
+ fileId: file.id,
+ chargedSize: declaredSize,
+ size,
+ mimeType,
+ });
// The cleanup cron claims a stale PENDING row by deleting it, then deletes
// its objects, so losing the row here means it won. The promoting copy may
diff --git a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/pending-file-cleanup.service.ts b/packages/twenty-server/src/engine/core-modules/file/file-upload/services/pending-file-cleanup.service.ts
index c24747755ae..bf341424ae7 100644
--- a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/pending-file-cleanup.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/file/file-upload/services/pending-file-cleanup.service.ts
@@ -84,6 +84,15 @@ export class PendingFileCleanupService {
continue;
}
+ if (isDefined(file.workspaceId)) {
+ await this.fileStorageService.releaseStorageStock({
+ workspaceId: file.workspaceId,
+ applicationId: file.applicationId,
+ bytes: file.size,
+ quantity: 1,
+ });
+ }
+
await this.deleteStorageObject(file);
deletedCount++;
diff --git a/packages/twenty-server/src/engine/core-modules/file/files-field/resolvers/files-field.resolver.ts b/packages/twenty-server/src/engine/core-modules/file/files-field/resolvers/files-field.resolver.ts
index fb0b9472b5e..ab931642ab2 100644
--- a/packages/twenty-server/src/engine/core-modules/file/files-field/resolvers/files-field.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/file/files-field/resolvers/files-field.resolver.ts
@@ -19,10 +19,12 @@ import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.g
import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
import { streamToBuffer } from 'src/utils/stream-to-buffer';
import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filters/auth-graphql-api-exception.filter';
+import { UsageLimitGraphqlApiExceptionFilter } from 'src/engine/core-modules/usage-limit/filters/usage-limit-graphql-api-exception.filter';
@UseGuards(WorkspaceAuthGuard)
@UsePipes(ResolverValidationPipe)
@UseFilters(
+ UsageLimitGraphqlApiExceptionFilter,
PreventNestToAutoLogGraphqlErrorsFilter,
AuthGraphqlApiExceptionFilter,
)
diff --git a/packages/twenty-server/src/engine/core-modules/file/files-field/services/__tests__/files-field.service.copy-file-into-files-field.spec.ts b/packages/twenty-server/src/engine/core-modules/file/files-field/services/__tests__/files-field.service.copy-file-into-files-field.spec.ts
index 58be9e9efea..c9e7ec2c474 100644
--- a/packages/twenty-server/src/engine/core-modules/file/files-field/services/__tests__/files-field.service.copy-file-into-files-field.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/file/files-field/services/__tests__/files-field.service.copy-file-into-files-field.spec.ts
@@ -41,7 +41,9 @@ describe('FilesFieldService.copyFileIntoFilesField', () => {
beforeEach(() => {
fileStorageService = {
- copy: jest.fn().mockResolvedValue(undefined),
+ copyFile: jest
+ .fn()
+ .mockImplementation(async ({ fileId }) => ({ id: fileId })),
} as unknown as jest.Mocked<FileStorageService>;
applicationRepository = {
@@ -59,9 +61,6 @@ describe('FilesFieldService.copyFileIntoFilesField', () => {
fileRepository = {
findOne: jest.fn().mockResolvedValue(null),
- insertAndReturnOne: jest
- .fn()
- .mockImplementation(async (_workspaceId, entity) => entity),
} as unknown as jest.Mocked<WorkspaceScopedRepository<FileEntity>>;
});
@@ -78,7 +77,7 @@ describe('FilesFieldService.copyFileIntoFilesField', () => {
}),
).rejects.toThrow(`File ${chatFileId} not found`);
- expect(fileStorageService.copy).not.toHaveBeenCalled();
+ expect(fileStorageService.copyFile).not.toHaveBeenCalled();
});
it('should throw when the upload has not been completed', async () => {
@@ -94,7 +93,7 @@ describe('FilesFieldService.copyFileIntoFilesField', () => {
}),
).rejects.toThrow(`File ${chatFileId} upload has not been completed`);
- expect(fileStorageService.copy).not.toHaveBeenCalled();
+ expect(fileStorageService.copyFile).not.toHaveBeenCalled();
});
it('should copy an agent-chat file into the files field partition', async () => {
@@ -106,9 +105,9 @@ describe('FilesFieldService.copyFileIntoFilesField', () => {
fieldMetadataId,
});
- expect(fileStorageService.copy).toHaveBeenCalledTimes(1);
+ expect(fileStorageService.copyFile).toHaveBeenCalledTimes(1);
- const copyArgs = fileStorageService.copy.mock.calls[0][0];
+ const copyArgs = fileStorageService.copyFile.mock.calls[0][0];
expect(copyArgs.from).toEqual({
workspaceId,
@@ -125,23 +124,14 @@ describe('FilesFieldService.copyFileIntoFilesField', () => {
/^field-universal-identifier\/[0-9a-f-]{36}\.pdf$/,
);
- expect(fileRepository.insertAndReturnOne).toHaveBeenCalledTimes(1);
-
- const [insertWorkspaceId, insertedRow] =
- fileRepository.insertAndReturnOne.mock.calls[0];
-
- expect(insertWorkspaceId).toBe(workspaceId);
- expect(insertedRow.path).toBe(`files-field/${copyArgs.to.resourcePath}`);
- expect(insertedRow.applicationId).toBe('field-application-id');
- expect(insertedRow.mimeType).toBe('application/pdf');
- expect(insertedRow.size).toBe(1234);
- expect(insertedRow.settings).toEqual({
- isTemporaryFile: true,
- toDelete: false,
+ expect(copyArgs).toMatchObject({
+ applicationId: 'field-application-id',
+ mimeType: 'application/pdf',
+ size: 1234,
+ settings: { isTemporaryFile: true, toDelete: false },
});
-
- expect(insertedRow.id).not.toBe(chatFileId);
- expect(result.id).toBe(insertedRow.id);
+ expect(copyArgs.fileId).not.toBe(chatFileId);
+ expect(result.id).toBe(copyArgs.fileId);
});
it('should keep the source extension when copying', async () => {
@@ -155,8 +145,8 @@ describe('FilesFieldService.copyFileIntoFilesField', () => {
fieldMetadataId,
});
- expect(fileStorageService.copy.mock.calls[0][0].to.resourcePath).toMatch(
- /\.csv$/,
- );
+ expect(
+ fileStorageService.copyFile.mock.calls[0][0].to.resourcePath,
+ ).toMatch(/\.csv$/);
});
});
diff --git a/packages/twenty-server/src/engine/core-modules/file/files-field/services/files-field.service.ts b/packages/twenty-server/src/engine/core-modules/file/files-field/services/files-field.service.ts
index 148a1a7aaf6..942ce54422c 100644
--- a/packages/twenty-server/src/engine/core-modules/file/files-field/services/files-field.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/file/files-field/services/files-field.service.ts
@@ -163,7 +163,7 @@ export class FilesFieldService {
const resourcePath = `${fieldMetadata.universalIdentifier}/${copiedFileId}${extension}`;
const sourceFileFolder = sourceFile.path.split('/')[0] as FileFolder;
- await this.fileStorageService.copy({
+ return this.fileStorageService.copyFile({
from: {
workspaceId,
applicationUniversalIdentifier: sourceApplication.universalIdentifier,
@@ -177,15 +177,10 @@ export class FilesFieldService {
fileFolder: FileFolder.FilesField,
resourcePath,
},
- });
-
- return this.fileRepository.insertAndReturnOne(workspaceId, {
- id: copiedFileId,
- path: `${FileFolder.FilesField}/${resourcePath}`,
+ fileId: copiedFileId,
applicationId: fieldMetadata.applicationId,
mimeType: sourceFile.mimeType,
size: sourceFile.size,
- status: FILE_STATUS.UPLOADED,
settings: {
isTemporaryFile: true,
toDelete: false,
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-resource/logic-function-resource.service.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-resource/logic-function-resource.service.ts
index 7ac73476119..c4c8ec503b8 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-resource/logic-function-resource.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-resource/logic-function-resource.service.ts
@@ -3,9 +3,9 @@ import { Injectable } from '@nestjs/common';
import crypto from 'crypto';
import { promises as fs } from 'fs';
import { dirname, join } from 'path';
-import { type QueryRunner } from 'typeorm';
import { FileFolder } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
+import { type QueryRunner } from 'typeorm';
import { FileStorageExceptionCode } from 'src/engine/core-modules/file-storage/interfaces/file-storage-exception';
@@ -212,7 +212,7 @@ export class LogicFunctionResourceService {
workspaceId,
applicationUniversalIdentifier,
}: CopySourceParams): Promise<void> {
- await this.fileStorageService.copy({
+ await this.fileStorageService.copyFileByPath({
from: {
workspaceId,
applicationUniversalIdentifier,
@@ -238,7 +238,7 @@ export class LogicFunctionResourceService {
return;
}
- await this.fileStorageService.copy({
+ await this.fileStorageService.copyFileByPath({
from: {
workspaceId,
applicationUniversalIdentifier,
diff --git a/packages/twenty-server/src/engine/core-modules/metrics/types/metrics-keys.type.ts b/packages/twenty-server/src/engine/core-modules/metrics/types/metrics-keys.type.ts
index 517d406e849..a4693a53d35 100644
--- a/packages/twenty-server/src/engine/core-modules/metrics/types/metrics-keys.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/metrics/types/metrics-keys.type.ts
@@ -63,6 +63,7 @@ export enum MetricsKeys {
JobEnqueueApplicationRateLimited = 'job/enqueue-application-rate-limited',
UsageLimitQuotaAdmittedOnFailure = 'usage-limit-quota/admitted-on-failure',
UsageLimitQuotaAdmittedOnFailureCreditsMicro = 'usage-limit-quota/admitted-on-failure-credits-micro',
+ UsageLimitStockAdmittedOnFailure = 'usage-limit-stock/admitted-on-failure',
JobCompleted = 'job/completed',
JobFailed = 'job/failed',
JobStalled = 'job/stalled',
diff --git a/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts b/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
index f483d0feb74..c5e5289b0de 100644
--- a/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
+++ b/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
@@ -689,6 +689,16 @@ export class ConfigVariables {
@IsOptional()
MAX_TARBALL_UPLOAD_SIZE_BYTES: number = 100 * 1024 * 1024;
+ @ConfigVariablesMetadata({
+ group: ConfigVariablesGroup.STORAGE_CONFIG,
+ description:
+ 'Maximum bytes of file storage a single workspace may hold, all its files counted. An upload that would cross it is refused',
+ type: ConfigVariableType.NUMBER,
+ })
+ @CastToPositiveNumber()
+ @IsOptional()
+ WORKSPACE_STORAGE_LIMIT_BYTES: number = 100 * 1024 * 1024 * 1024;
+
@ConfigVariablesMetadata({
group: ConfigVariablesGroup.LOGIC_FUNCTION_CONFIG,
description: 'Type of function execution (local or Lambda)',
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/limit-kind-rules.constant.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/limit-kind-rules.constant.ts
new file mode 100644
index 00000000000..c143e4c7034
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/limit-kind-rules.constant.ts
@@ -0,0 +1,32 @@
+import { ANCHORED_PERIOD_UNITS } from 'src/engine/core-modules/usage-limit/constants/period-units.constant';
+import {
+ QUOTA_METERS,
+ SPEED_METERS,
+ STOCK_METERS,
+} from 'src/engine/core-modules/usage-limit/constants/usage-meters.constant';
+import { type LimitKind } from 'src/engine/core-modules/usage-limit/types/limit-kind.type';
+import { type LimitKindRule } from 'src/engine/core-modules/usage-limit/types/limit-kind-rule.type';
+
+export const LIMIT_KIND_RULES: Record<LimitKind, LimitKindRule> = {
+ speed: {
+ isAllOperationTypeAllowed: false,
+ allowedPeriodUnits: ['second'],
+ requiredPeriodCount: null,
+ allowedMeters: SPEED_METERS,
+ isBurstValueAllowed: true,
+ },
+ quota: {
+ isAllOperationTypeAllowed: true,
+ allowedPeriodUnits: ANCHORED_PERIOD_UNITS,
+ requiredPeriodCount: 1,
+ allowedMeters: QUOTA_METERS,
+ isBurstValueAllowed: false,
+ },
+ stock: {
+ isAllOperationTypeAllowed: false,
+ allowedPeriodUnits: ['lifetime'],
+ requiredPeriodCount: 1,
+ allowedMeters: STOCK_METERS,
+ isBurstValueAllowed: false,
+ },
+};
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 4fcb508bcdd..ee59361b227 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', 'quota'] as const;
+export const LIMIT_KINDS = ['speed', 'quota', 'stock'] 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
index 483962c3099..c92e8472198 100644
--- 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
@@ -4,4 +4,12 @@ export const PERIOD_UNITS = [
'week',
'month',
'allowancePeriod',
+ 'lifetime',
+] as const;
+
+export const ANCHORED_PERIOD_UNITS = [
+ 'day',
+ 'week',
+ 'month',
+ 'allowancePeriod',
] as const;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/release-stock-counters-script.constant.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/release-stock-counters-script.constant.ts
new file mode 100644
index 00000000000..fe9cf497613
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/release-stock-counters-script.constant.ts
@@ -0,0 +1,21 @@
+import { type CacheScript } from 'src/engine/core-modules/cache-storage/types/cache-script.type';
+
+export const RELEASE_STOCK_COUNTERS_SCRIPT: CacheScript = {
+ name: 'usage-limit:release-stock-counters',
+ source: `
+local amounts = cjson.decode(ARGV[1])
+local caps = cjson.decode(ARGV[2])
+
+for i = 1, #KEYS do
+ if redis.call('EXISTS', KEYS[i]) == 1 then
+ local remaining = redis.call('INCRBY', KEYS[i], amounts[i])
+
+ if remaining > caps[i] then
+ redis.call('SET', KEYS[i], caps[i], 'KEEPTTL')
+ end
+ end
+end
+
+return 1
+`,
+};
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 20a7d3a05a8..66cbedaf153 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
@@ -2,10 +2,7 @@ import { type UsageLimitDefinitions } from 'src/engine/core-modules/usage-limit/
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,
- UsageLimitDefinitions
-> = {
+export const USAGE_LIMIT_DEFINITIONS = {
[UsageResourceType.API]: {
speed: {
allowedOperationTypes: [UsageOperationType.API_REQUEST],
@@ -53,7 +50,21 @@ export const USAGE_LIMIT_DEFINITIONS: Record<
},
[UsageResourceType.WORKFLOW]: {},
[UsageResourceType.APP]: {},
- [UsageResourceType.STORAGE]: {},
+ [UsageResourceType.STORAGE]: {
+ stock: {
+ allowedOperationTypes: [UsageOperationType.STORAGE_FILE],
+ allowedSpenderTypes: ['workspace', 'application'],
+ allowedMeters: ['bytes', 'quantity'],
+ defaults: [
+ {
+ spenderType: 'workspace',
+ meter: 'bytes',
+ limitValueConfigVariable: 'WORKSPACE_STORAGE_LIMIT_BYTES',
+ isOverridable: true,
+ },
+ ],
+ },
+ },
[UsageResourceType.LOGIC_FUNCTION]: {},
[UsageResourceType.EMAIL]: {
speed: {
@@ -98,4 +109,4 @@ export const USAGE_LIMIT_DEFINITIONS: Record<
],
},
},
-};
+} satisfies Record<UsageResourceType, UsageLimitDefinitions>;
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
index e5097521957..9d77ff8f374 100644
--- 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
@@ -1 +1,7 @@
-export const USAGE_METERS = ['creditsUsedMicro', 'quantity'] as const;
+export const SPEED_METERS = ['quantity'] as const;
+
+export const QUOTA_METERS = ['creditsUsedMicro', 'quantity'] as const;
+
+export const STOCK_METERS = ['quantity', 'bytes'] as const;
+
+export const USAGE_METERS = ['creditsUsedMicro', 'quantity', 'bytes'] as const;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/usage-quota-definition.dto.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/usage-quota-definition.dto.ts
index b133580197f..3362c697679 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/usage-quota-definition.dto.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/usage-quota-definition.dto.ts
@@ -1,5 +1,6 @@
import { Field, ObjectType } from '@nestjs/graphql';
+import { type LimitKind } from 'src/engine/core-modules/usage-limit/types/limit-kind.type';
import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
import { type UsageMeter } from 'src/engine/core-modules/usage-limit/types/usage-meter.type';
import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
@@ -10,6 +11,9 @@ export class UsageQuotaDefinitionDTO {
@Field(() => UsageResourceType)
resourceType: UsageResourceType;
+ @Field(() => String)
+ limitKind: LimitKind;
+
@Field(() => [UsageOperationType])
allowedOperationTypes: UsageOperationType[];
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 9f9cc2dbc97..b444c14325c 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,6 +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',
+ STOCK_EXHAUSTED = 'STOCK_EXHAUSTED',
LIMIT_INVALID = 'LIMIT_INVALID',
LIMIT_NOT_ENTITLED = 'LIMIT_NOT_ENTITLED',
}
@@ -21,6 +22,8 @@ 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.STOCK_EXHAUSTED:
+ return msg`This workspace has reached its storage limit.`;
case UsageLimitExceptionCode.LIMIT_INVALID:
return msg`This limit cannot be saved.`;
case UsageLimitExceptionCode.LIMIT_NOT_ENTITLED:
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 1422d62786a..40a8fa3091c 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
@@ -22,6 +22,7 @@ export class UsageLimitGraphqlApiExceptionFilter implements ExceptionFilter {
throw new ForbiddenError(exception);
case UsageLimitExceptionCode.RATE_LIMITED:
case UsageLimitExceptionCode.QUOTA_EXHAUSTED:
+ case UsageLimitExceptionCode.STOCK_EXHAUSTED:
return usageLimitToGraphqlApiExceptionHandler(exception);
default:
assertUnreachable(exception.code);
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-entitlement.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-entitlement.service.ts
index ae667782603..8acaf649609 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-entitlement.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-entitlement.service.ts
@@ -27,13 +27,13 @@ export class UsageLimitEntitlementService implements OnModuleInit {
);
}
- async findEnforceableLimits({
+ async findEnforceableLimits<TLimit extends FlatUsageLimit>({
workspaceId,
limits,
}: {
workspaceId: string;
- limits: FlatUsageLimit[];
- }): Promise<FlatUsageLimit[]> {
+ limits: TLimit[];
+ }): Promise<TLimit[]> {
if (!limits.some((limit) => isIntraWorkspaceScoped(limit.spenderType))) {
return limits;
}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-quota.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-quota.service.ts
index ba651d5f7ef..7b2444ca95f 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-quota.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-quota.service.ts
@@ -24,6 +24,7 @@ import { UsageLimitEntitlementService } from 'src/engine/core-modules/usage-limi
import { UsagePeriodService } from 'src/engine/core-modules/usage-limit/services/usage-period.service';
import { type AllowanceQuotaCounter } from 'src/engine/core-modules/usage-limit/types/allowance-quota-counter.type';
import { type ExhaustedScope } from 'src/engine/core-modules/usage-limit/types/exhausted-scope.type';
+import { type FlatQuotaLimit } from 'src/engine/core-modules/usage-limit/types/flat-quota-limit.type';
import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
import { type LimitConsumption } from 'src/engine/core-modules/usage-limit/types/limit-consumption.type';
import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
@@ -44,6 +45,8 @@ import { computeQuotaConsumed } from 'src/engine/core-modules/usage-limit/utils/
import { findCreditAllowanceProvider } from 'src/engine/core-modules/usage-limit/utils/find-credit-allowance-provider.util';
import { findExhaustedCounters } from 'src/engine/core-modules/usage-limit/utils/find-exhausted-counters.util';
import { findUsageLimitDefinition } from 'src/engine/core-modules/usage-limit/utils/find-usage-limit-definition.util';
+import { isAnchoredPeriodUnit } from 'src/engine/core-modules/usage-limit/utils/is-anchored-period-unit.util';
+import { isQuotaLimit } from 'src/engine/core-modules/usage-limit/utils/is-quota-limit.util';
import { fromConsumeResultsToRemainings } from 'src/engine/core-modules/usage-limit/utils/from-consume-results-to-remainings.util';
import { getPeriodAnchor } from 'src/engine/core-modules/usage-limit/utils/get-period-anchor.util';
import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
@@ -174,7 +177,7 @@ export class UsageLimitQuotaService implements OnModuleInit {
async dropLimitCounter(usageLimit: UsageLimitCounterScope): Promise<void> {
if (
usageLimit.limitKind !== 'quota' ||
- usageLimit.periodUnit === 'second'
+ !isAnchoredPeriodUnit(usageLimit.periodUnit)
) {
return;
}
@@ -289,7 +292,7 @@ export class UsageLimitQuotaService implements OnModuleInit {
{ workspaceId, limits },
);
- const entries = limits.flatMap((limit) => {
+ const entries = limits.filter(isQuotaLimit).flatMap((limit) => {
const period = periodByUnit[limit.periodUnit];
return isDefined(period)
@@ -628,14 +631,14 @@ export class UsageLimitQuotaService implements OnModuleInit {
}: {
workspaceId: string;
resourceType: UsageResourceType;
- }): Promise<FlatUsageLimit[]> {
+ }): Promise<FlatQuotaLimit[]> {
const { usageLimits } = await this.workspaceCacheService.getOrRecompute(
workspaceId,
['usageLimits'],
);
const quotaLimits = (usageLimits.byResourceType[resourceType] ?? []).filter(
- (limit) => limit.limitKind === 'quota',
+ isQuotaLimit,
);
return this.usageLimitEntitlementService.findEnforceableLimits({
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-stock.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-stock.service.ts
new file mode 100644
index 00000000000..767b5141f85
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-stock.service.ts
@@ -0,0 +1,431 @@
+import { Injectable, Logger } from '@nestjs/common';
+
+import { isDefined } from 'twenty-shared/utils';
+
+import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';
+import {
+ CacheLockException,
+ CacheLockExceptionCode,
+} from 'src/engine/core-modules/cache-lock/exceptions/cache-lock.exception';
+import { InjectCacheStorage } from 'src/engine/core-modules/cache-storage/decorators/cache-storage.decorator';
+import { CacheStorageService } from 'src/engine/core-modules/cache-storage/services/cache-storage.service';
+import { type CacheScript } from 'src/engine/core-modules/cache-storage/types/cache-script.type';
+import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';
+import { MetricsService } from 'src/engine/core-modules/metrics/metrics.service';
+import { MetricsKeys } from 'src/engine/core-modules/metrics/types/metrics-keys.type';
+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
+import { CONSUME_QUOTA_COUNTERS_SCRIPT } from 'src/engine/core-modules/usage-limit/constants/consume-quota-counters-script.constant';
+import { RELEASE_STOCK_COUNTERS_SCRIPT } from 'src/engine/core-modules/usage-limit/constants/release-stock-counters-script.constant';
+import { STOCK_METERS } from 'src/engine/core-modules/usage-limit/constants/usage-meters.constant';
+import {
+ UsageLimitException,
+ UsageLimitExceptionCode,
+} from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';
+import { UsageLimitEntitlementService } from 'src/engine/core-modules/usage-limit/services/usage-limit-entitlement.service';
+import { type ComputeUsedStock } from 'src/engine/core-modules/usage-limit/types/compute-used-stock.type';
+import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
+import { type StockCost } from 'src/engine/core-modules/usage-limit/types/stock-cost.type';
+import { type StockCounter } from 'src/engine/core-modules/usage-limit/types/stock-counter.type';
+import { type StockLimitDefault } from 'src/engine/core-modules/usage-limit/types/stock-limit-default.type';
+import { type StockResourceType } from 'src/engine/core-modules/usage-limit/types/stock-resource-type.type';
+import { buildStockCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-stock-counter-key.util';
+import { buildStockCounters } from 'src/engine/core-modules/usage-limit/utils/build-stock-counters.util';
+import { buildStockDefaultCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-stock-default-counter-key.util';
+import { buildStockExhaustedScope } from 'src/engine/core-modules/usage-limit/utils/build-stock-exhausted-scope.util';
+import { buildStockWarmedEntries } from 'src/engine/core-modules/usage-limit/utils/build-stock-warmed-entries.util';
+import { buildStockScopeKey } from 'src/engine/core-modules/usage-limit/utils/build-stock-scope-key.util';
+import { buildStockWarmLockKey } from 'src/engine/core-modules/usage-limit/utils/build-stock-warm-lock-key.util';
+import { findExhaustedStockCounter } from 'src/engine/core-modules/usage-limit/utils/find-exhausted-stock-counter.util';
+import { findUsageLimitDefinition } from 'src/engine/core-modules/usage-limit/utils/find-usage-limit-definition.util';
+import { isStockLimit } from 'src/engine/core-modules/usage-limit/utils/is-stock-limit.util';
+import { isStockResourceType } from 'src/engine/core-modules/usage-limit/utils/is-stock-resource-type.util';
+import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { type UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+import { type UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+
+const STOCK_COUNTER_TTL_MS = 60 * 60 * 1000;
+const STOCK_WARM_LOCK_OPTIONS = { ms: 50, maxRetries: 20, ttl: 10_000 };
+
+type StockArgs = {
+ workspaceId: string;
+ resourceType: UsageResourceType;
+ operationType: UsageOperationType;
+ spenders: UsageSpenders;
+};
+
+@Injectable()
+export class UsageLimitStockService {
+ private readonly logger = new Logger(UsageLimitStockService.name);
+
+ constructor(
+ @InjectCacheStorage(CacheStorageNamespace.EngineUsageLimit)
+ private readonly cacheStorage: CacheStorageService,
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ private readonly cacheLockService: CacheLockService,
+ private readonly usageLimitEntitlementService: UsageLimitEntitlementService,
+ private readonly metricsService: MetricsService,
+ private readonly twentyConfigService: TwentyConfigService,
+ ) {}
+
+ async assertStockAvailable({
+ cost,
+ computeUsedStock,
+ ...args
+ }: StockArgs & {
+ cost: StockCost;
+ computeUsedStock: ComputeUsedStock;
+ }): Promise<void> {
+ try {
+ const counters = await this.buildCounters(args);
+
+ if (counters.length === 0) {
+ return;
+ }
+
+ const remainings = await this.readRemainings({
+ workspaceId: args.workspaceId,
+ counters,
+ computeUsedStock,
+ });
+
+ const exhausted = findExhaustedStockCounter({
+ counters,
+ remainings,
+ cost,
+ });
+
+ if (isDefined(exhausted)) {
+ throw new UsageLimitException(
+ `${exhausted.counter.resourceType} limit reached for this workspace`,
+ UsageLimitExceptionCode.STOCK_EXHAUSTED,
+ { exhaustedScope: buildStockExhaustedScope(exhausted) },
+ );
+ }
+ } catch (error) {
+ this.admitOnFailure({ error, workspaceId: args.workspaceId });
+ }
+ }
+
+ async acquireStock({
+ cost,
+ ...args
+ }: StockArgs & { cost: StockCost }): Promise<void> {
+ await this.applyStockDelta({
+ ...args,
+ cost,
+ script: CONSUME_QUOTA_COUNTERS_SCRIPT,
+ buildArgs: (counters) => [
+ JSON.stringify(counters.map((counter) => cost[counter.meter] ?? 0)),
+ ],
+ });
+ }
+
+ async releaseStock({
+ cost,
+ ...args
+ }: StockArgs & { cost: StockCost }): Promise<void> {
+ await this.applyStockDelta({
+ ...args,
+ cost,
+ script: RELEASE_STOCK_COUNTERS_SCRIPT,
+ buildArgs: (counters) => [
+ JSON.stringify(counters.map((counter) => cost[counter.meter] ?? 0)),
+ JSON.stringify(counters.map((counter) => counter.limitValue)),
+ ],
+ });
+ }
+
+ async dropStockCounters({
+ workspaceId,
+ resourceType,
+ operationType,
+ spenderType,
+ spenderId,
+ }: {
+ workspaceId: string;
+ resourceType: UsageResourceType;
+ operationType: UsageOperationType;
+ spenderType: SpenderType;
+ spenderId: string;
+ }) {
+ const keys = STOCK_METERS.map((meter) =>
+ buildStockCounterKey({
+ workspaceId,
+ resourceType,
+ operationType,
+ spenderType,
+ spenderId,
+ meter,
+ }),
+ );
+
+ if (isStockResourceType(resourceType)) {
+ keys.push(
+ ...this.buildStockLimitDefaults(resourceType)
+ .filter(
+ (stockLimitDefault) =>
+ stockLimitDefault.spenderType === spenderType,
+ )
+ .map((stockLimitDefault) =>
+ buildStockDefaultCounterKey({
+ workspaceId,
+ resourceType,
+ operationType,
+ spenderType,
+ meter: stockLimitDefault.meter,
+ limitValue: stockLimitDefault.limitValue,
+ }),
+ ),
+ );
+ }
+
+ await this.dropCounterKeys({ workspaceId, keys });
+ }
+
+ async invalidateStock(args: StockArgs): Promise<void> {
+ try {
+ const counters = await this.buildCounters(args);
+
+ if (counters.length === 0) {
+ return;
+ }
+
+ await this.dropCounterKeys({
+ workspaceId: args.workspaceId,
+ keys: counters.map((counter) => counter.key),
+ });
+ } catch (error) {
+ this.recordDegradation({ error, workspaceId: args.workspaceId });
+ }
+ }
+
+ private async dropCounterKeys({
+ workspaceId,
+ keys,
+ }: {
+ workspaceId: string;
+ keys: string[];
+ }): Promise<void> {
+ try {
+ await this.cacheLockService.withLock(
+ () => this.cacheStorage.mdel(keys),
+ buildStockWarmLockKey(workspaceId),
+ STOCK_WARM_LOCK_OPTIONS,
+ );
+ } catch (error) {
+ if (
+ !(error instanceof CacheLockException) ||
+ error.code !== CacheLockExceptionCode.LOCK_ACQUISITION_TIMEOUT
+ ) {
+ throw error;
+ }
+
+ this.logger.warn(
+ `Dropping stock counters ${keys.join(', ')} without the warm lock: ${error.message}`,
+ );
+
+ await this.cacheStorage.mdel(keys);
+ }
+ }
+
+ private async applyStockDelta({
+ cost,
+ script,
+ buildArgs,
+ ...args
+ }: StockArgs & {
+ cost: StockCost;
+ script: CacheScript;
+ buildArgs: (counters: StockCounter[]) => string[];
+ }): Promise<void> {
+ try {
+ const counters = (await this.buildCounters(args)).filter(
+ (counter) => (cost[counter.meter] ?? 0) > 0,
+ );
+
+ if (counters.length === 0) {
+ return;
+ }
+
+ await this.cacheStorage.runScript({
+ script,
+ keys: counters.map((counter) => counter.key),
+ args: buildArgs(counters),
+ });
+ } catch (error) {
+ this.recordDegradation({ error, workspaceId: args.workspaceId });
+ }
+ }
+
+ private async buildCounters({
+ workspaceId,
+ resourceType,
+ operationType,
+ spenders,
+ }: StockArgs): Promise<StockCounter[]> {
+ if (!isStockResourceType(resourceType)) {
+ return [];
+ }
+
+ const { usageLimits } = await this.workspaceCacheService.getOrRecompute(
+ workspaceId,
+ ['usageLimits'],
+ );
+
+ const enforceableLimits =
+ await this.usageLimitEntitlementService.findEnforceableLimits({
+ workspaceId,
+ limits: (usageLimits.byResourceType[resourceType] ?? []).filter(
+ isStockLimit,
+ ),
+ });
+
+ return buildStockCounters({
+ workspaceId,
+ resourceType,
+ operationType,
+ spenders,
+ limits: enforceableLimits,
+ stockLimitDefaults: this.buildStockLimitDefaults(resourceType),
+ });
+ }
+
+ private buildStockLimitDefaults(
+ resourceType: StockResourceType,
+ ): StockLimitDefault[] {
+ const definition = findUsageLimitDefinition({
+ resourceType,
+ limitKind: 'stock',
+ });
+
+ return (definition?.defaults ?? []).map((stockLimitDefaultDefinition) => ({
+ spenderType: stockLimitDefaultDefinition.spenderType,
+ meter: stockLimitDefaultDefinition.meter,
+ isOverridable: stockLimitDefaultDefinition.isOverridable,
+ limitValue: this.twentyConfigService.get(
+ stockLimitDefaultDefinition.limitValueConfigVariable,
+ ),
+ }));
+ }
+
+ private async readRemainings({
+ workspaceId,
+ counters,
+ computeUsedStock,
+ }: {
+ workspaceId: string;
+ counters: StockCounter[];
+ computeUsedStock: ComputeUsedStock;
+ }): Promise<(number | null)[]> {
+ const remainings = await this.cacheStorage.mget<number>(
+ counters.map((counter) => counter.key),
+ );
+
+ if (remainings.every(isDefined)) {
+ return remainings;
+ }
+
+ return this.warmColdCounters({ workspaceId, counters, computeUsedStock });
+ }
+
+ private async warmColdCounters({
+ workspaceId,
+ counters,
+ computeUsedStock,
+ }: {
+ workspaceId: string;
+ counters: StockCounter[];
+ computeUsedStock: ComputeUsedStock;
+ }): Promise<(number | null)[]> {
+ return this.cacheLockService.withLock(
+ async () => {
+ const remainings = await this.cacheStorage.mget<number>(
+ counters.map((counter) => counter.key),
+ );
+
+ if (remainings.every(isDefined)) {
+ return remainings;
+ }
+
+ const coldCounters = counters.filter(
+ (_, index) => !isDefined(remainings[index]),
+ );
+
+ const scopeKeys = [
+ ...new Map(
+ coldCounters.map((counter) => [
+ buildStockScopeKey(counter),
+ counter,
+ ]),
+ ).entries(),
+ ];
+
+ const usedByScope = new Map(
+ await Promise.all(
+ scopeKeys.map(
+ async ([scopeKey, counter]) =>
+ [
+ scopeKey,
+ await computeUsedStock({
+ spenderType: counter.spenderType,
+ spenderId: counter.spenderId,
+ }),
+ ] as const,
+ ),
+ ),
+ );
+
+ const warmedEntries = buildStockWarmedEntries({
+ coldCounters,
+ usedByScope,
+ ttl: STOCK_COUNTER_TTL_MS,
+ });
+
+ await this.cacheStorage.mset(warmedEntries);
+
+ const warmedValueByKey = new Map(
+ warmedEntries.map((entry) => [entry.key, entry.value]),
+ );
+
+ return counters.map(
+ (counter, index) =>
+ remainings[index] ?? warmedValueByKey.get(counter.key) ?? null,
+ );
+ },
+ buildStockWarmLockKey(workspaceId),
+ STOCK_WARM_LOCK_OPTIONS,
+ );
+ }
+
+ private admitOnFailure({
+ error,
+ workspaceId,
+ }: {
+ error: unknown;
+ workspaceId: string;
+ }): void {
+ if (error instanceof UsageLimitException) {
+ throw error;
+ }
+
+ this.recordDegradation({ error, workspaceId });
+ }
+
+ private recordDegradation({
+ error,
+ workspaceId,
+ }: {
+ error: unknown;
+ workspaceId: string;
+ }): void {
+ this.logger.error(
+ `Usage stock enforcement degraded for workspace ${workspaceId}: ${error instanceof Error ? error.message : 'unknown error'}`,
+ );
+
+ this.metricsService.incrementCounterBy({
+ key: MetricsKeys.UsageLimitStockAdmittedOnFailure,
+ amount: 1,
+ });
+ }
+}
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 b23757af0a1..a3cda6b8cad 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
@@ -13,12 +13,14 @@ import {
} from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';
import { UsageLimitEntitlementService } from 'src/engine/core-modules/usage-limit/services/usage-limit-entitlement.service';
import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';
+import { UsageLimitStockService } from 'src/engine/core-modules/usage-limit/services/usage-limit-stock.service';
import { UsagePeriodService } from 'src/engine/core-modules/usage-limit/services/usage-period.service';
import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
import { UsageLimitEntity } from 'src/engine/core-modules/usage-limit/usage-limit.entity';
import { buildUsageLimitScope } from 'src/engine/core-modules/usage-limit/utils/build-usage-limit-scope.util';
import { isIntraWorkspaceScoped } from 'src/engine/core-modules/usage-limit/utils/is-intra-workspace-scoped.util';
import { validateUsageLimitAgainstDefinition } from 'src/engine/core-modules/usage-limit/utils/validate-usage-limit-against-definition.util';
+import { validateUsageLimitAgainstKindRule } from 'src/engine/core-modules/usage-limit/utils/validate-usage-limit-against-kind-rule.util';
import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
import { AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';
import { LogicFunctionEntity } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
@@ -43,6 +45,7 @@ export class UsageLimitService {
private readonly logicFunctionRepository: WorkspaceScopedRepository<LogicFunctionEntity>,
private readonly workspaceCacheService: WorkspaceCacheService,
private readonly usageLimitQuotaService: UsageLimitQuotaService,
+ private readonly usageLimitStockService: UsageLimitStockService,
private readonly usageLimitEntitlementService: UsageLimitEntitlementService,
private readonly usagePeriodService: UsagePeriodService,
) {}
@@ -80,7 +83,7 @@ export class UsageLimitService {
{ where: scope },
);
- await this.usageLimitQuotaService.dropLimitCounter(usageLimit);
+ await this.dropCounter(usageLimit);
return usageLimit;
}
@@ -133,8 +136,8 @@ export class UsageLimitService {
);
// counters are keyed by scope, so a scope change leaves two of them to rewarm
- await this.usageLimitQuotaService.dropLimitCounter(usageLimit);
- await this.usageLimitQuotaService.dropLimitCounter(updatedUsageLimit);
+ await this.dropCounter(usageLimit);
+ await this.dropCounter(updatedUsageLimit);
return updatedUsageLimit;
}
@@ -172,6 +175,7 @@ export class UsageLimitService {
input: CreateUsageLimitInput;
}): Promise<void> {
validateUsageLimitAgainstDefinition(input);
+ validateUsageLimitAgainstKindRule(input);
if (
isIntraWorkspaceScoped(input.spenderType) &&
@@ -231,11 +235,25 @@ export class UsageLimitService {
'usageLimits',
]);
- await this.usageLimitQuotaService.dropLimitCounter(usageLimit);
+ await this.dropCounter(usageLimit);
return true;
}
+ private async dropCounter(usageLimit: UsageLimitEntity): Promise<void> {
+ if (usageLimit.limitKind === 'stock') {
+ return this.usageLimitStockService.dropStockCounters({
+ workspaceId: usageLimit.workspaceId,
+ resourceType: usageLimit.resourceType,
+ operationType: usageLimit.operationType,
+ spenderType: usageLimit.spenderType,
+ spenderId: usageLimit.spenderId,
+ });
+ }
+
+ return this.usageLimitQuotaService.dropLimitCounter(usageLimit);
+ }
+
private async validateSpenderBelongsToWorkspace({
workspaceId,
spenderType,
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-period.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-period.service.ts
index f205a372464..10fc04e779f 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-period.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-period.service.ts
@@ -15,6 +15,7 @@ import { findCreditAllowanceProvider } from 'src/engine/core-modules/usage-limit
import { getCalendarDayPeriod } from 'src/engine/core-modules/usage-limit/utils/get-calendar-day-period.util';
import { getCalendarMonthPeriod } from 'src/engine/core-modules/usage-limit/utils/get-calendar-month-period.util';
import { getCalendarWeekPeriod } from 'src/engine/core-modules/usage-limit/utils/get-calendar-week-period.util';
+import { isAnchoredPeriodUnit } from 'src/engine/core-modules/usage-limit/utils/is-anchored-period-unit.util';
@Injectable()
export class UsagePeriodService implements OnModuleInit {
@@ -57,12 +58,7 @@ export class UsagePeriodService implements OnModuleInit {
}): Promise<Partial<Record<PeriodUnit, UsagePeriod>>> {
const periodUnits = [
...new Set(
- limits
- .map((limit) => limit.periodUnit)
- .filter(
- (periodUnit): periodUnit is AnchoredPeriodUnit =>
- periodUnit !== 'second',
- ),
+ limits.map((limit) => limit.periodUnit).filter(isAnchoredPeriodUnit),
),
];
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-quota-consumption.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-quota-consumption.service.ts
index d63b3270a3c..38b7a268248 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-quota-consumption.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-quota-consumption.service.ts
@@ -16,6 +16,8 @@ import { type UsageQuotaWithConsumption } from 'src/engine/core-modules/usage-li
import { type UsageLimitEntity } from 'src/engine/core-modules/usage-limit/usage-limit.entity';
import { buildCustomQuota } from 'src/engine/core-modules/usage-limit/utils/build-custom-quota.util';
import { getPeriodAnchor } from 'src/engine/core-modules/usage-limit/utils/get-period-anchor.util';
+import { isAnchoredPeriodUnit } from 'src/engine/core-modules/usage-limit/utils/is-anchored-period-unit.util';
+import { isQuotaMeter } from 'src/engine/core-modules/usage-limit/utils/is-quota-meter.util';
import { normalizeSpenderId } from 'src/engine/core-modules/usage-limit/utils/normalize-spender-id.util';
import { groupSpenderIdsByType } from 'src/engine/core-modules/usage-limit/utils/group-spender-ids-by-type.util';
import { UsageAnalyticsService } from 'src/engine/core-modules/usage/services/usage-analytics.service';
@@ -62,10 +64,12 @@ export class UsageQuotaConsumptionService {
}): Promise<UsageQuotaScopeConsumption | null> {
const periodUnit = scope.periodUnit;
- if (periodUnit === 'second') {
+ if (!isAnchoredPeriodUnit(periodUnit) || !isQuotaMeter(scope.meter)) {
return null;
}
+ const meter = scope.meter;
+
const period = await this.usagePeriodService.findCurrentPeriod({
workspaceId,
periodUnit,
@@ -89,7 +93,7 @@ export class UsageQuotaConsumptionService {
});
return {
- consumedValue: Number(totals[scope.meter]),
+ consumedValue: Number(totals[meter]),
periodStart: period.periodStart,
periodEnd: period.periodEnd,
};
@@ -125,7 +129,7 @@ export class UsageQuotaConsumptionService {
const enforceableIds = new Set(enforceableLimits.map((limit) => limit.id));
- const [consumptionById, spenderLabelById] = await Promise.all([
+ const [quotaConsumptionById, spenderLabelById] = await Promise.all([
this.usageLimitQuotaService.readLimitConsumptions({
workspaceId,
limits: enforceableLimits,
@@ -137,7 +141,7 @@ export class UsageQuotaConsumptionService {
buildCustomQuota({
usageLimit,
isEnforced: enforceableIds.has(usageLimit.id),
- consumption: consumptionById.get(usageLimit.id),
+ consumption: quotaConsumptionById.get(usageLimit.id),
spenderLabel: spenderLabelById.get(usageLimit.spenderId) ?? null,
}),
);
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
index b86fca474f8..5922fe2ff79 100644
--- 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
@@ -1,3 +1,3 @@
-import { type PeriodUnit } from 'src/engine/core-modules/usage-limit/types/period-unit.type';
+import { type ANCHORED_PERIOD_UNITS } from 'src/engine/core-modules/usage-limit/constants/period-units.constant';
-export type AnchoredPeriodUnit = Exclude<PeriodUnit, 'second'>;
+export type AnchoredPeriodUnit = (typeof ANCHORED_PERIOD_UNITS)[number];
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/compute-used-stock.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/compute-used-stock.type.ts
new file mode 100644
index 00000000000..1f9549448d2
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/compute-used-stock.type.ts
@@ -0,0 +1,6 @@
+import { type StockMeter } from 'src/engine/core-modules/usage-limit/types/stock-meter.type';
+import { type StockScope } from 'src/engine/core-modules/usage-limit/types/stock-scope.type';
+
+export type ComputeUsedStock = (
+ scope: StockScope,
+) => Promise<Record<StockMeter, number>>;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/flat-quota-limit.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/flat-quota-limit.type.ts
new file mode 100644
index 00000000000..11025ef727c
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/flat-quota-limit.type.ts
@@ -0,0 +1,6 @@
+import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
+import { type QuotaMeter } from 'src/engine/core-modules/usage-limit/types/quota-meter.type';
+
+export type FlatQuotaLimit = Omit<FlatUsageLimit, 'meter'> & {
+ meter: QuotaMeter;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/flat-stock-limit.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/flat-stock-limit.type.ts
new file mode 100644
index 00000000000..0cbfa8431e6
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/flat-stock-limit.type.ts
@@ -0,0 +1,8 @@
+import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
+import { type StockMeter } from 'src/engine/core-modules/usage-limit/types/stock-meter.type';
+import { type StockResourceType } from 'src/engine/core-modules/usage-limit/types/stock-resource-type.type';
+
+export type FlatStockLimit = Omit<FlatUsageLimit, 'meter' | 'resourceType'> & {
+ meter: StockMeter;
+ resourceType: StockResourceType;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-consumption.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-consumption.type.ts
index f3c0d397522..87176042395 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-consumption.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-consumption.type.ts
@@ -1,6 +1,6 @@
export type LimitConsumption = {
consumedValue: number | null;
remainingValue: number | null;
- periodStart: Date;
- periodEnd: Date;
+ periodStart: Date | null;
+ periodEnd: Date | null;
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-kind-rule.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-kind-rule.type.ts
new file mode 100644
index 00000000000..2e3d76756d3
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-kind-rule.type.ts
@@ -0,0 +1,10 @@
+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';
+
+export type LimitKindRule = {
+ isAllOperationTypeAllowed: boolean;
+ allowedPeriodUnits: readonly PeriodUnit[];
+ requiredPeriodCount: number | null;
+ allowedMeters: readonly UsageMeter[];
+ isBurstValueAllowed: boolean;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-quota-counter.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-quota-counter.type.ts
index 22e616dd3c8..a7f7d07d8a7 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-quota-counter.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-quota-counter.type.ts
@@ -1,6 +1,6 @@
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';
+import { type QuotaMeter } from 'src/engine/core-modules/usage-limit/types/quota-meter.type';
import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { type UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
@@ -8,7 +8,7 @@ export type LimitQuotaCounter = {
kind: 'limit';
key: string;
limitValue: number;
- meter: UsageMeter;
+ meter: QuotaMeter;
resourceType: UsageResourceType;
periodUnit: PeriodUnit;
periodStart: Date;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-cost.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-cost.type.ts
index 32592dc9c76..31e83b0b76a 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-cost.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-cost.type.ts
@@ -1,3 +1,3 @@
-import { type UsageMeter } from 'src/engine/core-modules/usage-limit/types/usage-meter.type';
+import { type QuotaMeter } from 'src/engine/core-modules/usage-limit/types/quota-meter.type';
-export type QuotaCost = Record<UsageMeter, number>;
+export type QuotaCost = Record<QuotaMeter, number>;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-meter.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-meter.type.ts
new file mode 100644
index 00000000000..bdc9461d27b
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-meter.type.ts
@@ -0,0 +1,3 @@
+import { type QUOTA_METERS } from 'src/engine/core-modules/usage-limit/constants/usage-meters.constant';
+
+export type QuotaMeter = (typeof QUOTA_METERS)[number];
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-cost.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-cost.type.ts
new file mode 100644
index 00000000000..94085ba28a5
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-cost.type.ts
@@ -0,0 +1,3 @@
+import { type StockMeter } from 'src/engine/core-modules/usage-limit/types/stock-meter.type';
+
+export type StockCost = Partial<Record<StockMeter, number>>;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-counter.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-counter.type.ts
new file mode 100644
index 00000000000..eb30fd0d750
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-counter.type.ts
@@ -0,0 +1,15 @@
+import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
+import { type StockMeter } from 'src/engine/core-modules/usage-limit/types/stock-meter.type';
+import { type StockResourceType } from 'src/engine/core-modules/usage-limit/types/stock-resource-type.type';
+
+export type StockCounter = {
+ key: string;
+ isDefault: boolean;
+ limitValue: number;
+ meter: StockMeter;
+ resourceType: StockResourceType;
+ operationType: UsageOperationType;
+ spenderType: SpenderType;
+ spenderId: string | null;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-limit-default-definition.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-limit-default-definition.type.ts
new file mode 100644
index 00000000000..961d034061c
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-limit-default-definition.type.ts
@@ -0,0 +1,10 @@
+import { type NumericConfigVariableKey } from 'src/engine/core-modules/twenty-config/types/numeric-config-variable-key.type';
+import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
+import { type StockMeter } from 'src/engine/core-modules/usage-limit/types/stock-meter.type';
+
+export type StockLimitDefaultDefinition = {
+ spenderType: SpenderType;
+ meter: StockMeter;
+ isOverridable: boolean;
+ limitValueConfigVariable: NumericConfigVariableKey;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-limit-default.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-limit-default.type.ts
new file mode 100644
index 00000000000..7a6dad2cfc1
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-limit-default.type.ts
@@ -0,0 +1,8 @@
+import { type StockLimitDefaultDefinition } from 'src/engine/core-modules/usage-limit/types/stock-limit-default-definition.type';
+
+export type StockLimitDefault = Pick<
+ StockLimitDefaultDefinition,
+ 'spenderType' | 'meter' | 'isOverridable'
+> & {
+ limitValue: number;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-meter.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-meter.type.ts
new file mode 100644
index 00000000000..1458f66bcdd
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-meter.type.ts
@@ -0,0 +1,3 @@
+import { type STOCK_METERS } from 'src/engine/core-modules/usage-limit/constants/usage-meters.constant';
+
+export type StockMeter = (typeof STOCK_METERS)[number];
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-resource-type.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-resource-type.type.ts
new file mode 100644
index 00000000000..dfe98723b4e
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-resource-type.type.ts
@@ -0,0 +1,9 @@
+import { type USAGE_LIMIT_DEFINITIONS } from 'src/engine/core-modules/usage-limit/constants/usage-limit-definitions.constant';
+
+type UsageLimitDefinitionsByResourceType = typeof USAGE_LIMIT_DEFINITIONS;
+
+export type StockResourceType = {
+ [TResourceType in keyof UsageLimitDefinitionsByResourceType]: 'stock' extends keyof UsageLimitDefinitionsByResourceType[TResourceType]
+ ? TResourceType
+ : never;
+}[keyof UsageLimitDefinitionsByResourceType];
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-scope.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-scope.type.ts
new file mode 100644
index 00000000000..bb37d7734f3
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-scope.type.ts
@@ -0,0 +1,6 @@
+import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
+
+export type StockScope = {
+ spenderType: SpenderType;
+ spenderId: string | null;
+};
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 c2539d1581a..8836e7066a6 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,21 +1,31 @@
-import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
+import { type QuotaMeter } from 'src/engine/core-modules/usage-limit/types/quota-meter.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 SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
+import { type StockLimitDefaultDefinition } from 'src/engine/core-modules/usage-limit/types/stock-limit-default-definition.type';
+import { type StockMeter } from 'src/engine/core-modules/usage-limit/types/stock-meter.type';
import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
-export type SpeedLimitDefinition = {
+type SpeedLimitDefinition = {
allowedOperationTypes: UsageOperationType[];
allowedSpenderTypes: SpenderType[];
defaults: SpeedLimitDefaultDefinition[];
};
-export type QuotaLimitDefinition = {
+type QuotaLimitDefinition = {
+ allowedOperationTypes: UsageOperationType[];
+ allowedSpenderTypes: SpenderType[];
+ allowedMeters: QuotaMeter[];
+};
+
+type StockLimitDefinition = {
allowedOperationTypes: UsageOperationType[];
allowedSpenderTypes: SpenderType[];
- allowedMeters: UsageMeter[];
+ allowedMeters: StockMeter[];
+ defaults: StockLimitDefaultDefinition[];
};
export type UsageLimitDefinitions = {
speed?: SpeedLimitDefinition;
quota?: QuotaLimitDefinition;
+ stock?: StockLimitDefinition;
};
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 ad8f70b685a..774ebed1fe1 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
@@ -11,7 +11,7 @@ import { type LimitKind } from 'src/engine/core-modules/usage-limit/types/limit-
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 { nullableBigintColumnTransformer } from 'src/engine/twenty-orm/utils/nullable-bigint-column-transformer.util';
import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { type UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
import { WorkspaceRelatedEntity } from 'src/engine/workspace-manager/types/workspace-related-entity';
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 94dfc4effbb..72b2e81aa27 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
@@ -7,7 +7,7 @@ import { CacheLockModule } from 'src/engine/core-modules/cache-lock/cache-lock.m
import { MetricsModule } from 'src/engine/core-modules/metrics/metrics.module';
import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';
import { UsagePeriodService } from 'src/engine/core-modules/usage-limit/services/usage-period.service';
-import { UsageModule } from 'src/engine/core-modules/usage/usage.module';
+import { UsageAnalyticsModule } from 'src/engine/core-modules/usage/usage-analytics.module';
import { ApplicationEntity } from 'src/engine/core-modules/application/application.entity';
import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
import { AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';
@@ -16,6 +16,7 @@ import { UsageQuotaConsumptionService } from 'src/engine/core-modules/usage-limi
import { UsageQuotaDefinitionService } from 'src/engine/core-modules/usage-limit/services/usage-quota-definition.service';
import { UsageLimitEntitlementService } from 'src/engine/core-modules/usage-limit/services/usage-limit-entitlement.service';
import { UsageLimitSpeedService } from 'src/engine/core-modules/usage-limit/services/usage-limit-speed.service';
+import { UsageLimitStockService } from 'src/engine/core-modules/usage-limit/services/usage-limit-stock.service';
import { UsageLimitResolver } from 'src/engine/core-modules/usage-limit/usage-limit.resolver';
import { UsageLimitService } from 'src/engine/core-modules/usage-limit/services/usage-limit.service';
import { UsageLimitsCacheService } from 'src/engine/core-modules/usage-limit/services/usage-limits-cache.service';
@@ -39,11 +40,12 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
DiscoveryModule,
CacheLockModule,
MetricsModule,
- UsageModule,
+ UsageAnalyticsModule,
],
providers: [
UsageLimitQuotaService,
UsageLimitSpeedService,
+ UsageLimitStockService,
UsageLimitEntitlementService,
UsageLimitsCacheService,
UsagePeriodService,
@@ -62,6 +64,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
UsageLimitEntitlementService,
UsageLimitQuotaService,
UsageLimitSpeedService,
+ UsageLimitStockService,
UsageLimitsCacheService,
],
})
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-counters.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-counters.util.spec.ts
index 6bf0da131c6..5bb264ca9fc 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-counters.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-counters.util.spec.ts
@@ -1,4 +1,4 @@
-import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
+import { type FlatQuotaLimit } from 'src/engine/core-modules/usage-limit/types/flat-quota-limit.type';
import { buildQuotaCounters } from 'src/engine/core-modules/usage-limit/utils/build-quota-counters.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';
@@ -13,7 +13,7 @@ const WEEK_PERIOD = {
periodEnd: new Date('2026-08-31T00:00:00.000Z'),
};
-const buildLimit = (overrides: Partial<FlatUsageLimit>): FlatUsageLimit => ({
+const buildLimit = (overrides: Partial<FlatQuotaLimit>): FlatQuotaLimit => ({
id: 'limit-1',
resourceType: UsageResourceType.AI,
operationType: UsageOperationType.AI_CHAT_TOKEN,
@@ -28,7 +28,7 @@ const buildLimit = (overrides: Partial<FlatUsageLimit>): FlatUsageLimit => ({
...overrides,
});
-const buildCounters = ({ limits }: { limits: FlatUsageLimit[] }) =>
+const buildCounters = ({ limits }: { limits: FlatQuotaLimit[] }) =>
buildQuotaCounters({
limits,
usageSpenders: { userWorkspaceId: 'user-1' },
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-definitions.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-definitions.util.spec.ts
index 0d07a21925c..b11ccd6f722 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-definitions.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-definitions.util.spec.ts
@@ -2,19 +2,22 @@ import { buildQuotaDefinitions } from 'src/engine/core-modules/usage-limit/utils
import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
describe('buildQuotaDefinitions', () => {
- it('exposes only the resources that define a quota', () => {
- const resourceTypes = buildQuotaDefinitions().map(
- (definition) => definition.resourceType,
- );
-
- expect(resourceTypes).toEqual([UsageResourceType.AI]);
+ it('exposes only resources with quota definitions', () => {
+ expect(
+ buildQuotaDefinitions().map(({ resourceType, limitKind }) => [
+ resourceType,
+ limitKind,
+ ]),
+ ).toEqual([[UsageResourceType.AI, 'quota']]);
});
it('carries the allow lists a form needs to offer a scope', () => {
- const [definition] = buildQuotaDefinitions();
+ const quota = buildQuotaDefinitions().find(
+ (definition) => definition.limitKind === 'quota',
+ );
- expect(definition.allowedOperationTypes.length).toBeGreaterThan(0);
- expect(definition.allowedSpenderTypes).toContain('workspace');
- expect(definition.allowedMeters).toContain('creditsUsedMicro');
+ expect(quota?.allowedOperationTypes.length).toBeGreaterThan(0);
+ expect(quota?.allowedSpenderTypes).toContain('workspace');
+ expect(quota?.allowedMeters).toContain('creditsUsedMicro');
});
});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-stock-counter-key.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-stock-counter-key.util.spec.ts
new file mode 100644
index 00000000000..24f02766c3d
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-stock-counter-key.util.spec.ts
@@ -0,0 +1,43 @@
+import { buildStockCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-stock-counter-key.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';
+
+const WORKSPACE_ID = 'workspace-1';
+
+const buildKey = (
+ overrides: Partial<Parameters<typeof buildStockCounterKey>[0]> = {},
+) =>
+ buildStockCounterKey({
+ workspaceId: WORKSPACE_ID,
+ resourceType: UsageResourceType.STORAGE,
+ operationType: UsageOperationType.STORAGE_FILE,
+ spenderType: 'workspace',
+ spenderId: null,
+ meter: 'bytes',
+ ...overrides,
+ });
+
+describe('buildStockCounterKey', () => {
+ it('hashes on the workspace so every counter of a workspace shares a slot', () => {
+ expect(buildKey()).toBe(
+ `{${WORKSPACE_ID}}:stock:STORAGE:STORAGE_FILE:workspace:-:bytes`,
+ );
+ });
+
+ it('names an absent spender rather than leaving the segment empty', () => {
+ expect(buildKey({ spenderType: 'application', spenderId: 'app-1' })).toBe(
+ `{${WORKSPACE_ID}}:stock:STORAGE:STORAGE_FILE:application:app-1:bytes`,
+ );
+ });
+
+ it.each([
+ ['operationType', { operationType: UsageOperationType.CALL_RECORDING }],
+ ['meter', { meter: 'quantity' as const }],
+ ['spenderId', { spenderId: 'app-1' }],
+ ])(
+ 'gives two limits differing only by %s their own counter',
+ (_, differs) => {
+ expect(buildKey(differs)).not.toBe(buildKey());
+ },
+ );
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-stock-counters.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-stock-counters.util.spec.ts
new file mode 100644
index 00000000000..e7c99cb83f9
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-stock-counters.util.spec.ts
@@ -0,0 +1,140 @@
+import { type FlatStockLimit } from 'src/engine/core-modules/usage-limit/types/flat-stock-limit.type';
+import { type StockLimitDefault } from 'src/engine/core-modules/usage-limit/types/stock-limit-default.type';
+import { buildStockCounters } from 'src/engine/core-modules/usage-limit/utils/build-stock-counters.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';
+
+const WORKSPACE_ID = 'workspace-1';
+
+const buildLimit = (
+ overrides: Partial<FlatStockLimit> = {},
+): FlatStockLimit => ({
+ id: 'limit-1',
+ resourceType: UsageResourceType.STORAGE,
+ operationType: UsageOperationType.STORAGE_FILE,
+ spenderType: 'workspace',
+ spenderId: '',
+ limitKind: 'stock',
+ periodCount: 1,
+ periodUnit: 'lifetime',
+ meter: 'bytes',
+ limitValue: 500,
+ burstValue: null,
+ ...overrides,
+});
+
+const buildDefault = (
+ overrides: Partial<StockLimitDefault> = {},
+): StockLimitDefault => ({
+ spenderType: 'workspace',
+ meter: 'bytes',
+ limitValue: 1_000,
+ isOverridable: true,
+ ...overrides,
+});
+
+const build = ({
+ limits = [],
+ stockLimitDefaults = [],
+ spenders = {},
+}: {
+ limits?: FlatStockLimit[];
+ stockLimitDefaults?: StockLimitDefault[];
+ spenders?: { applicationId?: string };
+}) =>
+ buildStockCounters({
+ workspaceId: WORKSPACE_ID,
+ resourceType: UsageResourceType.STORAGE,
+ operationType: UsageOperationType.STORAGE_FILE,
+ spenders,
+ limits,
+ stockLimitDefaults,
+ });
+
+describe('buildStockCounters', () => {
+ it('caps the workspace with the default when nothing is stored', () => {
+ expect(build({ stockLimitDefaults: [buildDefault()] })).toEqual([
+ expect.objectContaining({
+ isDefault: true,
+ limitValue: 1_000,
+ meter: 'bytes',
+ spenderType: 'workspace',
+ spenderId: null,
+ }),
+ ]);
+ });
+
+ it.each([500, 2_000])(
+ 'overrides the default with a workspace limit of %i',
+ (limitValue) => {
+ expect(
+ build({
+ limits: [buildLimit({ limitValue })],
+ stockLimitDefaults: [buildDefault()],
+ }),
+ ).toEqual([expect.objectContaining({ isDefault: false, limitValue })]);
+ },
+ );
+
+ it('keeps a non-overridable default alongside a stored limit', () => {
+ const counters = build({
+ limits: [buildLimit()],
+ stockLimitDefaults: [buildDefault({ isOverridable: false })],
+ });
+
+ expect(counters.map((counter) => counter.isDefault)).toEqual([false, true]);
+ expect(new Set(counters.map((counter) => counter.key)).size).toBe(2);
+ });
+
+ it.each([
+ { spenderType: 'application' as const, spenderId: 'application-1' },
+ { meter: 'quantity' as const },
+ ])(
+ 'preserves the workspace byte default for a different scope: %j',
+ (overrides) => {
+ const counters = build({
+ limits: [buildLimit(overrides)],
+ stockLimitDefaults: [buildDefault()],
+ spenders: { applicationId: 'application-1' },
+ });
+
+ expect(counters.map((counter) => counter.isDefault)).toEqual([
+ false,
+ true,
+ ]);
+ },
+ );
+
+ it('preserves the default for a different operation', () => {
+ expect(
+ build({
+ limits: [buildLimit({ operationType: UsageOperationType.API_REQUEST })],
+ stockLimitDefaults: [buildDefault()],
+ }),
+ ).toEqual([expect.objectContaining({ isDefault: true })]);
+ });
+
+ it('keys the default by its value so a changed setting warms afresh', () => {
+ const [before] = build({ stockLimitDefaults: [buildDefault()] });
+ const [after] = build({
+ stockLimitDefaults: [buildDefault({ limitValue: 2_000 })],
+ });
+
+ expect(before.key).not.toBe(after.key);
+ });
+
+ it('skips a default whose spender type the call does not carry', () => {
+ expect(
+ build({
+ stockLimitDefaults: [buildDefault({ spenderType: 'application' })],
+ }),
+ ).toEqual([]);
+
+ expect(
+ build({
+ stockLimitDefaults: [buildDefault({ spenderType: 'application' })],
+ spenders: { applicationId: 'application-1' },
+ }),
+ ).toHaveLength(1);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-stock-warmed-entries.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-stock-warmed-entries.util.spec.ts
new file mode 100644
index 00000000000..178c1c0b249
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-stock-warmed-entries.util.spec.ts
@@ -0,0 +1,101 @@
+import { type StockCounter } from 'src/engine/core-modules/usage-limit/types/stock-counter.type';
+import { buildStockScopeKey } from 'src/engine/core-modules/usage-limit/utils/build-stock-scope-key.util';
+import { buildStockWarmedEntries } from 'src/engine/core-modules/usage-limit/utils/build-stock-warmed-entries.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';
+
+const TTL = 1_000;
+
+const buildCounter = (overrides: Partial<StockCounter> = {}): StockCounter => ({
+ key: 'stock:bytes',
+ isDefault: false,
+ limitValue: 1_000,
+ meter: 'bytes',
+ resourceType: UsageResourceType.STORAGE,
+ operationType: UsageOperationType.STORAGE_FILE,
+ spenderType: 'workspace',
+ spenderId: null,
+ ...overrides,
+});
+
+describe('buildStockWarmedEntries', () => {
+ it('warms a counter to what the limit leaves over what is held', () => {
+ const counter = buildCounter();
+
+ expect(
+ buildStockWarmedEntries({
+ coldCounters: [counter],
+ usedByScope: new Map([
+ [buildStockScopeKey(counter), { bytes: 400, quantity: 2 }],
+ ]),
+ ttl: TTL,
+ }),
+ ).toEqual([{ key: 'stock:bytes', value: 600, ttl: TTL }]);
+ });
+
+ it('reads each counter against its own meter', () => {
+ const counter = buildCounter({
+ key: 'stock:quantity',
+ meter: 'quantity',
+ limitValue: 5,
+ });
+
+ expect(
+ buildStockWarmedEntries({
+ coldCounters: [counter],
+ usedByScope: new Map([
+ [buildStockScopeKey(counter), { bytes: 400, quantity: 2 }],
+ ]),
+ ttl: TTL,
+ }),
+ ).toEqual([{ key: 'stock:quantity', value: 3, ttl: TTL }]);
+ });
+
+ it('warms a lowered limit into the red rather than clamping it', () => {
+ const counter = buildCounter({ limitValue: 500 });
+
+ expect(
+ buildStockWarmedEntries({
+ coldCounters: [counter],
+ usedByScope: new Map([
+ [buildStockScopeKey(counter), { bytes: 900, quantity: 4 }],
+ ]),
+ ttl: TTL,
+ }),
+ ).toEqual([{ key: 'stock:bytes', value: -400, ttl: TTL }]);
+ });
+
+ it('skips a counter whose scope was never counted', () => {
+ expect(
+ buildStockWarmedEntries({
+ coldCounters: [buildCounter()],
+ usedByScope: new Map(),
+ ttl: TTL,
+ }),
+ ).toEqual([]);
+ });
+
+ it('warms each spender from its own scope', () => {
+ const workspaceCounter = buildCounter();
+ const applicationCounter = buildCounter({
+ key: 'stock:application:bytes',
+ spenderType: 'application',
+ spenderId: 'application-1',
+ limitValue: 800,
+ });
+
+ expect(
+ buildStockWarmedEntries({
+ coldCounters: [workspaceCounter, applicationCounter],
+ usedByScope: new Map([
+ [buildStockScopeKey(workspaceCounter), { bytes: 400, quantity: 2 }],
+ [buildStockScopeKey(applicationCounter), { bytes: 100, quantity: 1 }],
+ ]),
+ ttl: TTL,
+ }),
+ ).toEqual([
+ { key: 'stock:bytes', value: 600, ttl: TTL },
+ { key: 'stock:application:bytes', value: 700, ttl: TTL },
+ ]);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-exhausted-stock-counter.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-exhausted-stock-counter.util.spec.ts
new file mode 100644
index 00000000000..e527a380b14
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-exhausted-stock-counter.util.spec.ts
@@ -0,0 +1,86 @@
+import { type StockCounter } from 'src/engine/core-modules/usage-limit/types/stock-counter.type';
+import { findExhaustedStockCounter } from 'src/engine/core-modules/usage-limit/utils/find-exhausted-stock-counter.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';
+
+const buildCounter = (overrides: Partial<StockCounter> = {}): StockCounter => ({
+ key: 'stock:bytes',
+ isDefault: false,
+ limitValue: 1_000,
+ meter: 'bytes',
+ resourceType: UsageResourceType.STORAGE,
+ operationType: UsageOperationType.STORAGE_FILE,
+ spenderType: 'workspace',
+ spenderId: null,
+ ...overrides,
+});
+
+describe('findExhaustedStockCounter', () => {
+ it('admits a cost that exactly consumes the remainder', () => {
+ expect(
+ findExhaustedStockCounter({
+ counters: [buildCounter()],
+ remainings: [250],
+ cost: { bytes: 250 },
+ }),
+ ).toBeNull();
+ });
+
+ it('reports the counter a cost overruns, with what was left', () => {
+ const counter = buildCounter();
+
+ expect(
+ findExhaustedStockCounter({
+ counters: [counter],
+ remainings: [250],
+ cost: { bytes: 251 },
+ }),
+ ).toEqual({ counter, remaining: 250 });
+ });
+
+ it('admits a counter the cost does not touch', () => {
+ expect(
+ findExhaustedStockCounter({
+ counters: [buildCounter({ meter: 'quantity' })],
+ remainings: [0],
+ cost: { bytes: 400 },
+ }),
+ ).toBeNull();
+ });
+
+ it('admits a counter that could not be read', () => {
+ expect(
+ findExhaustedStockCounter({
+ counters: [buildCounter()],
+ remainings: [null],
+ cost: { bytes: 400 },
+ }),
+ ).toBeNull();
+ });
+
+ it('refuses on a counter already in the red', () => {
+ expect(
+ findExhaustedStockCounter({
+ counters: [buildCounter()],
+ remainings: [-10],
+ cost: { bytes: 1 },
+ }),
+ ).toMatchObject({ remaining: -10 });
+ });
+
+ it('keeps looking past a counter the cost fits in', () => {
+ const quantityCounter = buildCounter({
+ key: 'stock:quantity',
+ meter: 'quantity',
+ limitValue: 5,
+ });
+
+ expect(
+ findExhaustedStockCounter({
+ counters: [buildCounter(), quantityCounter],
+ remainings: [500, 0],
+ cost: { bytes: 400, quantity: 1 },
+ }),
+ ).toEqual({ counter: quantityCounter, remaining: 0 });
+ });
+});
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 e4076d305ce..d9f73b75729 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
@@ -117,6 +117,32 @@ describe('usageLimitToRestApiExceptionHandler', () => {
);
});
+ it('answers 409 without retry headers when a stock limit is exhausted', () => {
+ const error = catchThrown(
+ buildExhaustedScope({
+ resourceType: UsageResourceType.STORAGE,
+ limitKind: 'stock',
+ operationType: UsageOperationType.STORAGE_FILE,
+ periodCount: 1,
+ periodUnit: 'lifetime',
+ }),
+ {
+ message: 'Storage limit reached for this workspace',
+ code: UsageLimitExceptionCode.STOCK_EXHAUSTED,
+ },
+ );
+
+ expect(error.getStatus()).toBe(HttpStatus.CONFLICT);
+ expect(error.getResponseBody()).toEqual(
+ expect.objectContaining({
+ statusCode: HttpStatus.CONFLICT,
+ error: 'QUOTA_EXHAUSTED',
+ limitKind: 'stock',
+ }),
+ );
+ expect(error.getResponseHeaders()).toEqual({});
+ });
+
it('answers 402 without retry headers when the credit allowance is exhausted', () => {
const error = catchThrown(
buildExhaustedScope({
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 e9aad332040..50af0361c3c 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
@@ -1,8 +1,8 @@
-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 CreateUsageLimitInput } from 'src/engine/core-modules/usage-limit/dtos/create-usage-limit.input';
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';
+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';
const validSpeedLimit: CreateUsageLimitInput = {
resourceType: UsageResourceType.API,
@@ -28,6 +28,25 @@ const validQuotaLimit: CreateUsageLimitInput = {
limitValue: 1_000_000,
};
+const validStockLimit: CreateUsageLimitInput = {
+ resourceType: UsageResourceType.STORAGE,
+ operationType: UsageOperationType.STORAGE_FILE,
+ spenderType: 'workspace',
+ spenderId: null,
+ limitKind: 'stock',
+ periodCount: 1,
+ periodUnit: 'lifetime',
+ meter: 'bytes',
+ limitValue: 10_737_418_240,
+};
+
+const rejects = (input: CreateUsageLimitInput) =>
+ expect(() => validateUsageLimitAgainstDefinition(input)).toThrow(
+ expect.objectContaining({
+ code: UsageLimitExceptionCode.LIMIT_INVALID,
+ }),
+ );
+
describe('validateUsageLimitAgainstDefinition', () => {
it('accepts a limit the definition allows', () => {
expect(() =>
@@ -35,98 +54,6 @@ describe('validateUsageLimitAgainstDefinition', () => {
).not.toThrow();
});
- it('rejects a resource that has no definition', () => {
- expect(() =>
- validateUsageLimitAgainstDefinition({
- ...validSpeedLimit,
- resourceType: UsageResourceType.STORAGE,
- }),
- ).toThrow(
- expect.objectContaining({
- code: UsageLimitExceptionCode.LIMIT_INVALID,
- }),
- );
- });
-
- it('rejects an operation the resource does not meter', () => {
- expect(() =>
- validateUsageLimitAgainstDefinition({
- ...validSpeedLimit,
- operationType: UsageOperationType.EMAIL_SEND,
- }),
- ).toThrow(
- expect.objectContaining({
- code: UsageLimitExceptionCode.LIMIT_INVALID,
- }),
- );
- });
-
- it('refuses to rate-limit a human, because the definition does not allow that scope', () => {
- expect(() =>
- validateUsageLimitAgainstDefinition({
- ...validSpeedLimit,
- spenderType: 'userWorkspace',
- }),
- ).toThrow(
- expect.objectContaining({
- 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 limit metered on credits', () => {
- expect(() =>
- validateUsageLimitAgainstDefinition({
- ...validSpeedLimit,
- meter: 'creditsUsedMicro',
- }),
- ).toThrow(
- expect.objectContaining({
- code: UsageLimitExceptionCode.LIMIT_INVALID,
- }),
- );
- });
-
- it('rejects a workspace limit, because the definition does not allow that scope', () => {
- expect(() =>
- validateUsageLimitAgainstDefinition({
- ...validSpeedLimit,
- spenderType: 'workspace',
- spenderId: null,
- }),
- ).toThrow(
- expect.objectContaining({
- code: UsageLimitExceptionCode.LIMIT_INVALID,
- }),
- );
- });
-
- it('rejects a spender id that is not a uuid', () => {
- expect(() =>
- validateUsageLimitAgainstDefinition({
- ...validSpeedLimit,
- spenderId: 'key-1',
- }),
- ).toThrow(
- expect.objectContaining({
- code: UsageLimitExceptionCode.LIMIT_INVALID,
- }),
- );
- });
-
it('accepts a limit targeting every spender of a type', () => {
expect(() =>
validateUsageLimitAgainstDefinition({
@@ -136,9 +63,12 @@ describe('validateUsageLimitAgainstDefinition', () => {
).not.toThrow();
});
- it('accepts a monthly credit quota on the workspace', () => {
+ it('accepts a quota covering every operation of the resource', () => {
expect(() =>
- validateUsageLimitAgainstDefinition(validQuotaLimit),
+ validateUsageLimitAgainstDefinition({
+ ...validQuotaLimit,
+ operationType: UsageOperationType.ALL,
+ }),
).not.toThrow();
});
@@ -152,110 +82,54 @@ describe('validateUsageLimitAgainstDefinition', () => {
).not.toThrow();
});
- it('rejects a quota scoped to an agent, which spends through its workflow', () => {
- expect(() =>
- validateUsageLimitAgainstDefinition({
- ...validQuotaLimit,
- spenderType: 'agent',
- spenderId: '20202020-1c25-4d02-bf25-6aeccf7ea419',
- }),
- ).toThrow();
+ it('rejects a resource that has no definition', () => {
+ rejects({ ...validSpeedLimit, resourceType: UsageResourceType.WORKFLOW });
});
- it('accepts a quota covering every operation of the resource', () => {
- expect(() =>
- validateUsageLimitAgainstDefinition({
- ...validQuotaLimit,
- operationType: UsageOperationType.ALL,
- }),
- ).not.toThrow();
+ it('rejects an operation the resource does not meter', () => {
+ rejects({
+ ...validSpeedLimit,
+ operationType: UsageOperationType.EMAIL_SEND,
+ });
});
- it('rejects a quota on a rolling window', () => {
- expect(() =>
- validateUsageLimitAgainstDefinition({
- ...validQuotaLimit,
- periodUnit: 'second',
- }),
- ).toThrow(
- expect.objectContaining({
- code: UsageLimitExceptionCode.LIMIT_INVALID,
- }),
- );
+ it('refuses to rate-limit a human, because the definition does not allow that scope', () => {
+ rejects({ ...validSpeedLimit, spenderType: 'userWorkspace' });
});
- it('rejects a quota with a burst value', () => {
- expect(() =>
- validateUsageLimitAgainstDefinition({
- ...validQuotaLimit,
- burstValue: 200,
- }),
- ).toThrow(
- expect.objectContaining({
- code: UsageLimitExceptionCode.LIMIT_INVALID,
- }),
- );
+ it('rejects a workspace limit, because the definition does not allow that scope', () => {
+ rejects({ ...validSpeedLimit, spenderType: 'workspace', spenderId: null });
});
- it('accepts an absolute weekly quota', () => {
- expect(() =>
- validateUsageLimitAgainstDefinition({
- ...validQuotaLimit,
- periodUnit: 'week',
- limitValue: 5_000_000,
- }),
- ).not.toThrow();
+ it('rejects a spender id that is not a uuid', () => {
+ rejects({ ...validSpeedLimit, spenderId: 'key-1' });
});
- it('rejects a quota spanning several periods', () => {
- expect(() =>
- validateUsageLimitAgainstDefinition({
- ...validQuotaLimit,
- periodUnit: 'week',
- periodCount: 2,
- }),
- ).toThrow(
- expect.objectContaining({
- code: UsageLimitExceptionCode.LIMIT_INVALID,
- }),
- );
+ it('rejects a quota scoped to an agent, which spends through its workflow', () => {
+ rejects({
+ ...validQuotaLimit,
+ spenderType: 'agent',
+ spenderId: '20202020-1c25-4d02-bf25-6aeccf7ea419',
+ });
});
- it('accepts a token quota on one operation', () => {
- expect(() =>
- validateUsageLimitAgainstDefinition({
- ...validQuotaLimit,
- meter: 'quantity',
- limitValue: 1_000_000,
- }),
- ).not.toThrow();
+ it('rejects a quota on a spender type the resource does not allow', () => {
+ rejects({ ...validQuotaLimit, spenderType: 'workflow' });
});
- 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 metered on bytes, which the resource does not track', () => {
+ rejects({ ...validQuotaLimit, meter: 'bytes' });
});
- 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,
- }),
- );
+ it('rejects a stock scoped below the workspace', () => {
+ rejects({
+ ...validStockLimit,
+ spenderType: 'userWorkspace',
+ spenderId: '20202020-1c25-4d02-bf25-6aeccf7ea419',
+ });
+ });
+
+ it('rejects a stock metered on credits, which the resource does not track', () => {
+ rejects({ ...validStockLimit, meter: 'creditsUsedMicro' });
});
});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/validate-usage-limit-against-kind-rule.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/validate-usage-limit-against-kind-rule.util.spec.ts
new file mode 100644
index 00000000000..2b4609fda61
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/validate-usage-limit-against-kind-rule.util.spec.ts
@@ -0,0 +1,193 @@
+import { type CreateUsageLimitInput } from 'src/engine/core-modules/usage-limit/dtos/create-usage-limit.input';
+import { UsageLimitExceptionCode } from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';
+import { validateUsageLimitAgainstKindRule } from 'src/engine/core-modules/usage-limit/utils/validate-usage-limit-against-kind-rule.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';
+
+const validSpeedLimit: CreateUsageLimitInput = {
+ resourceType: UsageResourceType.API,
+ operationType: UsageOperationType.API_REQUEST,
+ spenderType: 'apiKey',
+ spenderId: '20202020-1c25-4d02-bf25-6aeccf7ea419',
+ limitKind: 'speed',
+ periodCount: 60,
+ periodUnit: 'second',
+ meter: 'quantity',
+ limitValue: 100,
+};
+
+const validQuotaLimit: CreateUsageLimitInput = {
+ resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ spenderType: 'workspace',
+ spenderId: null,
+ limitKind: 'quota',
+ periodCount: 1,
+ periodUnit: 'month',
+ meter: 'creditsUsedMicro',
+ limitValue: 1_000_000,
+};
+
+const validStockLimit: CreateUsageLimitInput = {
+ resourceType: UsageResourceType.STORAGE,
+ operationType: UsageOperationType.STORAGE_FILE,
+ spenderType: 'workspace',
+ spenderId: null,
+ limitKind: 'stock',
+ periodCount: 1,
+ periodUnit: 'lifetime',
+ meter: 'bytes',
+ limitValue: 10_737_418_240,
+};
+
+const rejects = (input: CreateUsageLimitInput) =>
+ expect(() => validateUsageLimitAgainstKindRule(input)).toThrow(
+ expect.objectContaining({
+ code: UsageLimitExceptionCode.LIMIT_INVALID,
+ }),
+ );
+
+describe('validateUsageLimitAgainstKindRule', () => {
+ describe('speed', () => {
+ it('accepts a rolling window over several seconds', () => {
+ expect(() =>
+ validateUsageLimitAgainstKindRule(validSpeedLimit),
+ ).not.toThrow();
+ });
+
+ it('accepts a burst value', () => {
+ expect(() =>
+ validateUsageLimitAgainstKindRule({
+ ...validSpeedLimit,
+ burstValue: 200,
+ }),
+ ).not.toThrow();
+ });
+
+ it('rejects a speed limit without a rolling window', () => {
+ rejects({ ...validSpeedLimit, periodUnit: 'month' });
+ });
+
+ it('rejects a speed limit metered on credits', () => {
+ rejects({ ...validSpeedLimit, meter: 'creditsUsedMicro' });
+ });
+ });
+
+ describe('quota', () => {
+ it('accepts a monthly credit quota', () => {
+ expect(() =>
+ validateUsageLimitAgainstKindRule(validQuotaLimit),
+ ).not.toThrow();
+ });
+
+ it('accepts a weekly quota', () => {
+ expect(() =>
+ validateUsageLimitAgainstKindRule({
+ ...validQuotaLimit,
+ periodUnit: 'week',
+ }),
+ ).not.toThrow();
+ });
+
+ it('accepts a credit quota covering every operation', () => {
+ expect(() =>
+ validateUsageLimitAgainstKindRule({
+ ...validQuotaLimit,
+ operationType: UsageOperationType.ALL,
+ }),
+ ).not.toThrow();
+ });
+
+ it('accepts a quantity quota on one operation', () => {
+ expect(() =>
+ validateUsageLimitAgainstKindRule({
+ ...validQuotaLimit,
+ meter: 'quantity',
+ }),
+ ).not.toThrow();
+ });
+
+ it('rejects a quota on a rolling window', () => {
+ rejects({ ...validQuotaLimit, periodUnit: 'second' });
+ });
+
+ it('rejects a quota that never resets', () => {
+ rejects({ ...validQuotaLimit, periodUnit: 'lifetime' });
+ });
+
+ it('rejects a quota spanning several periods', () => {
+ rejects({ ...validQuotaLimit, periodCount: 2 });
+ });
+
+ it('rejects a quota with a burst value', () => {
+ rejects({ ...validQuotaLimit, burstValue: 200 });
+ });
+
+ it('rejects a quota metered on bytes', () => {
+ rejects({ ...validQuotaLimit, meter: 'bytes' });
+ });
+
+ it('rejects a quantity quota covering every operation', () => {
+ rejects({
+ ...validQuotaLimit,
+ operationType: UsageOperationType.ALL,
+ meter: 'quantity',
+ });
+ });
+ });
+
+ describe('stock', () => {
+ it('accepts a workspace-wide stock on the operation that fills it', () => {
+ expect(() =>
+ validateUsageLimitAgainstKindRule(validStockLimit),
+ ).not.toThrow();
+ });
+
+ it('accepts a stock metered on a file count', () => {
+ expect(() =>
+ validateUsageLimitAgainstKindRule({
+ ...validStockLimit,
+ meter: 'quantity',
+ }),
+ ).not.toThrow();
+ });
+
+ it('accepts a stock capping one application', () => {
+ expect(() =>
+ validateUsageLimitAgainstKindRule({
+ ...validStockLimit,
+ spenderType: 'application',
+ spenderId: '20202020-1c25-4d02-bf25-6aeccf7ea419',
+ }),
+ ).not.toThrow();
+ });
+
+ it('rejects a stock spanning every operation', () => {
+ rejects({ ...validStockLimit, operationType: UsageOperationType.ALL });
+ });
+
+ it('rejects a stock that resets', () => {
+ rejects({ ...validStockLimit, periodUnit: 'month' });
+ });
+
+ it('rejects a stock covering several periods', () => {
+ rejects({ ...validStockLimit, periodCount: 3 });
+ });
+
+ it('rejects a stock holding a burst value', () => {
+ rejects({ ...validStockLimit, burstValue: 10 });
+ });
+
+ it('rejects a stock metered on credits', () => {
+ rejects({ ...validStockLimit, meter: 'creditsUsedMicro' });
+ });
+
+ it('rejects an application stock that names no application', () => {
+ rejects({
+ ...validStockLimit,
+ spenderType: 'application',
+ spenderId: null,
+ });
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-limit-quota-counter.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-limit-quota-counter.util.ts
index 106eca34d7c..5eb968409d2 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-limit-quota-counter.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-limit-quota-counter.util.ts
@@ -1,4 +1,4 @@
-import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
+import { type FlatQuotaLimit } from 'src/engine/core-modules/usage-limit/types/flat-quota-limit.type';
import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
import { type UsagePeriod } from 'src/engine/core-modules/usage-limit/types/usage-period.type';
import { buildQuotaCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-quota-counter-key.util';
@@ -11,7 +11,7 @@ export const buildLimitQuotaCounter = ({
}: {
workspaceId: string;
limit: Omit<
- FlatUsageLimit,
+ FlatQuotaLimit,
'id' | 'limitKind' | 'periodCount' | 'burstValue'
>;
period: UsagePeriod;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-counters.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-counters.util.ts
index b56e5d488dd..38a9c9c6330 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-counters.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-counters.util.ts
@@ -1,7 +1,7 @@
import { isDefined } from 'twenty-shared/utils';
import { SPENDER_TYPE_SPECIFICITY } from 'src/engine/core-modules/usage-limit/constants/spender-type-specificity.constant';
-import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
+import { type FlatQuotaLimit } from 'src/engine/core-modules/usage-limit/types/flat-quota-limit.type';
import { type PeriodUnit } from 'src/engine/core-modules/usage-limit/types/period-unit.type';
import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
import { buildLimitQuotaCounter } from 'src/engine/core-modules/usage-limit/utils/build-limit-quota-counter.util';
@@ -23,7 +23,7 @@ export const buildQuotaCounters = ({
operationType,
periodByUnit,
}: {
- limits: FlatUsageLimit[];
+ limits: FlatQuotaLimit[];
usageSpenders: UsageSpenders;
workspaceId: string;
operationType: UsageOperationType;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-definitions.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-definitions.util.ts
index 633746dee18..4566e9eafe0 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-definitions.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-definitions.util.ts
@@ -1,20 +1,22 @@
import { isDefined } from 'twenty-shared/utils';
-import { USAGE_LIMIT_DEFINITIONS } from 'src/engine/core-modules/usage-limit/constants/usage-limit-definitions.constant';
import { type UsageQuotaDefinitionDTO } from 'src/engine/core-modules/usage-limit/dtos/usage-quota-definition.dto';
+import { findUsageLimitDefinition } from 'src/engine/core-modules/usage-limit/utils/find-usage-limit-definition.util';
import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
export const buildQuotaDefinitions = (): UsageQuotaDefinitionDTO[] =>
Object.values(UsageResourceType).flatMap((resourceType) => {
- const { quota } = USAGE_LIMIT_DEFINITIONS[resourceType];
+ const limitKind = 'quota';
+ const definition = findUsageLimitDefinition({ resourceType, limitKind });
- return isDefined(quota)
+ return isDefined(definition)
? [
{
resourceType,
- allowedOperationTypes: quota.allowedOperationTypes,
- allowedSpenderTypes: quota.allowedSpenderTypes,
- allowedMeters: quota.allowedMeters,
+ limitKind,
+ allowedOperationTypes: definition.allowedOperationTypes,
+ allowedSpenderTypes: definition.allowedSpenderTypes,
+ allowedMeters: definition.allowedMeters,
},
]
: [];
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-counter-key.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-counter-key.util.ts
new file mode 100644
index 00000000000..12f5e627063
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-counter-key.util.ts
@@ -0,0 +1,25 @@
+import { isNonEmptyString } from '@sniptt/guards';
+
+import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
+import { type StockMeter } from 'src/engine/core-modules/usage-limit/types/stock-meter.type';
+import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { type UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+
+const ABSENT = '-';
+
+export const buildStockCounterKey = ({
+ workspaceId,
+ resourceType,
+ operationType,
+ spenderType,
+ spenderId,
+ meter,
+}: {
+ workspaceId: string;
+ resourceType: UsageResourceType;
+ operationType: UsageOperationType;
+ spenderType: SpenderType;
+ spenderId?: string | null;
+ meter: StockMeter;
+}): string =>
+ `{${workspaceId}}:stock:${resourceType}:${operationType}:${spenderType}:${isNonEmptyString(spenderId) ? spenderId : ABSENT}:${meter}`;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-counter.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-counter.util.ts
new file mode 100644
index 00000000000..cff7d5586f5
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-counter.util.ts
@@ -0,0 +1,28 @@
+import { type FlatStockLimit } from 'src/engine/core-modules/usage-limit/types/flat-stock-limit.type';
+import { type StockCounter } from 'src/engine/core-modules/usage-limit/types/stock-counter.type';
+import { buildStockCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-stock-counter-key.util';
+import { normalizeSpenderId } from 'src/engine/core-modules/usage-limit/utils/normalize-spender-id.util';
+
+export const buildStockCounter = ({
+ workspaceId,
+ limit,
+}: {
+ workspaceId: string;
+ limit: FlatStockLimit;
+}): StockCounter => ({
+ key: buildStockCounterKey({
+ workspaceId,
+ resourceType: limit.resourceType,
+ operationType: limit.operationType,
+ spenderType: limit.spenderType,
+ spenderId: limit.spenderId,
+ meter: limit.meter,
+ }),
+ isDefault: false,
+ limitValue: limit.limitValue,
+ meter: limit.meter,
+ resourceType: limit.resourceType,
+ operationType: limit.operationType,
+ spenderType: limit.spenderType,
+ spenderId: normalizeSpenderId(limit.spenderId),
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-counters.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-counters.util.ts
new file mode 100644
index 00000000000..834f7c83436
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-counters.util.ts
@@ -0,0 +1,64 @@
+import { type FlatStockLimit } from 'src/engine/core-modules/usage-limit/types/flat-stock-limit.type';
+import { type StockCounter } from 'src/engine/core-modules/usage-limit/types/stock-counter.type';
+import { type StockLimitDefault } from 'src/engine/core-modules/usage-limit/types/stock-limit-default.type';
+import { type StockResourceType } from 'src/engine/core-modules/usage-limit/types/stock-resource-type.type';
+import { buildSpendersFromUsageSpenders } from 'src/engine/core-modules/usage-limit/utils/build-spenders-from-usage-spenders.util';
+import { buildStockCounter } from 'src/engine/core-modules/usage-limit/utils/build-stock-counter.util';
+import { buildStockDefaultCounter } from 'src/engine/core-modules/usage-limit/utils/build-stock-default-counter.util';
+import { findStockLimitsForSpenders } from 'src/engine/core-modules/usage-limit/utils/find-stock-limits-for-spenders.util';
+import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { type UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';
+
+export const buildStockCounters = ({
+ workspaceId,
+ resourceType,
+ operationType,
+ spenders,
+ limits,
+ stockLimitDefaults,
+}: {
+ workspaceId: string;
+ resourceType: StockResourceType;
+ operationType: UsageOperationType;
+ spenders: UsageSpenders;
+ limits: FlatStockLimit[];
+ stockLimitDefaults: StockLimitDefault[];
+}): StockCounter[] => {
+ const limitCounters = findStockLimitsForSpenders({
+ limits,
+ usageSpenders: spenders,
+ operationType,
+ }).map((limit) => buildStockCounter({ workspaceId, limit }));
+
+ const spenderTypes = new Set(
+ buildSpendersFromUsageSpenders(spenders).map(
+ (spender) => spender.spenderType,
+ ),
+ );
+
+ const defaultCounters = stockLimitDefaults
+ .filter(
+ (stockLimitDefault) =>
+ spenderTypes.has(stockLimitDefault.spenderType) &&
+ !(
+ stockLimitDefault.isOverridable &&
+ limitCounters.some(
+ (counter) =>
+ counter.resourceType === resourceType &&
+ counter.spenderType === stockLimitDefault.spenderType &&
+ counter.spenderId === null &&
+ counter.meter === stockLimitDefault.meter,
+ )
+ ),
+ )
+ .map((stockLimitDefault) =>
+ buildStockDefaultCounter({
+ workspaceId,
+ resourceType,
+ operationType,
+ stockLimitDefault,
+ }),
+ );
+
+ return [...limitCounters, ...defaultCounters];
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-default-counter-key.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-default-counter-key.util.ts
new file mode 100644
index 00000000000..180b3cede75
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-default-counter-key.util.ts
@@ -0,0 +1,22 @@
+import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
+import { type StockMeter } from 'src/engine/core-modules/usage-limit/types/stock-meter.type';
+import { buildStockCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-stock-counter-key.util';
+import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { type UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+
+export const buildStockDefaultCounterKey = ({
+ workspaceId,
+ resourceType,
+ operationType,
+ spenderType,
+ meter,
+ limitValue,
+}: {
+ workspaceId: string;
+ resourceType: UsageResourceType;
+ operationType: UsageOperationType;
+ spenderType: SpenderType;
+ meter: StockMeter;
+ limitValue: number;
+}): string =>
+ `${buildStockCounterKey({ workspaceId, resourceType, operationType, spenderType, meter })}:default:${limitValue}`;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-default-counter.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-default-counter.util.ts
new file mode 100644
index 00000000000..c263e7464e0
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-default-counter.util.ts
@@ -0,0 +1,33 @@
+import { type StockCounter } from 'src/engine/core-modules/usage-limit/types/stock-counter.type';
+import { type StockLimitDefault } from 'src/engine/core-modules/usage-limit/types/stock-limit-default.type';
+import { type StockResourceType } from 'src/engine/core-modules/usage-limit/types/stock-resource-type.type';
+import { buildStockDefaultCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-stock-default-counter-key.util';
+import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+
+export const buildStockDefaultCounter = ({
+ workspaceId,
+ resourceType,
+ operationType,
+ stockLimitDefault,
+}: {
+ workspaceId: string;
+ resourceType: StockResourceType;
+ operationType: UsageOperationType;
+ stockLimitDefault: StockLimitDefault;
+}): StockCounter => ({
+ key: buildStockDefaultCounterKey({
+ workspaceId,
+ resourceType,
+ operationType,
+ spenderType: stockLimitDefault.spenderType,
+ meter: stockLimitDefault.meter,
+ limitValue: stockLimitDefault.limitValue,
+ }),
+ isDefault: true,
+ limitValue: stockLimitDefault.limitValue,
+ meter: stockLimitDefault.meter,
+ resourceType,
+ operationType,
+ spenderType: stockLimitDefault.spenderType,
+ spenderId: null,
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-exhausted-scope.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-exhausted-scope.util.ts
new file mode 100644
index 00000000000..c35649870ff
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-exhausted-scope.util.ts
@@ -0,0 +1,23 @@
+import { type ExhaustedScope } from 'src/engine/core-modules/usage-limit/types/exhausted-scope.type';
+import { type StockCounter } from 'src/engine/core-modules/usage-limit/types/stock-counter.type';
+
+export const buildStockExhaustedScope = ({
+ counter,
+ remaining,
+}: {
+ counter: StockCounter;
+ remaining: number;
+}): ExhaustedScope => ({
+ resourceType: counter.resourceType,
+ limitKind: 'stock',
+ exhaustedKind: 'limit',
+ spenderType: counter.spenderType,
+ spenderId: counter.spenderId,
+ operationType: counter.operationType,
+ limitValue: counter.limitValue,
+ remaining,
+ periodCount: null,
+ periodUnit: null,
+ retryAfterMs: 0,
+ isDefault: counter.isDefault,
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-scope-key.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-scope-key.util.ts
new file mode 100644
index 00000000000..0e16b4c3e70
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-scope-key.util.ts
@@ -0,0 +1,4 @@
+import { type StockCounter } from 'src/engine/core-modules/usage-limit/types/stock-counter.type';
+
+export const buildStockScopeKey = (counter: StockCounter): string =>
+ `${counter.resourceType}:${counter.spenderType}:${counter.spenderId ?? '-'}`;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-warm-lock-key.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-warm-lock-key.util.ts
new file mode 100644
index 00000000000..b192b04b147
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-warm-lock-key.util.ts
@@ -0,0 +1,2 @@
+export const buildStockWarmLockKey = (workspaceId: string): string =>
+ `usage-stock-warm:${workspaceId}`;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-warmed-entries.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-warmed-entries.util.ts
new file mode 100644
index 00000000000..052b1e306b2
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-warmed-entries.util.ts
@@ -0,0 +1,22 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type StockMeter } from 'src/engine/core-modules/usage-limit/types/stock-meter.type';
+import { type StockCounter } from 'src/engine/core-modules/usage-limit/types/stock-counter.type';
+import { buildStockScopeKey } from 'src/engine/core-modules/usage-limit/utils/build-stock-scope-key.util';
+
+export const buildStockWarmedEntries = ({
+ coldCounters,
+ usedByScope,
+ ttl,
+}: {
+ coldCounters: StockCounter[];
+ usedByScope: Map<string, Record<StockMeter, number>>;
+ ttl: number;
+}): { key: string; value: number; ttl: number }[] =>
+ coldCounters.flatMap((counter) => {
+ const used = usedByScope.get(buildStockScopeKey(counter))?.[counter.meter];
+
+ return isDefined(used)
+ ? [{ key: counter.key, value: counter.limitValue - used, ttl }]
+ : [];
+ });
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-enforceable-limits.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-enforceable-limits.util.ts
index d5abefd4a10..eaa3c2a9ded 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-enforceable-limits.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-enforceable-limits.util.ts
@@ -1,13 +1,13 @@
import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
import { isIntraWorkspaceScoped } from 'src/engine/core-modules/usage-limit/utils/is-intra-workspace-scoped.util';
-export const findEnforceableLimits = ({
+export const findEnforceableLimits = <TLimit extends FlatUsageLimit>({
limits,
isIntraWorkspaceLimitEntitled,
}: {
- limits: FlatUsageLimit[];
+ limits: TLimit[];
isIntraWorkspaceLimitEntitled: boolean;
-}): FlatUsageLimit[] =>
+}): TLimit[] =>
isIntraWorkspaceLimitEntitled
? limits
: limits.filter((limit) => !isIntraWorkspaceScoped(limit.spenderType));
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-exhausted-stock-counter.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-exhausted-stock-counter.util.ts
new file mode 100644
index 00000000000..05ba9fe745d
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-exhausted-stock-counter.util.ts
@@ -0,0 +1,24 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type StockCost } from 'src/engine/core-modules/usage-limit/types/stock-cost.type';
+import { type StockCounter } from 'src/engine/core-modules/usage-limit/types/stock-counter.type';
+
+export const findExhaustedStockCounter = ({
+ counters,
+ remainings,
+ cost,
+}: {
+ counters: StockCounter[];
+ remainings: (number | null)[];
+ cost: StockCost;
+}): { counter: StockCounter; remaining: number } | null => {
+ for (const [index, counter] of counters.entries()) {
+ const remaining = remainings[index];
+
+ if (isDefined(remaining) && remaining < (cost[counter.meter] ?? 0)) {
+ return { counter, remaining };
+ }
+ }
+
+ return null;
+};
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
index 2070c40e744..71a7952cc23 100644
--- 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
@@ -2,15 +2,15 @@ import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/f
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 = ({
+export const findLimitsForSpender = <TLimit extends FlatUsageLimit>({
limits,
spender,
operationType,
}: {
- limits: FlatUsageLimit[];
+ limits: TLimit[];
spender: Spender;
operationType: UsageOperationType;
-}): FlatUsageLimit[] =>
+}): TLimit[] =>
limits.filter(
(limit) =>
limit.spenderType === spender.spenderType &&
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-stock-limits-for-spenders.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-stock-limits-for-spenders.util.ts
new file mode 100644
index 00000000000..9e9a1e1a887
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-stock-limits-for-spenders.util.ts
@@ -0,0 +1,21 @@
+import { type FlatStockLimit } from 'src/engine/core-modules/usage-limit/types/flat-stock-limit.type';
+import { buildSpendersFromUsageSpenders } from 'src/engine/core-modules/usage-limit/utils/build-spenders-from-usage-spenders.util';
+import { findLimitsForSpender } from 'src/engine/core-modules/usage-limit/utils/find-limits-for-spender.util';
+import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { type UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';
+
+export const findStockLimitsForSpenders = ({
+ limits,
+ usageSpenders,
+ operationType,
+}: {
+ limits: FlatStockLimit[];
+ usageSpenders: UsageSpenders;
+ operationType: UsageOperationType;
+}): FlatStockLimit[] => {
+ const matched = buildSpendersFromUsageSpenders(usageSpenders).flatMap(
+ (spender) => findLimitsForSpender({ limits, spender, operationType }),
+ );
+
+ return [...new Map(matched.map((limit) => [limit.id, limit])).values()];
+};
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 6962a15c799..eedede1b79e 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
@@ -3,6 +3,11 @@ import { type LimitKind } from 'src/engine/core-modules/usage-limit/types/limit-
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';
+const definitionsByResourceType: Record<
+ UsageResourceType,
+ UsageLimitDefinitions
+> = USAGE_LIMIT_DEFINITIONS;
+
export const findUsageLimitDefinition = <TLimitKind extends LimitKind>({
resourceType,
limitKind,
@@ -10,4 +15,4 @@ export const findUsageLimitDefinition = <TLimitKind extends LimitKind>({
resourceType: UsageResourceType;
limitKind: TLimitKind;
}): UsageLimitDefinitions[TLimitKind] =>
- USAGE_LIMIT_DEFINITIONS[resourceType][limitKind];
+ definitionsByResourceType[resourceType][limitKind];
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-usage-limit-error-code.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-usage-limit-error-code.util.ts
index 94ac35bcd2e..e6bd35d5b36 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-usage-limit-error-code.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-usage-limit-error-code.util.ts
@@ -4,6 +4,7 @@ import { UsageLimitExceptionCode } from 'src/engine/core-modules/usage-limit/exc
export const getUsageLimitErrorCode = (
code: UsageLimitExceptionCode,
): ErrorCode =>
- code === UsageLimitExceptionCode.QUOTA_EXHAUSTED
+ code === UsageLimitExceptionCode.QUOTA_EXHAUSTED ||
+ code === UsageLimitExceptionCode.STOCK_EXHAUSTED
? ErrorCode.QUOTA_EXHAUSTED
: ErrorCode.RATE_LIMITED;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-anchored-period-unit.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-anchored-period-unit.util.ts
new file mode 100644
index 00000000000..c553050230d
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-anchored-period-unit.util.ts
@@ -0,0 +1,8 @@
+import { ANCHORED_PERIOD_UNITS } from 'src/engine/core-modules/usage-limit/constants/period-units.constant';
+import { type AnchoredPeriodUnit } from 'src/engine/core-modules/usage-limit/types/anchored-period-unit.type';
+import { type PeriodUnit } from 'src/engine/core-modules/usage-limit/types/period-unit.type';
+
+export const isAnchoredPeriodUnit = (
+ periodUnit: PeriodUnit,
+): periodUnit is AnchoredPeriodUnit =>
+ ANCHORED_PERIOD_UNITS.includes(periodUnit as AnchoredPeriodUnit);
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-quota-limit.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-quota-limit.util.ts
new file mode 100644
index 00000000000..f036cb98527
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-quota-limit.util.ts
@@ -0,0 +1,6 @@
+import { type FlatQuotaLimit } from 'src/engine/core-modules/usage-limit/types/flat-quota-limit.type';
+import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
+import { isQuotaMeter } from 'src/engine/core-modules/usage-limit/utils/is-quota-meter.util';
+
+export const isQuotaLimit = (limit: FlatUsageLimit): limit is FlatQuotaLimit =>
+ limit.limitKind === 'quota' && isQuotaMeter(limit.meter);
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-quota-meter.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-quota-meter.util.ts
new file mode 100644
index 00000000000..38347f3208c
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-quota-meter.util.ts
@@ -0,0 +1,6 @@
+import { QUOTA_METERS } from 'src/engine/core-modules/usage-limit/constants/usage-meters.constant';
+import { type QuotaMeter } from 'src/engine/core-modules/usage-limit/types/quota-meter.type';
+import { type UsageMeter } from 'src/engine/core-modules/usage-limit/types/usage-meter.type';
+
+export const isQuotaMeter = (meter: UsageMeter): meter is QuotaMeter =>
+ QUOTA_METERS.includes(meter as QuotaMeter);
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-stock-limit.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-stock-limit.util.ts
new file mode 100644
index 00000000000..ed59eb8158f
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-stock-limit.util.ts
@@ -0,0 +1,9 @@
+import { type FlatStockLimit } from 'src/engine/core-modules/usage-limit/types/flat-stock-limit.type';
+import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
+import { isStockMeter } from 'src/engine/core-modules/usage-limit/utils/is-stock-meter.util';
+import { isStockResourceType } from 'src/engine/core-modules/usage-limit/utils/is-stock-resource-type.util';
+
+export const isStockLimit = (limit: FlatUsageLimit): limit is FlatStockLimit =>
+ limit.limitKind === 'stock' &&
+ isStockMeter(limit.meter) &&
+ isStockResourceType(limit.resourceType);
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-stock-meter.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-stock-meter.util.ts
new file mode 100644
index 00000000000..7dddd856f68
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-stock-meter.util.ts
@@ -0,0 +1,6 @@
+import { STOCK_METERS } from 'src/engine/core-modules/usage-limit/constants/usage-meters.constant';
+import { type StockMeter } from 'src/engine/core-modules/usage-limit/types/stock-meter.type';
+import { type UsageMeter } from 'src/engine/core-modules/usage-limit/types/usage-meter.type';
+
+export const isStockMeter = (meter: UsageMeter): meter is StockMeter =>
+ STOCK_METERS.includes(meter as StockMeter);
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-stock-resource-type.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-stock-resource-type.util.ts
new file mode 100644
index 00000000000..abc05a63bff
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-stock-resource-type.util.ts
@@ -0,0 +1,8 @@
+import { USAGE_LIMIT_DEFINITIONS } from 'src/engine/core-modules/usage-limit/constants/usage-limit-definitions.constant';
+import { type StockResourceType } from 'src/engine/core-modules/usage-limit/types/stock-resource-type.type';
+import { type UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+
+export const isStockResourceType = (
+ resourceType: UsageResourceType,
+): resourceType is StockResourceType =>
+ 'stock' in USAGE_LIMIT_DEFINITIONS[resourceType];
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 df8f40d5548..79571a43dee 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,18 +8,26 @@ 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';
+const getStatusCode = (
+ exhaustedScope: UsageLimitException['exhaustedScope'],
+): HttpStatus => {
+ if (exhaustedScope?.exhaustedKind === 'allowance') {
+ return HttpStatus.PAYMENT_REQUIRED;
+ }
+
+ if (exhaustedScope?.limitKind === 'stock') {
+ return HttpStatus.CONFLICT;
+ }
+
+ return HttpStatus.TOO_MANY_REQUESTS;
+};
+
export const buildUsageLimitHttpException = (
error: UsageLimitException,
): 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;
+ const statusCode = getStatusCode(exhaustedScope);
if (!isDefined(exhaustedScope)) {
return new HttpException(error.message, statusCode);
@@ -45,9 +53,9 @@ export const buildUsageLimitHttpException = (
periodUnit: exhaustedScope.periodUnit,
retryAfterSeconds,
},
- isAllowanceExhausted
- ? {}
- : buildRateLimitResponseHeaders({ exhaustedScope, retryAfterSeconds }),
+ statusCode === HttpStatus.TOO_MANY_REQUESTS
+ ? buildRateLimitResponseHeaders({ exhaustedScope, retryAfterSeconds })
+ : {},
);
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/validate-usage-limit-against-definition.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/validate-usage-limit-against-definition.util.ts
index eeb9e9af7c8..cfcef70d85b 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
@@ -6,6 +6,7 @@ import {
UsageLimitException,
UsageLimitExceptionCode,
} from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';
+import { type UsageMeter } from 'src/engine/core-modules/usage-limit/types/usage-meter.type';
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';
@@ -48,60 +49,12 @@ export const validateUsageLimitAgainstDefinition = (
);
}
- 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 ('allowedMeters' in definition) {
+ const allowedMeters: readonly UsageMeter[] = definition.allowedMeters;
- if (
- input.meter === 'quantity' &&
- input.operationType === UsageOperationType.ALL
- ) {
+ if (!allowedMeters.includes(input.meter)) {
throw new UsageLimitException(
- 'A quantity quota needs an operation: only credits aggregate across operations',
+ `${input.resourceType} ${input.limitKind} limits cannot be metered on ${input.meter}`,
UsageLimitExceptionCode.LIMIT_INVALID,
);
}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/validate-usage-limit-against-kind-rule.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/validate-usage-limit-against-kind-rule.util.ts
new file mode 100644
index 00000000000..5a985a85c61
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/validate-usage-limit-against-kind-rule.util.ts
@@ -0,0 +1,85 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+
+import { LIMIT_KIND_RULES } from 'src/engine/core-modules/usage-limit/constants/limit-kind-rules.constant';
+import { type CreateUsageLimitInput } from 'src/engine/core-modules/usage-limit/dtos/create-usage-limit.input';
+import {
+ UsageLimitException,
+ UsageLimitExceptionCode,
+} from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+
+export const validateUsageLimitAgainstKindRule = (
+ input: CreateUsageLimitInput,
+): void => {
+ const rule = LIMIT_KIND_RULES[input.limitKind];
+
+ if (!isDefined(rule)) {
+ throw new UsageLimitException(
+ `No rule describes what a ${input.limitKind} limit may hold`,
+ UsageLimitExceptionCode.LIMIT_INVALID,
+ );
+ }
+
+ const spansEveryOperation = input.operationType === UsageOperationType.ALL;
+
+ if (!rule.isAllOperationTypeAllowed && spansEveryOperation) {
+ throw new UsageLimitException(
+ `A ${input.limitKind} limit targets a single operation, not ${UsageOperationType.ALL}`,
+ UsageLimitExceptionCode.LIMIT_INVALID,
+ );
+ }
+
+ if (!rule.allowedPeriodUnits.includes(input.periodUnit)) {
+ throw new UsageLimitException(
+ `A ${input.limitKind} limit cannot run on a ${input.periodUnit} period, only on ${rule.allowedPeriodUnits.join(', ')}`,
+ UsageLimitExceptionCode.LIMIT_INVALID,
+ );
+ }
+
+ if (
+ isDefined(rule.requiredPeriodCount) &&
+ input.periodCount !== rule.requiredPeriodCount
+ ) {
+ throw new UsageLimitException(
+ `A ${input.limitKind} limit covers exactly ${rule.requiredPeriodCount} period, not ${input.periodCount}`,
+ UsageLimitExceptionCode.LIMIT_INVALID,
+ );
+ }
+
+ if (!rule.allowedMeters.includes(input.meter)) {
+ throw new UsageLimitException(
+ `A ${input.limitKind} limit cannot be metered on ${input.meter}, only on ${rule.allowedMeters.join(', ')}`,
+ UsageLimitExceptionCode.LIMIT_INVALID,
+ );
+ }
+
+ if (!rule.isBurstValueAllowed && isDefined(input.burstValue)) {
+ throw new UsageLimitException(
+ `A ${input.limitKind} limit cannot hold a burst value`,
+ UsageLimitExceptionCode.LIMIT_INVALID,
+ );
+ }
+
+ if (
+ input.limitKind === 'quota' &&
+ input.meter === 'quantity' &&
+ spansEveryOperation
+ ) {
+ throw new UsageLimitException(
+ 'A quantity quota needs an operation: only credits aggregate across operations',
+ UsageLimitExceptionCode.LIMIT_INVALID,
+ );
+ }
+
+ if (
+ input.limitKind === 'stock' &&
+ input.spenderType !== 'workspace' &&
+ !isNonEmptyString(input.spenderId)
+ ) {
+ throw new UsageLimitException(
+ `A ${input.spenderType} stock needs the ${input.spenderType} it caps`,
+ UsageLimitExceptionCode.LIMIT_INVALID,
+ );
+ }
+};
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 951b86ee197..5ed2c4c9aad 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
@@ -16,6 +16,7 @@ export enum UsageOperationType {
// would spend the workspace's request budget.
API_REQUEST = 'API_REQUEST',
WEBHOOK_CALL = 'WEBHOOK_CALL',
+ STORAGE_FILE = 'STORAGE_FILE',
// Platform-raised, once per billing period. Also out of
// USAGE_OPERATION_TYPES: an app declares the amount, it never charges this.
SUBSCRIPTION = 'SUBSCRIPTION',
diff --git a/packages/twenty-server/src/engine/core-modules/usage/usage-analytics.module.ts b/packages/twenty-server/src/engine/core-modules/usage/usage-analytics.module.ts
new file mode 100644
index 00000000000..b5d82dce85c
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage/usage-analytics.module.ts
@@ -0,0 +1,13 @@
+/* @license Enterprise */
+
+import { Module } from '@nestjs/common';
+
+import { ClickHouseModule } from 'src/database/clickhouse/clickhouse.module';
+import { UsageAnalyticsService } from 'src/engine/core-modules/usage/services/usage-analytics.service';
+
+@Module({
+ imports: [ClickHouseModule],
+ providers: [UsageAnalyticsService],
+ exports: [UsageAnalyticsService],
+})
+export class UsageAnalyticsModule {}
diff --git a/packages/twenty-server/src/engine/core-modules/usage/usage.module.ts b/packages/twenty-server/src/engine/core-modules/usage/usage.module.ts
index 121ef264e02..1af06cb1be9 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/usage.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/usage.module.ts
@@ -4,11 +4,10 @@ import { Module } from '@nestjs/common';
import { DiscoveryModule } from '@nestjs/core';
import { TypeOrmModule } from '@nestjs/typeorm';
-import { ClickHouseModule } from 'src/database/clickhouse/clickhouse.module';
import { EventLogEmitterModule } from 'src/engine/core-modules/event-logs/emit/event-log-emitter.module';
import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';
import { UsageEventListener } from 'src/engine/core-modules/usage/listeners/usage-event.listener';
-import { UsageAnalyticsService } from 'src/engine/core-modules/usage/services/usage-analytics.service';
+import { UsageAnalyticsModule } from 'src/engine/core-modules/usage/usage-analytics.module';
import { UsageRecorderService } from 'src/engine/core-modules/usage/services/usage-recorder.service';
import { UsageResolver } from 'src/engine/core-modules/usage/usage.resolver';
import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
@@ -17,7 +16,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
@Module({
imports: [
- ClickHouseModule,
+ UsageAnalyticsModule,
DiscoveryModule,
EventLogEmitterModule,
FeatureFlagModule,
@@ -25,12 +24,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
TypeOrmModule.forFeature([UserWorkspaceEntity]),
WorkspaceCacheModule,
],
- providers: [
- UsageResolver,
- UsageAnalyticsService,
- UsageRecorderService,
- UsageEventListener,
- ],
- exports: [UsageAnalyticsService, UsageRecorderService],
+ providers: [UsageResolver, UsageRecorderService, UsageEventListener],
+ exports: [UsageAnalyticsModule, UsageRecorderService],
})
export class UsageModule {}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/entities/agent-chat-thread.entity.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/entities/agent-chat-thread.entity.ts
index fda0ff87697..ca5583c3f98 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/entities/agent-chat-thread.entity.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/entities/agent-chat-thread.entity.ts
@@ -13,7 +13,7 @@ import {
import { ADD_LAST_STREAM_ERROR_TO_AGENT_CHAT_THREAD_UPGRADE_COMMAND_NAME } from 'src/database/commands/upgrade-version-command/2-19/add-last-stream-error-to-agent-chat-thread-upgrade-command-name.constant';
import { ADD_PENDING_QUESTION_MESSAGE_ID_TO_AGENT_CHAT_THREAD_UPGRADE_COMMAND_NAME } from 'src/database/commands/upgrade-version-command/2-19/add-pending-question-message-id-to-agent-chat-thread-upgrade-command-name.constant';
import { WasIntroducedInUpgrade } from 'src/engine/core-modules/upgrade/decorators/was-introduced-in-upgrade.decorator';
-import { nullableBigintColumnTransformer } from 'src/engine/core-modules/usage-limit/utils/nullable-bigint-column-transformer.util';
+import { nullableBigintColumnTransformer } from 'src/engine/twenty-orm/utils/nullable-bigint-column-transformer.util';
import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
import { AgentMessageEntity } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';
import { AgentTurnEntity } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-turn.entity';
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/nullable-bigint-column-transformer.util.ts b/packages/twenty-server/src/engine/twenty-orm/utils/nullable-bigint-column-transformer.util.ts
similarity index 100%
rename from packages/twenty-server/src/engine/core-modules/usage-limit/utils/nullable-bigint-column-transformer.util.ts
rename to packages/twenty-server/src/engine/twenty-orm/utils/nullable-bigint-column-transformer.util.ts
diff --git a/packages/twenty-server/src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository.ts b/packages/twenty-server/src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository.ts
index 364284f7499..d4e6e846343 100644
--- a/packages/twenty-server/src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository.ts
@@ -1,3 +1,4 @@
+import { isDefined } from 'twenty-shared/utils';
import {
type DeepPartial,
type DeleteResult,
@@ -11,7 +12,6 @@ import {
type SelectQueryBuilder,
type UpdateResult,
} from 'typeorm';
-import { isDefined } from 'twenty-shared/utils';
import { type QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
import { type UpsertOptions } from 'typeorm/repository/UpsertOptions';
@@ -167,6 +167,39 @@ export class WorkspaceScopedRepository<T extends WorkspaceScopedEntity> {
);
}
+ async deleteAndReturn(
+ workspaceId: string,
+ criteria: FindOptionsWhere<T>,
+ ): Promise<T[]> {
+ this.assertWorkspaceId(workspaceId);
+
+ const { raw } = await this.repository
+ .createQueryBuilder()
+ .delete()
+ .from(this.repository.target)
+ .where(this.mergeWorkspaceIdIntoCriteria(workspaceId, criteria))
+ .returning('*')
+ .execute();
+
+ return ((raw ?? []) as Record<string, unknown>[]).map((row) =>
+ this.repository.create(this.hydrateRawRow(row)),
+ );
+ }
+
+ // DELETE ... RETURNING hands back raw driver output, which skips the
+ // hydration a find would do, so column transformers have to be applied by
+ // hand: a bigint column would otherwise read back as a string.
+ private hydrateRawRow(row: Record<string, unknown>): DeepPartial<T> {
+ const { driver } = this.repository.manager.connection;
+
+ return Object.fromEntries(
+ this.repository.metadata.columns.map((column) => [
+ column.propertyName,
+ driver.prepareHydratedValue(row[column.databaseName], column),
+ ]),
+ ) as DeepPartial<T>;
+ }
+
softDelete(
workspaceId: string,
criteria: FindOptionsWhere<T>,
diff --git a/packages/twenty-server/test/integration/usage-limit/usage-limit-mutations.integration-spec.ts b/packages/twenty-server/test/integration/usage-limit/usage-limit-mutations.integration-spec.ts
index e439831bd3f..832b6a07844 100644
--- a/packages/twenty-server/test/integration/usage-limit/usage-limit-mutations.integration-spec.ts
+++ b/packages/twenty-server/test/integration/usage-limit/usage-limit-mutations.integration-spec.ts
@@ -155,7 +155,7 @@ describe('Usage limit mutations', () => {
const response = await createUsageLimitRequest({ burstValue: 10 });
expect(response.body.errors?.[0]?.message).toBe(
- 'A quota cannot hold a burst value',
+ 'A quota limit cannot hold a burst value',
);
});
});
diff --git a/packages/twenty-shared/src/application/usageOperationTypesType.ts b/packages/twenty-shared/src/application/usageOperationTypesType.ts
index 7f585bc1801..60ca370863c 100644
--- a/packages/twenty-shared/src/application/usageOperationTypesType.ts
+++ b/packages/twenty-shared/src/application/usageOperationTypesType.ts
@@ -1,7 +1,7 @@
// The subset of the server's UsageOperationType an app may bill under, so a
-// manifest can name a category without importing server code. API_REQUEST and
-// SUBSCRIPTION are left out on purpose: the platform raises both itself, and
-// API_REQUEST rows feed the workspace's API rate limit.
+// manifest can name a category without importing server code. API_REQUEST,
+// STORAGE_FILE and SUBSCRIPTION are left out on purpose: the platform raises
+// all three itself, and API_REQUEST rows feed the workspace's API rate limit.
export const USAGE_OPERATION_TYPES = [
'AI_CHAT_TOKEN',
'AI_WORKFLOW_TOKEN',