Skip to content

The open alternative to Salesforce, designed for AI.

feat(usage) - collect + attribute every CommonAPI request (#24960)

Etienne58d2f46a7891
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index 62a0d14567e..7362d97ff8c 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -1833,6 +1833,32 @@ type ConnectedAccountPublicDTO {
connectionParameters: PublicImapSmtpCaldavConnectionParameters
}
+type UsageBreakdownItem {
+ key: String!
+ label: String
+ creditsUsed: Float!
+}
+
+type UsageTimeSeries {
+ date: String!
+ creditsUsed: Float!
+}
+
+type UsageUserDaily {
+ userWorkspaceId: String!
+ dailyUsage: [UsageTimeSeries!]!
+}
+
+type UsageAnalytics {
+ usageByUser: [UsageBreakdownItem!]!
+ usageByOperationType: [UsageBreakdownItem!]!
+ usageByModel: [UsageBreakdownItem!]!
+ timeSeries: [UsageTimeSeries!]!
+ periodStart: DateTime!
+ periodEnd: DateTime!
+ userDailyUsage: UsageUserDaily
+}
+
type FeatureFlag {
key: FeatureFlagKey!
value: Boolean!
@@ -2063,12 +2089,6 @@ type ClientConfig {
maintenance: ClientConfigMaintenanceMode
}
-type UsageBreakdownItem {
- key: String!
- label: String
- creditsUsed: Float!
-}
-
type ClaimableApplicationRegistration {
id: String!
universalIdentifier: String!
@@ -2599,26 +2619,6 @@ type StopImpersonation {
canRestoreImpersonatorSession: Boolean!
}
-type UsageTimeSeries {
- date: String!
- creditsUsed: Float!
-}
-
-type UsageUserDaily {
- userWorkspaceId: String!
- dailyUsage: [UsageTimeSeries!]!
-}
-
-type UsageAnalytics {
- usageByUser: [UsageBreakdownItem!]!
- usageByOperationType: [UsageBreakdownItem!]!
- usageByModel: [UsageBreakdownItem!]!
- timeSeries: [UsageTimeSeries!]!
- periodStart: DateTime!
- periodEnd: DateTime!
- userDailyUsage: UsageUserDaily
-}
-
type ApplicationAuthorization {
id: UUID!
applicationId: UUID!
@@ -3411,6 +3411,7 @@ type Query {
enterprisePortalSession(returnUrlPath: String): String
enterpriseCheckoutSession(billingInterval: String): String
enterpriseSubscriptionStatus: EnterpriseSubscriptionStatusDTO
+ getUsageAnalytics(input: UsageAnalyticsInput): UsageAnalytics!
usageLimits: [UsageLimit!]!
getViewFilterGroups(viewId: String): [ViewFilterGroup!]!
getViewFilterGroup(id: String!): ViewFilterGroup
@@ -3539,11 +3540,17 @@ type Query {
getConnectedImapSmtpCaldavAccount(id: UUID!): ConnectedImapSmtpCaldavAccount!
getAutoCompleteAddress(address: String!, token: String!, country: String, isFieldCity: Boolean): [AutocompleteResult!]!
getAddressDetails(placeId: String!, token: String!): PlaceDetailsResult!
- getUsageAnalytics(input: UsageAnalyticsInput): UsageAnalytics!
findManyPublicDomains: [PublicDomain!]!
currentUserApplicationAuthorizations: [ApplicationAuthorization!]!
}
+input UsageAnalyticsInput {
+ periodStart: DateTime
+ periodEnd: DateTime
+ userWorkspaceId: String
+ operationTypes: [UsageOperationType!]
+}
+
input GetApiKeyInput {
id: UUID!
}
@@ -3640,13 +3647,6 @@ input BarChartDataInput {
configuration: JSON!
}
-input UsageAnalyticsInput {
- periodStart: DateTime
- periodEnd: DateTime
- userWorkspaceId: String
- operationTypes: [UsageOperationType!]
-}
-
type Mutation {
addQueryToEventStream(input: AddQuerySubscriptionInput!): Boolean!
removeQueryFromEventStream(input: RemoveQueryFromEventStreamInput!): Boolean!
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index c68239882ee..1a3d3ccb934 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -1474,6 +1474,36 @@ export interface ConnectedAccountPublicDTO {
__typename: 'ConnectedAccountPublicDTO'
}
+export interface UsageBreakdownItem {
+ key: Scalars['String']
+ label?: Scalars['String']
+ creditsUsed: Scalars['Float']
+ __typename: 'UsageBreakdownItem'
+}
+
+export interface UsageTimeSeries {
+ date: Scalars['String']
+ creditsUsed: Scalars['Float']
+ __typename: 'UsageTimeSeries'
+}
+
+export interface UsageUserDaily {
+ userWorkspaceId: Scalars['String']
+ dailyUsage: UsageTimeSeries[]
+ __typename: 'UsageUserDaily'
+}
+
+export interface UsageAnalytics {
+ usageByUser: UsageBreakdownItem[]
+ usageByOperationType: UsageBreakdownItem[]
+ usageByModel: UsageBreakdownItem[]
+ timeSeries: UsageTimeSeries[]
+ periodStart: Scalars['DateTime']
+ periodEnd: Scalars['DateTime']
+ userDailyUsage?: UsageUserDaily
+ __typename: 'UsageAnalytics'
+}
+
export interface FeatureFlag {
key: FeatureFlagKey
value: Scalars['Boolean']
@@ -1694,13 +1724,6 @@ export interface ClientConfig {
__typename: 'ClientConfig'
}
-export interface UsageBreakdownItem {
- key: Scalars['String']
- label?: Scalars['String']
- creditsUsed: Scalars['Float']
- __typename: 'UsageBreakdownItem'
-}
-
export interface ClaimableApplicationRegistration {
id: Scalars['String']
universalIdentifier: Scalars['String']
@@ -2245,29 +2268,6 @@ export interface StopImpersonation {
__typename: 'StopImpersonation'
}
-export interface UsageTimeSeries {
- date: Scalars['String']
- creditsUsed: Scalars['Float']
- __typename: 'UsageTimeSeries'
-}
-
-export interface UsageUserDaily {
- userWorkspaceId: Scalars['String']
- dailyUsage: UsageTimeSeries[]
- __typename: 'UsageUserDaily'
-}
-
-export interface UsageAnalytics {
- usageByUser: UsageBreakdownItem[]
- usageByOperationType: UsageBreakdownItem[]
- usageByModel: UsageBreakdownItem[]
- timeSeries: UsageTimeSeries[]
- periodStart: Scalars['DateTime']
- periodEnd: Scalars['DateTime']
- userDailyUsage?: UsageUserDaily
- __typename: 'UsageAnalytics'
-}
-
export interface ApplicationAuthorization {
id: Scalars['UUID']
applicationId: Scalars['UUID']
@@ -2999,6 +2999,7 @@ export interface Query {
enterprisePortalSession?: Scalars['String']
enterpriseCheckoutSession?: Scalars['String']
enterpriseSubscriptionStatus?: EnterpriseSubscriptionStatusDTO
+ getUsageAnalytics: UsageAnalytics
usageLimits: UsageLimit[]
getViewFilterGroups: ViewFilterGroup[]
getViewFilterGroup?: ViewFilterGroup
@@ -3109,7 +3110,6 @@ export interface Query {
getConnectedImapSmtpCaldavAccount: ConnectedImapSmtpCaldavAccount
getAutoCompleteAddress: AutocompleteResult[]
getAddressDetails: PlaceDetailsResult
- getUsageAnalytics: UsageAnalytics
findManyPublicDomains: PublicDomain[]
currentUserApplicationAuthorizations: ApplicationAuthorization[]
__typename: 'Query'
@@ -4903,6 +4903,40 @@ export interface ConnectedAccountPublicDTOGenqlSelection{
__scalar?: boolean | number
}
+export interface UsageBreakdownItemGenqlSelection{
+ key?: boolean | number
+ label?: boolean | number
+ creditsUsed?: boolean | number
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
+export interface UsageTimeSeriesGenqlSelection{
+ date?: boolean | number
+ creditsUsed?: boolean | number
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
+export interface UsageUserDailyGenqlSelection{
+ userWorkspaceId?: boolean | number
+ dailyUsage?: UsageTimeSeriesGenqlSelection
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
+export interface UsageAnalyticsGenqlSelection{
+ usageByUser?: UsageBreakdownItemGenqlSelection
+ usageByOperationType?: UsageBreakdownItemGenqlSelection
+ usageByModel?: UsageBreakdownItemGenqlSelection
+ timeSeries?: UsageTimeSeriesGenqlSelection
+ periodStart?: boolean | number
+ periodEnd?: boolean | number
+ userDailyUsage?: UsageUserDailyGenqlSelection
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
export interface FeatureFlagGenqlSelection{
key?: boolean | number
value?: boolean | number
@@ -5133,14 +5167,6 @@ export interface ClientConfigGenqlSelection{
__scalar?: boolean | number
}
-export interface UsageBreakdownItemGenqlSelection{
- key?: boolean | number
- label?: boolean | number
- creditsUsed?: boolean | number
- __typename?: boolean | number
- __scalar?: boolean | number
-}
-
export interface ClaimableApplicationRegistrationGenqlSelection{
id?: boolean | number
universalIdentifier?: boolean | number
@@ -5730,32 +5756,6 @@ export interface StopImpersonationGenqlSelection{
__scalar?: boolean | number
}
-export interface UsageTimeSeriesGenqlSelection{
- date?: boolean | number
- creditsUsed?: boolean | number
- __typename?: boolean | number
- __scalar?: boolean | number
-}
-
-export interface UsageUserDailyGenqlSelection{
- userWorkspaceId?: boolean | number
- dailyUsage?: UsageTimeSeriesGenqlSelection
- __typename?: boolean | number
- __scalar?: boolean | number
-}
-
-export interface UsageAnalyticsGenqlSelection{
- usageByUser?: UsageBreakdownItemGenqlSelection
- usageByOperationType?: UsageBreakdownItemGenqlSelection
- usageByModel?: UsageBreakdownItemGenqlSelection
- timeSeries?: UsageTimeSeriesGenqlSelection
- periodStart?: boolean | number
- periodEnd?: boolean | number
- userDailyUsage?: UsageUserDailyGenqlSelection
- __typename?: boolean | number
- __scalar?: boolean | number
-}
-
export interface ApplicationAuthorizationGenqlSelection{
id?: boolean | number
applicationId?: boolean | number
@@ -6515,6 +6515,7 @@ 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
getViewFilterGroups?: (ViewFilterGroupGenqlSelection & { __args?: {viewId?: (Scalars['String'] | null)} })
getViewFilterGroup?: (ViewFilterGroupGenqlSelection & { __args: {id: Scalars['String']} })
@@ -6637,13 +6638,14 @@ export interface QueryGenqlSelection{
getConnectedImapSmtpCaldavAccount?: (ConnectedImapSmtpCaldavAccountGenqlSelection & { __args: {id: Scalars['UUID']} })
getAutoCompleteAddress?: (AutocompleteResultGenqlSelection & { __args: {address: Scalars['String'], token: Scalars['String'], country?: (Scalars['String'] | null), isFieldCity?: (Scalars['Boolean'] | null)} })
getAddressDetails?: (PlaceDetailsResultGenqlSelection & { __args: {placeId: Scalars['String'], token: Scalars['String']} })
- getUsageAnalytics?: (UsageAnalyticsGenqlSelection & { __args?: {input?: (UsageAnalyticsInput | null)} })
findManyPublicDomains?: PublicDomainGenqlSelection
currentUserApplicationAuthorizations?: ApplicationAuthorizationGenqlSelection
__typename?: boolean | number
__scalar?: boolean | number
}
+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 {
@@ -6676,8 +6678,6 @@ export interface LineChartDataInput {objectMetadataId: Scalars['UUID'],configura
export interface BarChartDataInput {objectMetadataId: Scalars['UUID'],configuration: Scalars['JSON']}
-export interface UsageAnalyticsInput {periodStart?: (Scalars['DateTime'] | null),periodEnd?: (Scalars['DateTime'] | null),userWorkspaceId?: (Scalars['String'] | null),operationTypes?: (UsageOperationType[] | null)}
-
export interface MutationGenqlSelection{
addQueryToEventStream?: { __args: {input: AddQuerySubscriptionInput} }
removeQueryFromEventStream?: { __args: {input: RemoveQueryFromEventStreamInput} }
@@ -8302,6 +8302,38 @@ export interface LogicFunctionLogsInput {applicationId?: (Scalars['UUID'] | null
+ const UsageBreakdownItem_possibleTypes: string[] = ['UsageBreakdownItem']
+ export const isUsageBreakdownItem = (obj?: { __typename?: any } | null): obj is UsageBreakdownItem => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isUsageBreakdownItem"')
+ return UsageBreakdownItem_possibleTypes.includes(obj.__typename)
+ }
+
+
+
+ const UsageTimeSeries_possibleTypes: string[] = ['UsageTimeSeries']
+ export const isUsageTimeSeries = (obj?: { __typename?: any } | null): obj is UsageTimeSeries => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isUsageTimeSeries"')
+ return UsageTimeSeries_possibleTypes.includes(obj.__typename)
+ }
+
+
+
+ const UsageUserDaily_possibleTypes: string[] = ['UsageUserDaily']
+ export const isUsageUserDaily = (obj?: { __typename?: any } | null): obj is UsageUserDaily => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isUsageUserDaily"')
+ return UsageUserDaily_possibleTypes.includes(obj.__typename)
+ }
+
+
+
+ const UsageAnalytics_possibleTypes: string[] = ['UsageAnalytics']
+ export const isUsageAnalytics = (obj?: { __typename?: any } | null): obj is UsageAnalytics => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isUsageAnalytics"')
+ return UsageAnalytics_possibleTypes.includes(obj.__typename)
+ }
+
+
+
const FeatureFlag_possibleTypes: string[] = ['FeatureFlag']
export const isFeatureFlag = (obj?: { __typename?: any } | null): obj is FeatureFlag => {
if (!obj?.__typename) throw new Error('__typename is missing in "isFeatureFlag"')
@@ -8478,14 +8510,6 @@ export interface LogicFunctionLogsInput {applicationId?: (Scalars['UUID'] | null
- const UsageBreakdownItem_possibleTypes: string[] = ['UsageBreakdownItem']
- export const isUsageBreakdownItem = (obj?: { __typename?: any } | null): obj is UsageBreakdownItem => {
- if (!obj?.__typename) throw new Error('__typename is missing in "isUsageBreakdownItem"')
- return UsageBreakdownItem_possibleTypes.includes(obj.__typename)
- }
-
-
-
const ClaimableApplicationRegistration_possibleTypes: string[] = ['ClaimableApplicationRegistration']
export const isClaimableApplicationRegistration = (obj?: { __typename?: any } | null): obj is ClaimableApplicationRegistration => {
if (!obj?.__typename) throw new Error('__typename is missing in "isClaimableApplicationRegistration"')
@@ -8990,30 +9014,6 @@ export interface LogicFunctionLogsInput {applicationId?: (Scalars['UUID'] | null
- const UsageTimeSeries_possibleTypes: string[] = ['UsageTimeSeries']
- export const isUsageTimeSeries = (obj?: { __typename?: any } | null): obj is UsageTimeSeries => {
- if (!obj?.__typename) throw new Error('__typename is missing in "isUsageTimeSeries"')
- return UsageTimeSeries_possibleTypes.includes(obj.__typename)
- }
-
-
-
- const UsageUserDaily_possibleTypes: string[] = ['UsageUserDaily']
- export const isUsageUserDaily = (obj?: { __typename?: any } | null): obj is UsageUserDaily => {
- if (!obj?.__typename) throw new Error('__typename is missing in "isUsageUserDaily"')
- return UsageUserDaily_possibleTypes.includes(obj.__typename)
- }
-
-
-
- const UsageAnalytics_possibleTypes: string[] = ['UsageAnalytics']
- export const isUsageAnalytics = (obj?: { __typename?: any } | null): obj is UsageAnalytics => {
- if (!obj?.__typename) throw new Error('__typename is missing in "isUsageAnalytics"')
- return UsageAnalytics_possibleTypes.includes(obj.__typename)
- }
-
-
-
const ApplicationAuthorization_possibleTypes: string[] = ['ApplicationAuthorization']
export const isApplicationAuthorization = (obj?: { __typename?: any } | null): obj is ApplicationAuthorization => {
if (!obj?.__typename) throw new Error('__typename is missing in "isApplicationAuthorization"')
diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.ts
index 7d52e363f75..754611013ed 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts
@@ -58,19 +58,19 @@ export default {
160,
162,
178,
- 182,
- 189,
- 190,
- 197,
- 200,
- 203,
- 215,
- 232,
- 233,
+ 186,
+ 193,
+ 194,
+ 201,
+ 204,
+ 207,
+ 218,
235,
- 240,
+ 236,
+ 238,
243,
- 252,
+ 246,
+ 255,
288,
296,
298,
@@ -92,7 +92,7 @@ export default {
367,
369,
374,
- 388,
+ 389,
401,
515,
539
@@ -562,7 +562,7 @@ export default {
1
],
"fields": [
- 247,
+ 250,
{
"paging": [
25,
@@ -575,7 +575,7 @@ export default {
}
],
"indexMetadatas": [
- 248,
+ 251,
{
"paging": [
25,
@@ -588,13 +588,13 @@ export default {
}
],
"fieldsList": [
- 234
+ 237
],
"indexMetadataList": [
- 242
+ 245
],
"searchFieldMetadataList": [
- 250
+ 253
],
"__typename": [
1
@@ -1636,7 +1636,7 @@ export default {
47
],
"featureFlags": [
- 181
+ 185
],
"billingSubscriptions": [
146
@@ -1651,7 +1651,7 @@ export default {
145
],
"billingEntitlements": [
- 251
+ 254
],
"hasValidSignedEnterpriseKey": [
8
@@ -1660,7 +1660,7 @@ export default {
8
],
"workspaceUrls": [
- 183
+ 187
],
"workspaceCustomApplicationId": [
1
@@ -1733,7 +1733,7 @@ export default {
33
],
"deletedWorkspaceMembers": [
- 225
+ 228
],
"hasPassword": [
8
@@ -1748,7 +1748,7 @@ export default {
50
],
"availableWorkspaces": [
- 224
+ 227
],
"__typename": [
1
@@ -3530,10 +3530,72 @@ export default {
1
]
},
- "FeatureFlag": {
+ "UsageBreakdownItem": {
"key": [
+ 1
+ ],
+ "label": [
+ 1
+ ],
+ "creditsUsed": [
+ 15
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "UsageTimeSeries": {
+ "date": [
+ 1
+ ],
+ "creditsUsed": [
+ 15
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "UsageUserDaily": {
+ "userWorkspaceId": [
+ 1
+ ],
+ "dailyUsage": [
182
],
+ "__typename": [
+ 1
+ ]
+ },
+ "UsageAnalytics": {
+ "usageByUser": [
+ 181
+ ],
+ "usageByOperationType": [
+ 181
+ ],
+ "usageByModel": [
+ 181
+ ],
+ "timeSeries": [
+ 182
+ ],
+ "periodStart": [
+ 4
+ ],
+ "periodEnd": [
+ 4
+ ],
+ "userDailyUsage": [
+ 183
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "FeatureFlag": {
+ "key": [
+ 186
+ ],
"value": [
8
],
@@ -3613,7 +3675,7 @@ export default {
1
],
"versionDistribution": [
- 185
+ 189
],
"__typename": [
1
@@ -3638,10 +3700,10 @@ export default {
1
],
"type": [
- 189
+ 193
],
"status": [
- 190
+ 194
],
"issuer": [
1
@@ -3654,7 +3716,7 @@ export default {
"SSOIdentityProviderStatus": {},
"AuthProviders": {
"sso": [
- 188
+ 192
],
"google": [
8
@@ -3691,10 +3753,10 @@ export default {
3
],
"authProviders": [
- 191
+ 195
],
"authBypassProviders": [
- 192
+ 196
],
"logo": [
1
@@ -3703,7 +3765,7 @@ export default {
1
],
"workspaceUrls": [
- 183
+ 187
],
"__typename": [
1
@@ -3742,7 +3804,7 @@ export default {
1
],
"modelFamily": [
- 197
+ 201
],
"modelFamilyLabel": [
1
@@ -3757,7 +3819,7 @@ export default {
15
],
"nativeCapabilities": [
- 195
+ 199
],
"isDeprecated": [
8
@@ -3796,7 +3858,7 @@ export default {
1
],
"trialPeriods": [
- 187
+ 191
],
"__typename": [
1
@@ -3804,7 +3866,7 @@ export default {
},
"Support": {
"supportDriver": [
- 200
+ 204
],
"supportFrontChatId": [
1
@@ -3833,7 +3895,7 @@ export default {
},
"Captcha": {
"provider": [
- 203
+ 207
],
"siteKey": [
1
@@ -3870,10 +3932,10 @@ export default {
},
"PublicFeatureFlag": {
"key": [
- 182
+ 186
],
"metadata": [
- 205
+ 209
],
"__typename": [
1
@@ -3898,13 +3960,13 @@ export default {
1
],
"authProviders": [
- 191
+ 195
],
"billing": [
- 198
+ 202
],
"aiModels": [
- 196
+ 200
],
"signInPrefilled": [
8
@@ -3928,25 +3990,25 @@ export default {
8
],
"support": [
- 199
+ 203
],
"isAttachmentPreviewEnabled": [
8
],
"sentry": [
- 201
+ 205
],
"captcha": [
- 202
+ 206
],
"api": [
- 204
+ 208
],
"canManageFeatureFlags": [
8
],
"publicFeatureFlags": [
- 206
+ 210
],
"isCookieSessionEnabled": [
8
@@ -4000,21 +4062,7 @@ export default {
1
],
"maintenance": [
- 207
- ],
- "__typename": [
- 1
- ]
- },
- "UsageBreakdownItem": {
- "key": [
- 1
- ],
- "label": [
- 1
- ],
- "creditsUsed": [
- 15
+ 211
],
"__typename": [
1
@@ -4090,7 +4138,7 @@ export default {
},
"AppConnection": {
"id": [
- 215
+ 218
],
"providerName": [
1
@@ -4145,7 +4193,7 @@ export default {
3
],
"type": [
- 189
+ 193
],
"issuer": [
1
@@ -4154,7 +4202,7 @@ export default {
1
],
"status": [
- 190
+ 194
],
"__typename": [
1
@@ -4173,7 +4221,7 @@ export default {
},
"FindAvailableSSOIDP": {
"type": [
- 189
+ 193
],
"id": [
3
@@ -4185,10 +4233,10 @@ export default {
1
],
"status": [
- 190
+ 194
],
"workspace": [
- 219
+ 222
],
"__typename": [
1
@@ -4199,7 +4247,7 @@ export default {
3
],
"type": [
- 189
+ 193
],
"issuer": [
1
@@ -4208,7 +4256,7 @@ export default {
1
],
"status": [
- 190
+ 194
],
"__typename": [
1
@@ -4216,7 +4264,7 @@ export default {
},
"SSOConnection": {
"type": [
- 189
+ 193
],
"id": [
3
@@ -4228,7 +4276,7 @@ export default {
1
],
"status": [
- 190
+ 194
],
"__typename": [
1
@@ -4251,13 +4299,13 @@ export default {
1
],
"workspaceUrls": [
- 183
+ 187
],
"logo": [
1
],
"sso": [
- 222
+ 225
],
"__typename": [
1
@@ -4265,10 +4313,10 @@ export default {
},
"AvailableWorkspaces": {
"availableWorkspacesForSignIn": [
- 223
+ 226
],
"availableWorkspacesForSignUp": [
- 223
+ 226
],
"__typename": [
1
@@ -4401,10 +4449,10 @@ export default {
1
],
"objectPermissions": [
- 227
+ 230
],
"fieldPermissions": [
- 228
+ 231
],
"__typename": [
1
@@ -4472,7 +4520,7 @@ export default {
1
],
"roles": [
- 229
+ 232
],
"manifest": [
9
@@ -4483,13 +4531,13 @@ export default {
},
"WorkspaceCompanyEnrichmentResult": {
"outcome": [
- 232
+ 235
],
"enrichment": [
9
],
"personOutcome": [
- 233
+ 236
],
"personEnrichment": [
9
@@ -4511,7 +4559,7 @@ export default {
1
],
"type": [
- 235
+ 238
],
"name": [
1
@@ -4574,10 +4622,10 @@ export default {
23
],
"relation": [
- 239
+ 242
],
"morphRelations": [
- 239
+ 242
],
"__typename": [
1
@@ -4603,7 +4651,7 @@ export default {
},
"FieldEdge": {
"node": [
- 234
+ 237
],
"cursor": [
27
@@ -4614,10 +4662,10 @@ export default {
},
"FieldConnection": {
"pageInfo": [
- 236
+ 239
],
"edges": [
- 237
+ 240
],
"__typename": [
1
@@ -4625,7 +4673,7 @@ export default {
},
"Relation": {
"type": [
- 240
+ 243
],
"sourceObjectMetadata": [
23
@@ -4634,10 +4682,10 @@ export default {
23
],
"sourceFieldMetadata": [
- 234
+ 237
],
"targetFieldMetadata": [
- 234
+ 237
],
"__typename": [
1
@@ -4684,7 +4732,7 @@ export default {
1
],
"indexType": [
- 243
+ 246
],
"createdAt": [
4
@@ -4693,7 +4741,7 @@ export default {
4
],
"indexFieldMetadataList": [
- 241
+ 244
],
"__typename": [
1
@@ -4702,7 +4750,7 @@ export default {
"IndexType": {},
"IndexEdge": {
"node": [
- 242
+ 245
],
"cursor": [
27
@@ -4724,10 +4772,10 @@ export default {
},
"ObjectConnection": {
"pageInfo": [
- 236
+ 239
],
"edges": [
- 245
+ 248
],
"__typename": [
1
@@ -4735,10 +4783,10 @@ export default {
},
"ObjectFieldsConnection": {
"pageInfo": [
- 236
+ 239
],
"edges": [
- 237
+ 240
],
"__typename": [
1
@@ -4746,10 +4794,10 @@ export default {
},
"ObjectIndexMetadatasConnection": {
"pageInfo": [
- 236
+ 239
],
"edges": [
- 244
+ 247
],
"__typename": [
1
@@ -4791,7 +4839,7 @@ export default {
},
"BillingEntitlement": {
"key": [
- 252
+ 255
],
"value": [
8
@@ -4829,7 +4877,7 @@ export default {
1
],
"records": [
- 253
+ 256
],
"isCustomDomainEnabled": [
8
@@ -4902,10 +4950,10 @@ export default {
},
"AvailableWorkspacesAndAccessTokens": {
"tokens": [
- 261
+ 264
],
"availableWorkspaces": [
- 224
+ 227
],
"__typename": [
1
@@ -4943,7 +4991,7 @@ export default {
},
"WorkspaceUrlsAndId": {
"workspaceUrls": [
- 183
+ 187
],
"id": [
3
@@ -4957,7 +5005,7 @@ export default {
11
],
"workspace": [
- 266
+ 269
],
"__typename": [
1
@@ -4990,7 +5038,7 @@ export default {
11
],
"workspaceUrls": [
- 183
+ 187
],
"__typename": [
1
@@ -5034,7 +5082,7 @@ export default {
},
"AuthTokens": {
"tokens": [
- 261
+ 264
],
"__typename": [
1
@@ -5075,7 +5123,7 @@ export default {
11
],
"workspace": [
- 266
+ 269
],
"__typename": [
1
@@ -5089,54 +5137,6 @@ export default {
1
]
},
- "UsageTimeSeries": {
- "date": [
- 1
- ],
- "creditsUsed": [
- 15
- ],
- "__typename": [
- 1
- ]
- },
- "UsageUserDaily": {
- "userWorkspaceId": [
- 1
- ],
- "dailyUsage": [
- 280
- ],
- "__typename": [
- 1
- ]
- },
- "UsageAnalytics": {
- "usageByUser": [
- 209
- ],
- "usageByOperationType": [
- 209
- ],
- "usageByModel": [
- 209
- ],
- "timeSeries": [
- 280
- ],
- "periodStart": [
- 4
- ],
- "periodEnd": [
- 4
- ],
- "userDailyUsage": [
- 281
- ],
- "__typename": [
- 1
- ]
- },
"ApplicationAuthorization": {
"id": [
3
@@ -6166,7 +6166,7 @@ export default {
},
"AgentChatThread": {
"id": [
- 215
+ 218
],
"title": [
1
@@ -6712,6 +6712,14 @@ export default {
"enterpriseSubscriptionStatus": [
151
],
+ "getUsageAnalytics": [
+ 184,
+ {
+ "input": [
+ 379
+ ]
+ }
+ ],
"usageLimits": [
75
],
@@ -6833,7 +6841,7 @@ export default {
2,
{
"input": [
- 379,
+ 380,
"GetApiKeyInput!"
]
}
@@ -6942,20 +6950,20 @@ export default {
10,
{
"input": [
- 380,
+ 381,
"AgentIdInput!"
]
}
],
"objects": [
- 246,
+ 249,
{
"paging": [
25,
"CursorPaging!"
],
"filter": [
- 381,
+ 382,
"ObjectFilter!"
]
}
@@ -6970,7 +6978,7 @@ export default {
}
],
"objectRecordCounts": [
- 249
+ 252
],
"mostlyEmptyFieldMetadataIds": [
3,
@@ -6985,7 +6993,7 @@ export default {
21,
{
"input": [
- 382,
+ 383,
"LogicFunctionIdInput!"
]
}
@@ -6997,7 +7005,7 @@ export default {
9,
{
"input": [
- 382,
+ 383,
"LogicFunctionIdInput!"
]
}
@@ -7006,7 +7014,7 @@ export default {
1,
{
"input": [
- 382,
+ 383,
"LogicFunctionIdInput!"
]
}
@@ -7039,7 +7047,7 @@ export default {
68
],
"getPublicWorkspaceDataByDomain": [
- 193,
+ 197,
{
"origin": [
1
@@ -7047,7 +7055,7 @@ export default {
}
],
"getPublicWorkspaceDataById": [
- 194,
+ 198,
{
"id": [
3,
@@ -7056,7 +7064,7 @@ export default {
}
],
"findApplicationRegistrationByClientId": [
- 212,
+ 215,
{
"clientId": [
1,
@@ -7086,7 +7094,7 @@ export default {
}
],
"findApplicationRegistrationStats": [
- 186,
+ 190,
{
"id": [
1,
@@ -7095,7 +7103,7 @@ export default {
}
],
"findApplicationRegistrationVariables": [
- 184,
+ 188,
{
"applicationRegistrationId": [
1,
@@ -7113,7 +7121,7 @@ export default {
}
],
"findClaimableApplicationRegistration": [
- 210,
+ 213,
{
"sourcePackage": [
1
@@ -7147,7 +7155,7 @@ export default {
}
],
"findManyMarketplaceApps": [
- 226,
+ 229,
{
"universalIdentifiers": [
1,
@@ -7156,7 +7164,7 @@ export default {
}
],
"findMarketplaceAppDetail": [
- 230,
+ 233,
{
"universalIdentifier": [
1,
@@ -7165,7 +7173,7 @@ export default {
}
],
"publicMarketplaceApps": [
- 226,
+ 229,
{
"isVetted": [
8,
@@ -7174,7 +7182,7 @@ export default {
}
],
"publicMarketplaceAppDetail": [
- 230,
+ 233,
{
"universalIdentifier": [
1,
@@ -7183,7 +7191,7 @@ export default {
}
],
"fields": [
- 238,
+ 241,
{
"paging": [
25,
@@ -7196,7 +7204,7 @@ export default {
}
],
"field": [
- 234,
+ 237,
{
"id": [
3,
@@ -7228,7 +7236,7 @@ export default {
306,
{
"input": [
- 383,
+ 384,
"PreviewMessageCampaignAudienceInput!"
]
}
@@ -7237,7 +7245,7 @@ export default {
314,
{
"input": [
- 384,
+ 385,
"FindMessageSuppressionsInput!"
]
}
@@ -7312,18 +7320,18 @@ export default {
}
],
"appConnections": [
- 214,
+ 217,
{
"filter": [
- 385
+ 386
]
}
],
"appConnection": [
- 214,
+ 217,
{
"id": [
- 215,
+ 218,
"ID!"
]
}
@@ -7392,13 +7400,13 @@ export default {
368,
{
"input": [
- 386,
+ 387,
"MetadataTranslationsInput!"
]
}
],
"checkUserExists": [
- 276,
+ 279,
{
"email": [
1,
@@ -7410,7 +7418,7 @@ export default {
}
],
"checkWorkspaceInviteHashIsValid": [
- 277,
+ 280,
{
"inviteHash": [
1,
@@ -7428,7 +7436,7 @@ export default {
}
],
"checkWorkspaceSubdomainAvailability": [
- 271,
+ 274,
{
"subdomain": [
1,
@@ -7437,10 +7445,10 @@ export default {
}
],
"getWorkspaceCreationDefaults": [
- 272
+ 275
],
"validatePasswordResetToken": [
- 269,
+ 272,
{
"passwordResetToken": [
1,
@@ -7452,13 +7460,13 @@ export default {
71
],
"getSSOIdentityProviders": [
- 220
+ 223
],
"eventLogs": [
342,
{
"input": [
- 387,
+ 388,
"EventLogQueryInput!"
]
}
@@ -7467,7 +7475,7 @@ export default {
336,
{
"input": [
- 391,
+ 392,
"PieChartDataInput!"
]
}
@@ -7476,7 +7484,7 @@ export default {
334,
{
"input": [
- 392,
+ 393,
"LineChartDataInput!"
]
}
@@ -7485,7 +7493,7 @@ export default {
331,
{
"input": [
- 393,
+ 394,
"BarChartDataInput!"
]
}
@@ -7540,14 +7548,6 @@ export default {
]
}
],
- "getUsageAnalytics": [
- 282,
- {
- "input": [
- 394
- ]
- }
- ],
"findManyPublicDomains": [
293
],
@@ -7558,6 +7558,23 @@ export default {
1
]
},
+ "UsageAnalyticsInput": {
+ "periodStart": [
+ 4
+ ],
+ "periodEnd": [
+ 4
+ ],
+ "userWorkspaceId": [
+ 1
+ ],
+ "operationTypes": [
+ 77
+ ],
+ "__typename": [
+ 1
+ ]
+ },
"GetApiKeyInput": {
"id": [
3
@@ -7576,10 +7593,10 @@ export default {
},
"ObjectFilter": {
"and": [
- 381
+ 382
],
"or": [
- 381
+ 382
],
"id": [
29
@@ -7614,7 +7631,7 @@ export default {
},
"LogicFunctionIdInput": {
"id": [
- 215
+ 218
],
"__typename": [
1
@@ -7681,10 +7698,10 @@ export default {
},
"EventLogQueryInput": {
"table": [
- 388
+ 389
],
"filters": [
- 389
+ 390
],
"first": [
26
@@ -7705,7 +7722,7 @@ export default {
1
],
"dateRange": [
- 390
+ 391
],
"recordId": [
1
@@ -7761,23 +7778,6 @@ export default {
1
]
},
- "UsageAnalyticsInput": {
- "periodStart": [
- 4
- ],
- "periodEnd": [
- 4
- ],
- "userWorkspaceId": [
- 1
- ],
- "operationTypes": [
- 77
- ],
- "__typename": [
- 1
- ]
- },
"Mutation": {
"addQueryToEventStream": [
8,
@@ -8649,7 +8649,7 @@ export default {
10,
{
"input": [
- 380,
+ 381,
"AgentIdInput!"
]
}
@@ -8682,7 +8682,7 @@ export default {
}
],
"createOneIndex": [
- 242,
+ 245,
{
"input": [
459,
@@ -8691,7 +8691,7 @@ export default {
}
],
"deleteOneIndex": [
- 242,
+ 245,
{
"input": [
462,
@@ -8703,7 +8703,7 @@ export default {
21,
{
"input": [
- 382,
+ 383,
"LogicFunctionIdInput!"
]
}
@@ -8820,10 +8820,10 @@ export default {
68
],
"checkCustomDomainValidRecords": [
- 254
+ 257
],
"enrichWorkspaceCompany": [
- 231
+ 234
],
"upgradeApplication": [
8,
@@ -8839,7 +8839,7 @@ export default {
}
],
"createApplicationRegistration": [
- 211,
+ 214,
{
"input": [
474,
@@ -8866,7 +8866,7 @@ export default {
}
],
"rotateApplicationRegistrationClientSecret": [
- 213,
+ 216,
{
"id": [
1,
@@ -8875,7 +8875,7 @@ export default {
}
],
"createApplicationRegistrationVariable": [
- 184,
+ 188,
{
"input": [
477,
@@ -8884,7 +8884,7 @@ export default {
}
],
"updateApplicationRegistrationVariable": [
- 184,
+ 188,
{
"input": [
478,
@@ -8985,7 +8985,7 @@ export default {
8
],
"createOneField": [
- 234,
+ 237,
{
"input": [
481,
@@ -8994,7 +8994,7 @@ export default {
}
],
"updateOneField": [
- 234,
+ 237,
{
"input": [
483,
@@ -9003,7 +9003,7 @@ export default {
}
],
"deleteOneField": [
- 234,
+ 237,
{
"input": [
485,
@@ -9133,7 +9133,7 @@ export default {
}
],
"upsertRowLevelPermissionPredicates": [
- 255,
+ 258,
{
"input": [
499,
@@ -9612,7 +9612,7 @@ export default {
}
],
"getAuthorizationUrlForSSO": [
- 264,
+ 267,
{
"input": [
532,
@@ -9621,7 +9621,7 @@ export default {
}
],
"getLoginTokenFromCredentials": [
- 275,
+ 278,
{
"email": [
1,
@@ -9647,7 +9647,7 @@ export default {
}
],
"signIn": [
- 262,
+ 265,
{
"email": [
1,
@@ -9669,7 +9669,7 @@ export default {
}
],
"verifyEmailAndGetLoginToken": [
- 270,
+ 273,
{
"emailVerificationToken": [
1,
@@ -9689,7 +9689,7 @@ export default {
}
],
"verifyEmailAndGetWorkspaceAgnosticToken": [
- 262,
+ 265,
{
"emailVerificationToken": [
1,
@@ -9705,7 +9705,7 @@ export default {
}
],
"getAuthTokensFromOTP": [
- 274,
+ 277,
{
"otp": [
1,
@@ -9725,7 +9725,7 @@ export default {
}
],
"signUp": [
- 262,
+ 265,
{
"email": [
1,
@@ -9747,7 +9747,7 @@ export default {
}
],
"signUpInWorkspace": [
- 267,
+ 270,
{
"email": [
1,
@@ -9778,7 +9778,7 @@ export default {
}
],
"signUpInNewWorkspace": [
- 267,
+ 270,
{
"input": [
533
@@ -9799,10 +9799,10 @@ export default {
}
],
"generateTransientToken": [
- 268
+ 271
],
"getAuthTokensFromLoginToken": [
- 274,
+ 277,
{
"loginToken": [
1,
@@ -9815,7 +9815,7 @@ export default {
}
],
"getAuthTokensFromSSOExchangeToken": [
- 274,
+ 277,
{
"ssoExchangeToken": [
1,
@@ -9824,7 +9824,7 @@ export default {
}
],
"authorizeApp": [
- 260,
+ 263,
{
"clientId": [
1,
@@ -9849,7 +9849,7 @@ export default {
}
],
"renewToken": [
- 274,
+ 277,
{
"appToken": [
1,
@@ -9866,7 +9866,7 @@ export default {
}
],
"generateApiKeyToken": [
- 273,
+ 276,
{
"apiKeyId": [
3,
@@ -9882,7 +9882,7 @@ export default {
11
],
"emailPasswordResetLink": [
- 263,
+ 266,
{
"email": [
1,
@@ -9897,7 +9897,7 @@ export default {
}
],
"updatePasswordViaResetToken": [
- 265,
+ 268,
{
"passwordResetToken": [
1,
@@ -9910,7 +9910,7 @@ export default {
}
],
"initiateOTPProvisioning": [
- 258,
+ 261,
{
"loginToken": [
1,
@@ -9923,10 +9923,10 @@ export default {
}
],
"initiateOTPProvisioningForAuthenticatedUser": [
- 258
+ 261
],
"deleteTwoFactorAuthenticationMethod": [
- 257,
+ 260,
{
"twoFactorAuthenticationMethodId": [
3,
@@ -9935,7 +9935,7 @@ export default {
}
],
"verifyTwoFactorAuthenticationMethodForAuthenticatedUser": [
- 259,
+ 262,
{
"otp": [
1,
@@ -9977,7 +9977,7 @@ export default {
}
],
"resendEmailVerificationToken": [
- 216,
+ 219,
{
"email": [
1,
@@ -9990,7 +9990,7 @@ export default {
}
],
"createOIDCIdentityProvider": [
- 221,
+ 224,
{
"input": [
535,
@@ -9999,7 +9999,7 @@ export default {
}
],
"createSAMLIdentityProvider": [
- 221,
+ 224,
{
"input": [
536,
@@ -10008,7 +10008,7 @@ export default {
}
],
"deleteSSOIdentityProvider": [
- 217,
+ 220,
{
"input": [
537,
@@ -10017,7 +10017,7 @@ export default {
}
],
"editSSOIdentityProvider": [
- 218,
+ 221,
{
"input": [
538,
@@ -10073,7 +10073,7 @@ export default {
}
],
"impersonate": [
- 278,
+ 281,
{
"userId": [
3,
@@ -10086,7 +10086,7 @@ export default {
}
],
"stopImpersonation": [
- 279
+ 282
],
"createCalendarEvent": [
329,
@@ -10132,7 +10132,7 @@ export default {
}
],
"updateLabPublicFeatureFlag": [
- 181,
+ 185,
{
"input": [
545,
@@ -10163,7 +10163,7 @@ export default {
}
],
"checkPublicDomainValidRecords": [
- 254,
+ 257,
{
"domain": [
1,
@@ -11528,7 +11528,7 @@ export default {
461
],
"indexType": [
- 243
+ 246
],
"__typename": [
1
@@ -11989,7 +11989,7 @@ export default {
},
"CreateFieldInput": {
"type": [
- 235
+ 238
],
"name": [
1
@@ -12955,7 +12955,7 @@ export default {
3
],
"status": [
- 190
+ 194
],
"__typename": [
1
@@ -13119,7 +13119,7 @@ export default {
}
],
"logicFunctionLogs": [
- 256,
+ 259,
{
"input": [
548,
@@ -13140,7 +13140,7 @@ export default {
340,
{
"table": [
- 388,
+ 389,
"EventLogTable!"
]
}
diff --git a/packages/twenty-server/src/app.module.ts b/packages/twenty-server/src/app.module.ts
index 8f477254621..5674b526098 100644
--- a/packages/twenty-server/src/app.module.ts
+++ b/packages/twenty-server/src/app.module.ts
@@ -27,6 +27,7 @@ import { WorkspaceAuthContextMiddleware } from 'src/engine/core-modules/auth/mid
import { MetricsModule } from 'src/engine/core-modules/metrics/metrics.module';
import { DataloaderModule } from 'src/engine/dataloaders/dataloader.module';
import { WorkspaceMetadataVersionModule } from 'src/engine/metadata-modules/workspace-metadata-version/workspace-metadata-version.module';
+import { ApiRequestContextMiddleware } from 'src/engine/core-modules/usage/middlewares/api-request-context.middleware';
import { CookieSessionCsrfMiddleware } from 'src/engine/middlewares/cookie-session-csrf.middleware';
import { GraphQLHydrateRequestFromTokenMiddleware } from 'src/engine/middlewares/graphql-hydrate-request-from-token.middleware';
import { MiddlewareModule } from 'src/engine/middlewares/middleware.module';
@@ -118,6 +119,7 @@ export class AppModule {
consumer
.apply(
+ ApiRequestContextMiddleware,
GraphQLHydrateRequestFromTokenMiddleware,
WorkspaceAuthContextMiddleware,
)
@@ -138,12 +140,16 @@ export class AppModule {
.forRoutes({ path: ApiPath.AdminPanel, method: RequestMethod.ALL });
consumer
- .apply(McpMethodGuardMiddleware)
+ .apply(ApiRequestContextMiddleware, McpMethodGuardMiddleware)
.forRoutes({ path: ApiPath.Mcp, method: RequestMethod.ALL });
for (const method of MIGRATED_REST_METHODS) {
consumer
- .apply(RestCoreMiddleware, WorkspaceAuthContextMiddleware)
+ .apply(
+ ApiRequestContextMiddleware,
+ RestCoreMiddleware,
+ WorkspaceAuthContextMiddleware,
+ )
.forRoutes({ path: `${ApiPath.Rest}/*path`, method });
}
}
diff --git a/packages/twenty-server/src/database/clickhouse/migrations/007-add-spender-columns-to-usage-event.sql b/packages/twenty-server/src/database/clickhouse/migrations/007-add-spender-columns-to-usage-event.sql
new file mode 100644
index 00000000000..7579afa22e6
--- /dev/null
+++ b/packages/twenty-server/src/database/clickhouse/migrations/007-add-spender-columns-to-usage-event.sql
@@ -0,0 +1,10 @@
+ALTER TABLE usageEvent ADD COLUMN IF NOT EXISTS apiKeyId String DEFAULT '';
+
+ALTER TABLE usageEvent ADD COLUMN IF NOT EXISTS applicationId String DEFAULT '';
+
+ALTER TABLE usageEvent ADD COLUMN IF NOT EXISTS agentId String DEFAULT '';
+
+ALTER TABLE usageEvent ADD COLUMN IF NOT EXISTS workflowId String DEFAULT '';
+
+ALTER TABLE usageEvent ADD COLUMN IF NOT EXISTS logicFunctionId String DEFAULT '';
+
diff --git a/packages/twenty-server/src/engine/api/common/common-query-runners/common-base-query-runner.service.ts b/packages/twenty-server/src/engine/api/common/common-query-runners/common-base-query-runner.service.ts
index 2cf7a4dcd62..a3ecfd427c9 100644
--- a/packages/twenty-server/src/engine/api/common/common-query-runners/common-base-query-runner.service.ts
+++ b/packages/twenty-server/src/engine/api/common/common-query-runners/common-base-query-runner.service.ts
@@ -61,6 +61,10 @@ import { UsageLimitSpeedService } from 'src/engine/core-modules/usage-limit/serv
import { type ExhaustedScope } from 'src/engine/core-modules/usage-limit/types/exhausted-scope.type';
import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
+import { UsageRecorderService } from 'src/engine/core-modules/usage/services/usage-recorder.service';
+import { getApiType } from 'src/engine/core-modules/usage/storage/api-request-context.storage';
+import { buildUsageSpendersFromAuthContext } from 'src/engine/core-modules/usage/utils/build-usage-spenders-from-auth-context.util';
import { FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';
import { findFlatEntityByIdInFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps.util';
import { type OrmFlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/orm-flat-field-metadata.type';
@@ -73,11 +77,11 @@ import {
} from 'src/engine/metadata-modules/permissions/permissions.exception';
import { PermissionsService } from 'src/engine/metadata-modules/permissions/permissions.service';
import { RelationNestedQueries } from 'src/engine/twenty-orm/field-operations/relation-nested-queries/relation-nested-queries';
-import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
-import { getWorkspaceContext } from 'src/engine/twenty-orm/storage/orm-workspace-context.storage';
-import { resolveRolePermissionConfig } from 'src/engine/twenty-orm/utils/resolve-role-permission-config.util';
import { type WorkspaceRepository } from 'src/engine/twenty-orm/repository/workspace-repository';
import { type MutationKind } from 'src/engine/twenty-orm/sql/utils/build-mutation-statement.util';
+import { getWorkspaceContext } from 'src/engine/twenty-orm/storage/orm-workspace-context.storage';
+import { resolveRolePermissionConfig } from 'src/engine/twenty-orm/utils/resolve-role-permission-config.util';
+import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
@Injectable()
@@ -114,6 +118,8 @@ export abstract class CommonBaseQueryRunnerService<
@Inject()
protected readonly usageLimitSpeedService: UsageLimitSpeedService;
@Inject()
+ protected readonly usageRecorderService: UsageRecorderService;
+ @Inject()
protected readonly twentyConfigService: TwentyConfigService;
@Inject()
protected readonly metricsService: MetricsService;
@@ -137,6 +143,8 @@ export abstract class CommonBaseQueryRunnerService<
await this.throttleQueryExecution(authContext);
+ this.recordApiUsage(authContext);
+
await this.validate(args, queryRunnerContext);
if (flatObjectMetadata.isSystem === true) {
@@ -535,6 +543,29 @@ export abstract class CommonBaseQueryRunnerService<
};
}
+ private recordApiUsage(authContext: WorkspaceAuthContext) {
+ const apiType = getApiType();
+
+ if (!isDefined(apiType)) {
+ return;
+ }
+
+ const spenders = buildUsageSpendersFromAuthContext(authContext);
+
+ if (!isDefined(spenders.apiKeyId) && !isDefined(spenders.applicationId)) {
+ return;
+ }
+
+ this.usageRecorderService.accumulate(authContext.workspace.id, {
+ resourceType: UsageResourceType.API,
+ operationType: UsageOperationType.API_REQUEST,
+ quantity: 1,
+ unit: UsageUnit.REQUEST,
+ resourceContext: apiType,
+ spenders,
+ });
+ }
+
private async throttleQueryExecution(authContext: WorkspaceAuthContext) {
const isApiRateLimitV2Enabled =
await this.featureFlagService.isFeatureEnabled(
diff --git a/packages/twenty-server/src/engine/api/common/core-common-api.module.ts b/packages/twenty-server/src/engine/api/common/core-common-api.module.ts
index 3de72860db9..f684c8de448 100644
--- a/packages/twenty-server/src/engine/api/common/core-common-api.module.ts
+++ b/packages/twenty-server/src/engine/api/common/core-common-api.module.ts
@@ -18,6 +18,7 @@ import { RecordPositionModule } from 'src/engine/core-modules/record-position/re
import { RecordTransformerModule } from 'src/engine/core-modules/record-transformer/record-transformer.module';
import { ThrottlerModule } from 'src/engine/core-modules/throttler/throttler.module';
import { UsageLimitModule } from 'src/engine/core-modules/usage-limit/usage-limit.module';
+import { UsageModule } from 'src/engine/core-modules/usage/usage.module';
import { WorkspaceManyOrAllFlatEntityMapsCacheModule } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.module';
import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permissions.module';
import { RoleTargetEntity } from 'src/engine/metadata-modules/role-target/role-target.entity';
@@ -41,6 +42,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
ViewFilterGroupModule,
ThrottlerModule,
UsageLimitModule,
+ UsageModule,
MetricsModule,
RecordPositionModule,
RecordTransformerModule,
diff --git a/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.module.ts b/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.module.ts
index 4ecca85156e..f549c8b2902 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.module.ts
@@ -8,6 +8,7 @@ import { AuthModule } from 'src/engine/core-modules/auth/auth.module';
import { BillingModule } from 'src/engine/core-modules/billing/billing.module';
import { ThrottlerModule } from 'src/engine/core-modules/throttler/throttler.module';
import { TwentyConfigModule } from 'src/engine/core-modules/twenty-config/twenty-config.module';
+import { UsageModule } from 'src/engine/core-modules/usage/usage.module';
import { WorkspaceCacheStorageModule } from 'src/engine/workspace-cache-storage/workspace-cache-storage.module';
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
import { WorkspaceEventEmitterModule } from 'src/engine/workspace-event-emitter/workspace-event-emitter.module';
@@ -18,6 +19,7 @@ import { WorkspaceEventEmitterModule } from 'src/engine/workspace-event-emitter/
BillingModule,
ThrottlerModule,
TwentyConfigModule,
+ UsageModule,
WorkspaceCacheModule,
WorkspaceCacheStorageModule,
WorkspaceEventEmitterModule,
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 b311119d155..e54d9b2f9db 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.service.ts
@@ -3,15 +3,10 @@
import { Injectable, Logger } from '@nestjs/common';
import { type ChargeDto } from 'src/engine/core-modules/billing/app-billing/dtos/charge.dto';
-import { NO_BILLING_SUBSCRIPTION } from 'src/engine/core-modules/billing/constants/no-billing-subscription.constant';
-import { BillingService } from 'src/engine/core-modules/billing/services/billing.service';
-import { USAGE_RECORDED } from 'src/engine/core-modules/usage/constants/usage-recorded.constant';
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 { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
-import { type UsageEvent } from 'src/engine/core-modules/usage/types/usage-event.type';
-import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
-import { WorkspaceEventEmitter } from 'src/engine/workspace-event-emitter/workspace-event-emitter';
+import { UsageRecorderService } from 'src/engine/core-modules/usage/services/usage-recorder.service';
// Each operation type has one canonical counting unit — matches how
// `ai-billing.service.ts` emits native usage events.
@@ -33,11 +28,7 @@ const USAGE_UNIT_BY_OPERATION_TYPE: Record<UsageOperationType, UsageUnit> = {
export class AppBillingService {
private readonly logger = new Logger(AppBillingService.name);
- constructor(
- private readonly workspaceEventEmitter: WorkspaceEventEmitter,
- private readonly billingService: BillingService,
- private readonly workspaceCacheService: WorkspaceCacheService,
- ) {}
+ constructor(private readonly usageRecorderService: UsageRecorderService) {}
async emitChargeEvent(params: {
workspaceId: string;
@@ -53,36 +44,17 @@ export class AppBillingService {
`${charge.creditsUsedMicro} micro-credits (${charge.quantity} ${unit}, ${charge.operationType})`,
);
- let periodStart: Date | undefined;
-
- if (this.billingService.isBillingEnabled()) {
- const { currentBillingSubscription } =
- await this.workspaceCacheService.getOrRecompute(workspaceId, [
- 'currentBillingSubscription',
- ]);
-
- periodStart =
- currentBillingSubscription === NO_BILLING_SUBSCRIPTION
- ? undefined
- : currentBillingSubscription.currentPeriodStart;
- }
-
- this.workspaceEventEmitter.emitCustomBatchEvent<UsageEvent>(
- USAGE_RECORDED,
- [
- {
- resourceType: UsageResourceType.APP,
- operationType: charge.operationType,
- creditsUsedMicro: charge.creditsUsedMicro,
- quantity: charge.quantity,
- unit,
- resourceId: applicationId,
- resourceContext: charge.resourceContext ?? null,
- userWorkspaceId: userWorkspaceId ?? null,
- periodStart,
- },
- ],
- workspaceId,
- );
+ await this.usageRecorderService.record(workspaceId, [
+ {
+ resourceType: UsageResourceType.APP,
+ operationType: charge.operationType,
+ creditsUsedMicro: charge.creditsUsedMicro,
+ quantity: charge.quantity,
+ unit,
+ resourceId: applicationId,
+ resourceContext: charge.resourceContext ?? null,
+ spenders: { userWorkspaceId, applicationId },
+ },
+ ]);
}
}
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.module.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.module.ts
index 45461347327..b65b1947dd9 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.module.ts
@@ -13,6 +13,7 @@ import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-
import { LogicFunctionExecutorService } from 'src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service';
import { SecretEncryptionModule } from 'src/engine/core-modules/secret-encryption/secret-encryption.module';
import { ThrottlerModule } from 'src/engine/core-modules/throttler/throttler.module';
+import { UsageModule } from 'src/engine/core-modules/usage/usage.module';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { SubscriptionsModule } from 'src/engine/subscriptions/subscriptions.module';
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
@@ -31,6 +32,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
WorkspaceDomainsModule,
ApplicationModule,
ApplicationVariableEntityModule,
+ UsageModule,
TypeOrmModule.forFeature([
ApplicationRegistrationVariableEntity,
WorkspaceEntity,
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts
index ff7b864dcb8..aa9ea9dc0c4 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts
@@ -23,33 +23,35 @@ import {
type LogicFunctionTranspileResult,
} from 'src/engine/core-modules/logic-function/logic-function-drivers/interfaces/logic-function-driver.interface';
-import { buildApplicationLogEnvelopes } from 'src/engine/core-modules/event-logs/producers/application-log/build-application-log-envelopes';
-import { parseApplicationLogLines } from 'src/engine/core-modules/event-logs/producers/application-log/parse-application-log-lines';
+import { isBillingExemptApplication } from 'src/engine/core-modules/application/application-marketplace/utils/is-billing-exempt-application.util';
import { ApplicationRegistrationVariableEntity } from 'src/engine/core-modules/application/application-registration-variable/application-registration-variable.entity';
import { ApplicationStopService } from 'src/engine/core-modules/application/application-stop/application-stop.service';
-import { ApplicationService } from 'src/engine/core-modules/application/application.service';
-import { FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
-import { EventLogEmitterService } from 'src/engine/core-modules/event-logs/emit/event-log-emitter.service';
-import { LOGIC_FUNCTION_EXECUTED_EVENT } from 'src/engine/core-modules/event-logs/emit/events/workspace-event/logic-function/logic-function-executed';
import { ApplicationVariableEntityService } from 'src/engine/core-modules/application/application-variable/application-variable.service';
import { type ApplicationVariableCacheMaps } from 'src/engine/core-modules/application/application-variable/types/application-variable-cache-maps.type';
-import { isBillingExemptApplication } from 'src/engine/core-modules/application/application-marketplace/utils/is-billing-exempt-application.util';
+import { ApplicationService } from 'src/engine/core-modules/application/application.service';
+import { FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
import { ApplicationTokenService } from 'src/engine/core-modules/auth/token/services/application-token.service';
import { NO_BILLING_SUBSCRIPTION } from 'src/engine/core-modules/billing/constants/no-billing-subscription.constant';
import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';
import { BillingService } from 'src/engine/core-modules/billing/services/billing.service';
import { WorkspaceDomainsService } from 'src/engine/core-modules/domain/workspace-domains/services/workspace-domains.service';
+import { EventLogEmitterService } from 'src/engine/core-modules/event-logs/emit/event-log-emitter.service';
+import { LOGIC_FUNCTION_EXECUTED_EVENT } from 'src/engine/core-modules/event-logs/emit/events/workspace-event/logic-function/logic-function-executed';
+import { EventLogLiveService } from 'src/engine/core-modules/event-logs/live/event-log-live.service';
+import { buildApplicationLogEnvelopes } from 'src/engine/core-modules/event-logs/producers/application-log/build-application-log-envelopes';
+import { parseApplicationLogLines } from 'src/engine/core-modules/event-logs/producers/application-log/parse-application-log-lines';
import { FeatureFlagService } from 'src/engine/core-modules/feature-flag/services/feature-flag.service';
import { LogicFunctionDriverFactory } from 'src/engine/core-modules/logic-function/logic-function-drivers/logic-function-driver.factory';
import { computeLogicFunctionExecutionCreditsMicro } from 'src/engine/core-modules/logic-function/logic-function-executor/utils/compute-logic-function-execution-credits-micro.util';
+import { resolveWorkspaceMemberIdForUser } from 'src/engine/core-modules/logic-function/logic-function-executor/utils/resolve-workspace-member-id-for-user.util';
import { SecretEncryptionService } from 'src/engine/core-modules/secret-encryption/secret-encryption.service';
import { ThrottlerService } from 'src/engine/core-modules/throttler/throttler.service';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
-import { USAGE_RECORDED } from 'src/engine/core-modules/usage/constants/usage-recorded.constant';
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 { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
-import { type UsageEvent } from 'src/engine/core-modules/usage/types/usage-event.type';
+import { UsageRecorderService } from 'src/engine/core-modules/usage/services/usage-recorder.service';
+import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { findFlatEntityByIdInFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps.util';
import { LogicFunctionExecutionMode } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
import {
@@ -59,11 +61,7 @@ import {
import { FlatLogicFunction } from 'src/engine/metadata-modules/logic-function/types/flat-logic-function.type';
import { SubscriptionChannel } from 'src/engine/subscriptions/enums/subscription-channel.enum';
import { SubscriptionService } from 'src/engine/subscriptions/subscription.service';
-import { EventLogLiveService } from 'src/engine/core-modules/event-logs/live/event-log-live.service';
-import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
-import { WorkspaceEventEmitter } from 'src/engine/workspace-event-emitter/workspace-event-emitter';
-import { resolveWorkspaceMemberIdForUser } from 'src/engine/core-modules/logic-function/logic-function-executor/utils/resolve-workspace-member-id-for-user.util';
import { cleanServerUrl } from 'src/utils/clean-server-url';
export class LogicFunctionExecutionException extends Error {
@@ -96,7 +94,7 @@ export class LogicFunctionExecutorService {
private readonly subscriptionService: SubscriptionService,
private readonly eventLogLiveService: EventLogLiveService,
private readonly eventLogEmitterService: EventLogEmitterService,
- private readonly workspaceEventEmitter: WorkspaceEventEmitter,
+ private readonly usageRecorderService: UsageRecorderService,
private readonly billingService: BillingService,
private readonly billingUsageService: BillingUsageService,
private readonly featureFlagService: FeatureFlagService,
@@ -633,49 +631,47 @@ export class LogicFunctionExecutorService {
const totalCreditsMicro = invocationCreditsMicro + durationCreditsMicro;
- let periodStart: Date | undefined;
-
if (this.billingService.isBillingEnabled()) {
const { currentBillingSubscription } =
await this.workspaceCacheService.getOrRecompute(workspaceId, [
'currentBillingSubscription',
]);
- if (currentBillingSubscription !== NO_BILLING_SUBSCRIPTION) {
- periodStart = currentBillingSubscription.currentPeriodStart;
-
- if (totalCreditsMicro > 0) {
- await this.billingUsageService.decrementAvailableCreditsInCache({
- workspaceId,
- usedCredits: totalCreditsMicro,
- });
- }
+ if (
+ currentBillingSubscription !== NO_BILLING_SUBSCRIPTION &&
+ totalCreditsMicro > 0
+ ) {
+ await this.billingUsageService.decrementAvailableCreditsInCache({
+ workspaceId,
+ usedCredits: totalCreditsMicro,
+ });
}
}
- this.workspaceEventEmitter.emitCustomBatchEvent<UsageEvent>(
- USAGE_RECORDED,
- [
- {
- resourceType: UsageResourceType.LOGIC_FUNCTION,
- operationType: UsageOperationType.CODE_EXECUTION,
- creditsUsedMicro: invocationCreditsMicro,
- quantity: 1,
- unit: UsageUnit.INVOCATION,
- resourceId: flatLogicFunction.id,
- periodStart,
- },
- {
- resourceType: UsageResourceType.LOGIC_FUNCTION,
- operationType: UsageOperationType.CODE_EXECUTION,
- creditsUsedMicro: durationCreditsMicro,
- quantity: billedDurationMs,
- unit: UsageUnit.MILLISECOND,
- resourceId: flatLogicFunction.id,
- periodStart,
- },
- ],
- workspaceId,
- );
+ const spenders = {
+ logicFunctionId: flatLogicFunction.id,
+ applicationId: flatApplication.id,
+ };
+
+ await this.usageRecorderService.record(workspaceId, [
+ {
+ resourceType: UsageResourceType.LOGIC_FUNCTION,
+ operationType: UsageOperationType.CODE_EXECUTION,
+ creditsUsedMicro: invocationCreditsMicro,
+ quantity: 1,
+ unit: UsageUnit.INVOCATION,
+ resourceId: flatLogicFunction.id,
+ spenders,
+ },
+ {
+ resourceType: UsageResourceType.LOGIC_FUNCTION,
+ operationType: UsageOperationType.CODE_EXECUTION,
+ creditsUsedMicro: durationCreditsMicro,
+ quantity: billedDurationMs,
+ unit: UsageUnit.MILLISECOND,
+ resourceId: flatLogicFunction.id,
+ spenders,
+ },
+ ]);
}
}
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 0ec81f11854..ba0be739a86 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
@@ -868,6 +868,16 @@ export class ConfigVariables {
@ValidateIf((env) => env.ANALYTICS_ENABLED === true)
CLICKHOUSE_URL: string;
+ @ConfigVariablesMetadata({
+ group: ConfigVariablesGroup.ANALYTICS_CONFIG,
+ description:
+ 'Interval in milliseconds between two flushes of the buffered usage rollups',
+ type: ConfigVariableType.NUMBER,
+ })
+ @IsOptional()
+ @CastToPositiveNumber()
+ USAGE_ROLLUP_FLUSH_INTERVAL_MS = 60_000;
+
@ConfigVariablesMetadata({
group: ConfigVariablesGroup.LOGGING,
description: 'Enable or disable telemetry logging',
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-spenders-from-auth-context.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-spenders-from-auth-context.util.ts
index 2f24cb5ff8d..dc53f0ab354 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-spenders-from-auth-context.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-spenders-from-auth-context.util.ts
@@ -1,39 +1,27 @@
import { isDefined } from 'twenty-shared/utils';
-import { isApiKeyAuthContext } from 'src/engine/core-modules/auth/guards/is-api-key-auth-context.guard';
-import { isApplicationAuthContext } from 'src/engine/core-modules/auth/guards/is-application-auth-context.guard';
-import { isUserAuthContext } from 'src/engine/core-modules/auth/guards/is-user-auth-context.guard';
import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
import { type Spender } from 'src/engine/core-modules/usage-limit/types/spender.type';
+import { buildUsageSpendersFromAuthContext } from 'src/engine/core-modules/usage/utils/build-usage-spenders-from-auth-context.util';
export const buildSpendersFromAuthContext = (
authContext: WorkspaceAuthContext,
): Spender[] => {
+ const { userWorkspaceId, apiKeyId, applicationId } =
+ buildUsageSpendersFromAuthContext(authContext);
+
const spenders: Spender[] = [];
- if (isApiKeyAuthContext(authContext)) {
- spenders.push({ spenderType: 'apiKey', spenderId: authContext.apiKey.id });
+ if (isDefined(userWorkspaceId)) {
+ spenders.push({ spenderType: 'userWorkspace', spenderId: userWorkspaceId });
}
- if (isApplicationAuthContext(authContext)) {
- spenders.push({
- spenderType: 'application',
- spenderId: authContext.application.id,
- });
+ if (isDefined(apiKeyId)) {
+ spenders.push({ spenderType: 'apiKey', spenderId: apiKeyId });
}
- if (isUserAuthContext(authContext)) {
- spenders.push({
- spenderType: 'userWorkspace',
- spenderId: authContext.userWorkspaceId,
- });
-
- const applicationId =
- authContext.application?.id ?? authContext.viaApplication?.id;
-
- if (isDefined(applicationId)) {
- spenders.push({ spenderType: 'application', spenderId: applicationId });
- }
+ if (isDefined(applicationId)) {
+ spenders.push({ spenderType: 'application', spenderId: applicationId });
}
spenders.push({ spenderType: 'workspace', spenderId: '' });
diff --git a/packages/twenty-server/src/engine/core-modules/usage/constants/api-types.constant.ts b/packages/twenty-server/src/engine/core-modules/usage/constants/api-types.constant.ts
new file mode 100644
index 00000000000..56ffe999da0
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage/constants/api-types.constant.ts
@@ -0,0 +1,11 @@
+/* @license Enterprise */
+
+import { ApiPath } from 'twenty-shared/types';
+
+import { type ApiType } from 'src/engine/core-modules/usage/types/api-type.type';
+
+export const API_TYPE_BY_PATH_PREFIX: Record<string, ApiType> = {
+ [ApiPath.GraphQL]: 'CORE_GQL',
+ [ApiPath.Rest]: 'CORE_REST',
+ [ApiPath.Mcp]: 'MCP',
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage/middlewares/api-request-context.middleware.ts b/packages/twenty-server/src/engine/core-modules/usage/middlewares/api-request-context.middleware.ts
new file mode 100644
index 00000000000..a7a15352db5
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage/middlewares/api-request-context.middleware.ts
@@ -0,0 +1,27 @@
+/* @license Enterprise */
+
+import { Injectable, type NestMiddleware } from '@nestjs/common';
+
+import { type NextFunction, type Request, type Response } from 'express';
+import { isDefined } from 'twenty-shared/utils';
+
+import { withApiRequestContext } from 'src/engine/core-modules/usage/storage/api-request-context.storage';
+import { getApiTypeFromPath } from 'src/engine/core-modules/usage/utils/get-api-type-from-path.util';
+
+@Injectable()
+export class ApiRequestContextMiddleware implements NestMiddleware {
+ use(req: Request, _res: Response, next: NextFunction) {
+ const [path] = req.originalUrl.split('?');
+ const apiType = getApiTypeFromPath(path);
+
+ if (!isDefined(apiType)) {
+ next();
+
+ return;
+ }
+
+ void withApiRequestContext(apiType, () => {
+ next();
+ });
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/usage/services/__tests__/usage-recorder.service.spec.ts b/packages/twenty-server/src/engine/core-modules/usage/services/__tests__/usage-recorder.service.spec.ts
new file mode 100644
index 00000000000..9b827d2e209
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage/services/__tests__/usage-recorder.service.spec.ts
@@ -0,0 +1,98 @@
+import { Logger } from '@nestjs/common';
+import { Test, type TestingModule } from '@nestjs/testing';
+
+import { EventLogEmitterService } from 'src/engine/core-modules/event-logs/emit/event-log-emitter.service';
+import {
+ type UsageEventRow,
+ type WorkspaceEventEnvelope,
+} from 'src/engine/core-modules/event-logs/types/workspace-event-envelope.type';
+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
+import { UsageRecorderService } from 'src/engine/core-modules/usage/services/usage-recorder.service';
+import { type RecordUsageInput } from 'src/engine/core-modules/usage/types/record-usage-input.type';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+import { WorkspaceEventEmitter } from 'src/engine/workspace-event-emitter/workspace-event-emitter';
+
+const API_REQUEST: RecordUsageInput = {
+ resourceType: UsageResourceType.API,
+ operationType: UsageOperationType.API_REQUEST,
+ quantity: 1,
+ unit: UsageUnit.REQUEST,
+};
+
+describe('UsageRecorderService', () => {
+ let recorder: UsageRecorderService;
+ let dispatch: jest.Mock;
+
+ const dispatchedRows = (): UsageEventRow[] =>
+ dispatch.mock.calls
+ .flatMap((call) => call[0] as WorkspaceEventEnvelope[])
+ .map((envelope) => envelope.row as UsageEventRow);
+
+ beforeEach(async () => {
+ jest.spyOn(Logger.prototype, 'warn').mockImplementation();
+ jest.spyOn(Logger.prototype, 'error').mockImplementation();
+
+ dispatch = jest.fn().mockResolvedValue(undefined);
+
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [
+ UsageRecorderService,
+ {
+ provide: EventLogEmitterService,
+ useValue: { dispatch, isEnabled: jest.fn().mockReturnValue(true) },
+ },
+ {
+ provide: WorkspaceEventEmitter,
+ useValue: { emitCustomBatchEvent: jest.fn() },
+ },
+ {
+ provide: WorkspaceCacheService,
+ useValue: { getOrRecompute: jest.fn() },
+ },
+ {
+ provide: TwentyConfigService,
+ useValue: { get: jest.fn().mockReturnValue(false) },
+ },
+ ],
+ }).compile();
+
+ recorder = module.get<UsageRecorderService>(UsageRecorderService);
+ });
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ it('dispatches one aggregated batch per workspace on shutdown', async () => {
+ recorder.accumulate('ws-1', API_REQUEST);
+ recorder.accumulate('ws-1', API_REQUEST);
+ recorder.accumulate('ws-2', API_REQUEST);
+
+ await recorder.onModuleDestroy();
+
+ expect(dispatch).toHaveBeenCalledTimes(2);
+ expect(dispatchedRows()).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ workspaceId: 'ws-1', quantity: 2 }),
+ expect.objectContaining({ workspaceId: 'ws-2', quantity: 1 }),
+ ]),
+ );
+ });
+
+ it('re-buffers the counts of a failed dispatch instead of dropping them', async () => {
+ dispatch.mockRejectedValueOnce(new Error('clickhouse unreachable'));
+ recorder.accumulate('ws-1', API_REQUEST);
+
+ await recorder.onModuleDestroy();
+
+ recorder.accumulate('ws-1', API_REQUEST);
+ await recorder.onModuleDestroy();
+
+ expect(dispatchedRows()).toContainEqual(
+ expect.objectContaining({ workspaceId: 'ws-1', quantity: 2 }),
+ );
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage/services/usage-recorder.service.ts b/packages/twenty-server/src/engine/core-modules/usage/services/usage-recorder.service.ts
new file mode 100644
index 00000000000..73ce779ef75
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage/services/usage-recorder.service.ts
@@ -0,0 +1,169 @@
+/* @license Enterprise */
+
+import {
+ Injectable,
+ Logger,
+ type OnModuleDestroy,
+ type OnModuleInit,
+} from '@nestjs/common';
+
+import { isDefined } from 'twenty-shared/utils';
+
+import { NO_BILLING_SUBSCRIPTION } from 'src/engine/core-modules/billing/constants/no-billing-subscription.constant';
+import { EventLogEmitterService } from 'src/engine/core-modules/event-logs/emit/event-log-emitter.service';
+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
+import { USAGE_RECORDED } from 'src/engine/core-modules/usage/constants/usage-recorded.constant';
+import { type RecordUsageInput } from 'src/engine/core-modules/usage/types/record-usage-input.type';
+import { type UsageEvent } from 'src/engine/core-modules/usage/types/usage-event.type';
+import { buildUsageEventEnvelopes } from 'src/engine/core-modules/usage/utils/build-usage-event-envelopes';
+import { UsageRollupBuffer } from 'src/engine/core-modules/usage/utils/usage-rollup-buffer';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+import { WorkspaceEventEmitter } from 'src/engine/workspace-event-emitter/workspace-event-emitter';
+
+const MAX_BUFFERED_ROLLUPS = 10_000;
+
+@Injectable()
+export class UsageRecorderService implements OnModuleInit, OnModuleDestroy {
+ private readonly logger = new Logger(UsageRecorderService.name);
+ private readonly buffer = new UsageRollupBuffer(MAX_BUFFERED_ROLLUPS);
+ private flushTimer: NodeJS.Timeout | null = null;
+ private pendingFlush: Promise<void> = Promise.resolve();
+
+ constructor(
+ private readonly workspaceEventEmitter: WorkspaceEventEmitter,
+ private readonly eventLogEmitterService: EventLogEmitterService,
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ private readonly twentyConfigService: TwentyConfigService,
+ ) {}
+
+ onModuleInit() {
+ this.flushTimer = setInterval(
+ () => void this.flush(),
+ this.twentyConfigService.get('USAGE_ROLLUP_FLUSH_INTERVAL_MS'),
+ );
+
+ this.flushTimer.unref();
+ }
+
+ async onModuleDestroy() {
+ await this.flushAndStop();
+ }
+
+ async flushAndStop(): Promise<void> {
+ if (isDefined(this.flushTimer)) {
+ clearInterval(this.flushTimer);
+ this.flushTimer = null;
+ }
+
+ await this.flush();
+ }
+
+ async record(workspaceId: string, inputs: RecordUsageInput[]): Promise<void> {
+ if (!this.eventLogEmitterService.isEnabled() || inputs.length === 0) {
+ return;
+ }
+
+ const periodStart = await this.resolvePeriodStart(workspaceId);
+
+ this.workspaceEventEmitter.emitCustomBatchEvent<UsageEvent>(
+ USAGE_RECORDED,
+ inputs.map((input) => ({
+ ...this.withDefaults(input),
+ periodStart,
+ })),
+ workspaceId,
+ );
+ }
+
+ accumulate(workspaceId: string, input: RecordUsageInput): void {
+ if (!this.eventLogEmitterService.isEnabled()) {
+ return;
+ }
+
+ this.buffer.increment(workspaceId, this.withDefaults(input));
+
+ if (this.buffer.isFull) {
+ void this.flush();
+ }
+ }
+
+ private flush(): Promise<void> {
+ this.pendingFlush = this.pendingFlush
+ .then(() => this.drainAndDispatch())
+ .catch((error) =>
+ this.logger.error('Failed to flush usage rollups', error),
+ );
+
+ return this.pendingFlush;
+ }
+
+ private async drainAndDispatch(): Promise<void> {
+ const entries = [...this.buffer.drain().entries()];
+
+ if (entries.length === 0) {
+ return;
+ }
+
+ const results = await Promise.allSettled(
+ entries.map(([workspaceId, usageEvents]) =>
+ this.dispatchRollups(workspaceId, usageEvents),
+ ),
+ );
+
+ const failedEntries = entries.filter(
+ (_, index) => results[index].status === 'rejected',
+ );
+
+ if (failedEntries.length === 0) {
+ return;
+ }
+
+ failedEntries.forEach(([workspaceId, usageEvents]) =>
+ usageEvents.forEach((usageEvent) =>
+ this.buffer.increment(workspaceId, usageEvent),
+ ),
+ );
+
+ this.logger.warn(
+ `Failed to flush usage rollups for ${failedEntries.length}/${entries.length} workspace(s); re-buffered for next flush`,
+ );
+ }
+
+ private async dispatchRollups(
+ workspaceId: string,
+ usageEvents: UsageEvent[],
+ ): Promise<void> {
+ const periodStart = await this.resolvePeriodStart(workspaceId);
+
+ return this.eventLogEmitterService.dispatch(
+ buildUsageEventEnvelopes(
+ workspaceId,
+ usageEvents.map((usageEvent) => ({
+ ...usageEvent,
+ periodStart: usageEvent.periodStart ?? periodStart,
+ })),
+ ),
+ );
+ }
+
+ private withDefaults(input: RecordUsageInput): UsageEvent {
+ return { ...input, creditsUsedMicro: input.creditsUsedMicro ?? 0 };
+ }
+
+ private async resolvePeriodStart(
+ workspaceId: string,
+ ): Promise<Date | undefined> {
+ if (!this.twentyConfigService.get('IS_BILLING_ENABLED')) {
+ return undefined;
+ }
+
+ const { currentBillingSubscription } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'currentBillingSubscription',
+ ]);
+
+ return currentBillingSubscription === NO_BILLING_SUBSCRIPTION
+ ? undefined
+ : currentBillingSubscription.currentPeriodStart;
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/usage/storage/api-request-context.storage.ts b/packages/twenty-server/src/engine/core-modules/usage/storage/api-request-context.storage.ts
new file mode 100644
index 00000000000..a9cd285e44f
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage/storage/api-request-context.storage.ts
@@ -0,0 +1,15 @@
+/* @license Enterprise */
+
+import { AsyncLocalStorage } from 'async_hooks';
+
+import { type ApiType } from 'src/engine/core-modules/usage/types/api-type.type';
+
+const apiRequestContextStorage = new AsyncLocalStorage<{ apiType: ApiType }>();
+
+export const withApiRequestContext = <T>(
+ apiType: ApiType,
+ fn: () => T | Promise<T>,
+): T | Promise<T> => apiRequestContextStorage.run({ apiType }, fn);
+
+export const getApiType = (): ApiType | undefined =>
+ apiRequestContextStorage.getStore()?.apiType;
diff --git a/packages/twenty-server/src/engine/core-modules/usage/types/api-type.type.ts b/packages/twenty-server/src/engine/core-modules/usage/types/api-type.type.ts
new file mode 100644
index 00000000000..ac237452df7
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage/types/api-type.type.ts
@@ -0,0 +1 @@
+export type ApiType = 'CORE_GQL' | 'CORE_REST' | 'MCP';
diff --git a/packages/twenty-server/src/engine/core-modules/usage/types/record-usage-input.type.ts b/packages/twenty-server/src/engine/core-modules/usage/types/record-usage-input.type.ts
new file mode 100644
index 00000000000..cc6f8bd093d
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage/types/record-usage-input.type.ts
@@ -0,0 +1,10 @@
+/* @license Enterprise */
+
+import { type UsageEvent } from 'src/engine/core-modules/usage/types/usage-event.type';
+
+export type RecordUsageInput = Omit<
+ UsageEvent,
+ 'periodStart' | 'creditsUsedMicro'
+> & {
+ creditsUsedMicro?: number;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage/types/usage-event.type.ts b/packages/twenty-server/src/engine/core-modules/usage/types/usage-event.type.ts
index 7c15916f2c5..cd5b72de8d6 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/types/usage-event.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/types/usage-event.type.ts
@@ -3,6 +3,7 @@
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 UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
+import { type UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';
export type UsageEvent = {
resourceType: UsageResourceType;
@@ -13,5 +14,6 @@ export type UsageEvent = {
periodStart?: Date;
resourceId?: string | null;
resourceContext?: string | null;
- userWorkspaceId?: string | null;
+ spenders?: UsageSpenders;
+ metadata?: Record<string, unknown>;
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage/types/usage-spenders.type.ts b/packages/twenty-server/src/engine/core-modules/usage/types/usage-spenders.type.ts
new file mode 100644
index 00000000000..8c381eba174
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage/types/usage-spenders.type.ts
@@ -0,0 +1,10 @@
+/* @license Enterprise */
+
+export type UsageSpenders = {
+ userWorkspaceId?: string | null;
+ apiKeyId?: string | null;
+ applicationId?: string | null;
+ agentId?: string | null;
+ workflowId?: string | null;
+ logicFunctionId?: string | null;
+};
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 7fb3923a50f..b8d95179fb9 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
@@ -8,9 +8,11 @@ import { EventLogEmitterModule } from 'src/engine/core-modules/event-logs/emit/e
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 { 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';
import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permissions.module';
+import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
@Module({
imports: [
@@ -19,8 +21,14 @@ import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permi
FeatureFlagModule,
PermissionsModule,
TypeOrmModule.forFeature([UserWorkspaceEntity]),
+ WorkspaceCacheModule,
],
- providers: [UsageResolver, UsageAnalyticsService, UsageEventListener],
- exports: [UsageAnalyticsService],
+ providers: [
+ UsageResolver,
+ UsageAnalyticsService,
+ UsageRecorderService,
+ UsageEventListener,
+ ],
+ exports: [UsageAnalyticsService, UsageRecorderService],
})
export class UsageModule {}
diff --git a/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/get-api-type-from-path.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/get-api-type-from-path.util.spec.ts
new file mode 100644
index 00000000000..650fb4897fe
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/get-api-type-from-path.util.spec.ts
@@ -0,0 +1,19 @@
+import { getApiTypeFromPath } from 'src/engine/core-modules/usage/utils/get-api-type-from-path.util';
+
+describe('getApiTypeFromPath', () => {
+ it.each([
+ ['/graphql', 'CORE_GQL'],
+ ['/rest/people', 'CORE_REST'],
+ ['/rest/batch/people', 'CORE_REST'],
+ ['/mcp', 'MCP'],
+ ])('reads the api type of %s', (path, expected) => {
+ expect(getApiTypeFromPath(path)).toBe(expected);
+ });
+
+ it.each(['/metadata', '/auth/token', '/files/logo.png', '/'])(
+ 'leaves %s unattributed',
+ (path) => {
+ expect(getApiTypeFromPath(path)).toBeUndefined();
+ },
+ );
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/usage-rollup-buffer.spec.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/usage-rollup-buffer.spec.ts
new file mode 100644
index 00000000000..31a9e279537
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/usage-rollup-buffer.spec.ts
@@ -0,0 +1,71 @@
+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 { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
+import { type UsageEvent } from 'src/engine/core-modules/usage/types/usage-event.type';
+import { UsageRollupBuffer } from 'src/engine/core-modules/usage/utils/usage-rollup-buffer';
+
+const apiRequest = (overrides: Partial<UsageEvent> = {}): UsageEvent => ({
+ resourceType: UsageResourceType.API,
+ operationType: UsageOperationType.API_REQUEST,
+ quantity: 1,
+ unit: UsageUnit.REQUEST,
+ creditsUsedMicro: 0,
+ ...overrides,
+});
+
+describe('UsageRollupBuffer', () => {
+ it('sums the quantities and credits of events sharing the same scope', () => {
+ const buffer = new UsageRollupBuffer(10);
+
+ buffer.increment('ws-1', apiRequest({ creditsUsedMicro: 5 }));
+ buffer.increment('ws-1', apiRequest({ quantity: 2, creditsUsedMicro: 7 }));
+
+ expect(buffer.drain().get('ws-1')).toEqual([
+ expect.objectContaining({ quantity: 3, creditsUsedMicro: 12 }),
+ ]);
+ });
+
+ it('keeps a row per spender', () => {
+ const buffer = new UsageRollupBuffer(10);
+
+ buffer.increment('ws-1', apiRequest({ spenders: { apiKeyId: 'key-1' } }));
+ buffer.increment('ws-1', apiRequest({ spenders: { apiKeyId: 'key-2' } }));
+
+ expect(buffer.drain().get('ws-1')).toHaveLength(2);
+ });
+
+ it('keeps a row per period so a window straddling a boundary does not merge two periods', () => {
+ const buffer = new UsageRollupBuffer(10);
+
+ buffer.increment(
+ 'ws-1',
+ apiRequest({ periodStart: new Date('2026-01-01T00:00:00.000Z') }),
+ );
+ buffer.increment(
+ 'ws-1',
+ apiRequest({ periodStart: new Date('2026-02-01T00:00:00.000Z') }),
+ );
+
+ expect(buffer.drain().get('ws-1')).toHaveLength(2);
+ });
+
+ it('groups drained events by workspace and empties the buffer', () => {
+ const buffer = new UsageRollupBuffer(10);
+
+ buffer.increment('ws-1', apiRequest());
+ buffer.increment('ws-2', apiRequest());
+
+ expect([...buffer.drain().keys()]).toEqual(['ws-1', 'ws-2']);
+ expect(buffer.drain().size).toBe(0);
+ });
+
+ it('reports being full once the max entry count is reached', () => {
+ const buffer = new UsageRollupBuffer(1);
+
+ expect(buffer.isFull).toBe(false);
+
+ buffer.increment('ws-1', apiRequest());
+
+ expect(buffer.isFull).toBe(true);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage/utils/build-usage-event-envelopes.spec.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/build-usage-event-envelopes.spec.ts
index 97677bddc39..36297d0adf6 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/utils/build-usage-event-envelopes.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/utils/build-usage-event-envelopes.spec.ts
@@ -17,7 +17,7 @@ describe('buildUsageEventEnvelopes', () => {
it('maps each usage event to a usageEvent envelope carrying the workspace + columns', () => {
const envelopes = buildUsageEventEnvelopes('ws-1', [
usageEvent({
- userWorkspaceId: 'uw-1',
+ spenders: { userWorkspaceId: 'uw-1', agentId: 'agent-1' },
resourceId: 'agent-1',
resourceContext: 'gpt-4o',
}),
@@ -28,6 +28,7 @@ describe('buildUsageEventEnvelopes', () => {
expect(envelopes[0].row).toMatchObject({
workspaceId: 'ws-1',
userWorkspaceId: 'uw-1',
+ agentId: 'agent-1',
resourceType: UsageResourceType.AI,
operationType: UsageOperationType.AI_CHAT_TOKEN,
quantity: 1500,
@@ -42,6 +43,11 @@ describe('buildUsageEventEnvelopes', () => {
expect(envelope.row).toMatchObject({
userWorkspaceId: '',
+ apiKeyId: '',
+ applicationId: '',
+ agentId: '',
+ workflowId: '',
+ logicFunctionId: '',
resourceId: '',
resourceContext: '',
});
diff --git a/packages/twenty-server/src/engine/core-modules/usage/utils/build-usage-event-envelopes.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/build-usage-event-envelopes.ts
index ec8322d666a..a31d9fcac86 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/utils/build-usage-event-envelopes.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/utils/build-usage-event-envelopes.ts
@@ -18,7 +18,12 @@ export const buildUsageEventEnvelopes = (
periodStart: usageEvent.periodStart
? formatDateTimeForClickHouse(usageEvent.periodStart)
: undefined,
- userWorkspaceId: usageEvent.userWorkspaceId ?? '',
+ userWorkspaceId: usageEvent.spenders?.userWorkspaceId ?? '',
+ apiKeyId: usageEvent.spenders?.apiKeyId ?? '',
+ applicationId: usageEvent.spenders?.applicationId ?? '',
+ agentId: usageEvent.spenders?.agentId ?? '',
+ workflowId: usageEvent.spenders?.workflowId ?? '',
+ logicFunctionId: usageEvent.spenders?.logicFunctionId ?? '',
resourceType: usageEvent.resourceType,
operationType: usageEvent.operationType,
quantity: usageEvent.quantity,
@@ -26,7 +31,7 @@ export const buildUsageEventEnvelopes = (
creditsUsedMicro: usageEvent.creditsUsedMicro,
resourceId: usageEvent.resourceId ?? '',
resourceContext: usageEvent.resourceContext ?? '',
- metadata: {},
+ metadata: usageEvent.metadata ?? {},
},
}));
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage/utils/build-usage-spenders-from-auth-context.util.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/build-usage-spenders-from-auth-context.util.ts
new file mode 100644
index 00000000000..955bf291f82
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage/utils/build-usage-spenders-from-auth-context.util.ts
@@ -0,0 +1,29 @@
+/* @license Enterprise */
+
+import { isApiKeyAuthContext } from 'src/engine/core-modules/auth/guards/is-api-key-auth-context.guard';
+import { isApplicationAuthContext } from 'src/engine/core-modules/auth/guards/is-application-auth-context.guard';
+import { isUserAuthContext } from 'src/engine/core-modules/auth/guards/is-user-auth-context.guard';
+import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
+import { type UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';
+
+export const buildUsageSpendersFromAuthContext = (
+ authContext: WorkspaceAuthContext,
+): UsageSpenders => {
+ if (isApiKeyAuthContext(authContext)) {
+ return { apiKeyId: authContext.apiKey.id };
+ }
+
+ if (isApplicationAuthContext(authContext)) {
+ return { applicationId: authContext.application.id };
+ }
+
+ if (isUserAuthContext(authContext)) {
+ return {
+ userWorkspaceId: authContext.userWorkspaceId,
+ applicationId:
+ authContext.application?.id ?? authContext.viaApplication?.id,
+ };
+ }
+
+ return {};
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage/utils/get-api-type-from-path.util.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/get-api-type-from-path.util.ts
new file mode 100644
index 00000000000..bb16d26c343
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage/utils/get-api-type-from-path.util.ts
@@ -0,0 +1,10 @@
+/* @license Enterprise */
+
+import { API_TYPE_BY_PATH_PREFIX } from 'src/engine/core-modules/usage/constants/api-types.constant';
+import { type ApiType } from 'src/engine/core-modules/usage/types/api-type.type';
+
+export const getApiTypeFromPath = (path: string): ApiType | undefined => {
+ const [pathPrefix] = path.replace(/^\//, '').split('/');
+
+ return API_TYPE_BY_PATH_PREFIX[pathPrefix];
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage/utils/usage-rollup-buffer.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/usage-rollup-buffer.ts
new file mode 100644
index 00000000000..af66f88d082
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage/utils/usage-rollup-buffer.ts
@@ -0,0 +1,73 @@
+/* @license Enterprise */
+
+import { isDefined } from 'twenty-shared/utils';
+
+import { type UsageEvent } from 'src/engine/core-modules/usage/types/usage-event.type';
+
+const ABSENT = '-';
+
+type BufferedRollup = {
+ workspaceId: string;
+ usageEvent: UsageEvent;
+};
+
+const buildRollupKey = (workspaceId: string, usageEvent: UsageEvent): string =>
+ [
+ workspaceId,
+ usageEvent.resourceType,
+ usageEvent.operationType,
+ usageEvent.unit,
+ usageEvent.resourceContext || ABSENT,
+ usageEvent.resourceId || ABSENT,
+ usageEvent.periodStart?.toISOString() ?? ABSENT,
+ usageEvent.spenders?.userWorkspaceId || ABSENT,
+ usageEvent.spenders?.apiKeyId || ABSENT,
+ usageEvent.spenders?.applicationId || ABSENT,
+ usageEvent.spenders?.agentId || ABSENT,
+ usageEvent.spenders?.workflowId || ABSENT,
+ usageEvent.spenders?.logicFunctionId || ABSENT,
+ ].join('|');
+
+export class UsageRollupBuffer {
+ private rollupByKey = new Map<string, BufferedRollup>();
+
+ constructor(private readonly maxEntries: number) {}
+
+ get isFull(): boolean {
+ return this.rollupByKey.size >= this.maxEntries;
+ }
+
+ increment(workspaceId: string, usageEvent: UsageEvent): void {
+ const rollupKey = buildRollupKey(workspaceId, usageEvent);
+ const bufferedRollup = this.rollupByKey.get(rollupKey);
+
+ if (isDefined(bufferedRollup)) {
+ bufferedRollup.usageEvent.quantity += usageEvent.quantity;
+ bufferedRollup.usageEvent.creditsUsedMicro += usageEvent.creditsUsedMicro;
+
+ return;
+ }
+
+ this.rollupByKey.set(rollupKey, {
+ workspaceId,
+ usageEvent: { ...usageEvent },
+ });
+ }
+
+ drain(): Map<string, UsageEvent[]> {
+ const drainedRollups = [...this.rollupByKey.values()];
+
+ this.rollupByKey = new Map();
+
+ const usageEventsByWorkspaceId = new Map<string, UsageEvent[]>();
+
+ for (const { workspaceId, usageEvent } of drainedRollups) {
+ const usageEvents = usageEventsByWorkspaceId.get(workspaceId) ?? [];
+
+ usageEvents.push(usageEvent);
+ usageEventsByWorkspaceId.set(workspaceId, usageEvents);
+ }
+
+ return usageEventsByWorkspaceId;
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/ai-billing.module.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/ai-billing.module.ts
index 7cc5a480928..41beccd1863 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/ai-billing.module.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/ai-billing.module.ts
@@ -1,18 +1,13 @@
import { Module } from '@nestjs/common';
import { BillingModule } from 'src/engine/core-modules/billing/billing.module';
+import { UsageModule } from 'src/engine/core-modules/usage/usage.module';
import { AiBillingService } from 'src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service';
import { AiModelsModule } from 'src/engine/metadata-modules/ai/ai-models/ai-models.module';
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
-import { WorkspaceEventEmitterModule } from 'src/engine/workspace-event-emitter/workspace-event-emitter.module';
@Module({
- imports: [
- WorkspaceEventEmitterModule,
- AiModelsModule,
- BillingModule,
- WorkspaceCacheModule,
- ],
+ imports: [AiModelsModule, BillingModule, UsageModule, WorkspaceCacheModule],
providers: [AiBillingService],
exports: [AiBillingService],
})
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service.ts
index 24bdaab1ce2..6969e213a4e 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service.ts
@@ -5,18 +5,16 @@ import { NO_BILLING_SUBSCRIPTION } from 'src/engine/core-modules/billing/constan
import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';
import { BillingService } from 'src/engine/core-modules/billing/services/billing.service';
-import { USAGE_RECORDED } from 'src/engine/core-modules/usage/constants/usage-recorded.constant';
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 { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
-import { type UsageEvent } from 'src/engine/core-modules/usage/types/usage-event.type';
+import { UsageRecorderService } from 'src/engine/core-modules/usage/services/usage-recorder.service';
import { NATIVE_WEB_SEARCH_COST_PER_CALL_DOLLARS } from 'src/engine/metadata-modules/ai/ai-billing/constants/native-web-search-cost-per-call-dollars';
import { computeCostBreakdown } from 'src/engine/metadata-modules/ai/ai-billing/utils/compute-cost-breakdown.util';
import { convertDollarsToBillingCredits } from 'src/engine/metadata-modules/ai/ai-billing/utils/convert-dollars-to-billing-credits.util';
import { AiModelRegistryService } from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service';
import { type ModelId } from 'src/engine/metadata-modules/ai/ai-models/types/model-id.type';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
-import { WorkspaceEventEmitter } from 'src/engine/workspace-event-emitter/workspace-event-emitter';
export type BillingUsageInput = {
usage: LanguageModelUsage;
@@ -28,7 +26,7 @@ export class AiBillingService {
private readonly logger = new Logger(AiBillingService.name);
constructor(
- private readonly workspaceEventEmitter: WorkspaceEventEmitter,
+ private readonly usageRecorderService: UsageRecorderService,
private readonly aiModelRegistryService: AiModelRegistryService,
private readonly billingService: BillingService,
private readonly billingUsageService: BillingUsageService,
@@ -136,8 +134,6 @@ export class AiBillingService {
`Native web search billing: ${nativeWebSearchCallCount} calls, $${costInDollars.toFixed(4)}`,
);
- let periodStart: Date | undefined;
-
if (this.billingService.isBillingEnabled()) {
const { currentBillingSubscription } =
await this.workspaceCacheService.getOrRecompute(workspaceId, [
@@ -145,8 +141,6 @@ export class AiBillingService {
]);
if (currentBillingSubscription !== NO_BILLING_SUBSCRIPTION) {
- periodStart = currentBillingSubscription.currentPeriodStart;
-
await this.billingUsageService.decrementAvailableCreditsInCache({
workspaceId,
usedCredits: creditsUsedMicro,
@@ -154,21 +148,16 @@ export class AiBillingService {
}
}
- this.workspaceEventEmitter.emitCustomBatchEvent<UsageEvent>(
- USAGE_RECORDED,
- [
- {
- resourceType: UsageResourceType.AI,
- operationType: UsageOperationType.WEB_SEARCH,
- creditsUsedMicro,
- quantity: nativeWebSearchCallCount,
- unit: UsageUnit.INVOCATION,
- userWorkspaceId: userWorkspaceId || null,
- periodStart,
- },
- ],
- workspaceId,
- );
+ await this.usageRecorderService.record(workspaceId, [
+ {
+ resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.WEB_SEARCH,
+ creditsUsedMicro,
+ quantity: nativeWebSearchCallCount,
+ unit: UsageUnit.INVOCATION,
+ spenders: { userWorkspaceId },
+ },
+ ]);
}
async emitAiTokenUsageEvent(
@@ -180,36 +169,17 @@ export class AiBillingService {
agentId?: string | null,
userWorkspaceId?: string | null,
): Promise<void> {
- let periodStart: Date | undefined;
-
- if (this.billingService.isBillingEnabled()) {
- const { currentBillingSubscription } =
- await this.workspaceCacheService.getOrRecompute(workspaceId, [
- 'currentBillingSubscription',
- ]);
-
- periodStart =
- currentBillingSubscription === NO_BILLING_SUBSCRIPTION
- ? undefined
- : currentBillingSubscription.currentPeriodStart;
- }
-
- this.workspaceEventEmitter.emitCustomBatchEvent<UsageEvent>(
- USAGE_RECORDED,
- [
- {
- resourceType: UsageResourceType.AI,
- operationType,
- creditsUsedMicro,
- quantity: totalTokens,
- unit: UsageUnit.TOKEN,
- resourceId: agentId || null,
- resourceContext: modelId,
- userWorkspaceId: userWorkspaceId || null,
- periodStart,
- },
- ],
- workspaceId,
- );
+ await this.usageRecorderService.record(workspaceId, [
+ {
+ resourceType: UsageResourceType.AI,
+ operationType,
+ creditsUsedMicro,
+ quantity: totalTokens,
+ unit: UsageUnit.TOKEN,
+ resourceId: agentId || null,
+ resourceContext: modelId,
+ spenders: { userWorkspaceId, agentId },
+ },
+ ]);
}
}
diff --git a/packages/twenty-server/src/main.ts b/packages/twenty-server/src/main.ts
index 56568385e75..00b79dd7496 100644
--- a/packages/twenty-server/src/main.ts
+++ b/packages/twenty-server/src/main.ts
@@ -18,6 +18,7 @@ import { LoggerService } from 'src/engine/core-modules/logger/logger.service';
import { getSessionStorageOptions } from 'src/engine/core-modules/session-storage/session-storage.module-factory';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
import { configTransformers } from 'src/engine/core-modules/twenty-config/utils/config-transformers.util';
+import { UsageRecorderService } from 'src/engine/core-modules/usage/services/usage-recorder.service';
import { applyCredentialedCors } from 'src/engine/core-modules/user-session/utils/apply-credentialed-cors.util';
import { shouldCaptureException } from 'src/engine/utils/global-exception-handler.util';
@@ -109,6 +110,14 @@ const bootstrap = async () => {
httpServer.keepAliveTimeout = keepAliveTimeout;
httpServer.headersTimeout = keepAliveTimeout + 1000;
+ const usageRecorder = app.get(UsageRecorderService);
+
+ for (const signal of ['SIGTERM', 'SIGINT'] as const) {
+ process.once(signal, () => {
+ void usageRecorder.flushAndStop().finally(() => process.exit(0));
+ });
+ }
+
await app.listen(twentyConfigService.get('NODE_PORT'));
};
diff --git a/packages/twenty-server/src/modules/emailing/emailing.module.ts b/packages/twenty-server/src/modules/emailing/emailing.module.ts
index 9c89bf7b426..a1f0f0153a7 100644
--- a/packages/twenty-server/src/modules/emailing/emailing.module.ts
+++ b/packages/twenty-server/src/modules/emailing/emailing.module.ts
@@ -8,6 +8,7 @@ import { CampaignDeliveryEntity } from 'src/engine/core-modules/emailing-domain/
import { MessageSuppressionEntity } from 'src/engine/core-modules/emailing-domain/message-suppression.entity';
import { UnsubscribeTopicEntity } from 'src/engine/core-modules/emailing-domain/unsubscribe-topic.entity';
import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';
+import { UsageModule } from 'src/engine/core-modules/usage/usage.module';
import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { MessageChannelMetadataModule } from 'src/engine/metadata-modules/message-channel/message-channel-metadata.module';
@@ -47,6 +48,7 @@ import { SaveCampaignTool } from 'src/modules/emailing/tools/save-campaign-tool'
PermissionsModule,
UserRoleModule,
BillingModule,
+ UsageModule,
WorkspaceEventEmitterModule,
WorkspaceCacheModule,
WorkspaceManyOrAllFlatEntityMapsCacheModule,
diff --git a/packages/twenty-server/src/modules/emailing/services/email-billing.service.ts b/packages/twenty-server/src/modules/emailing/services/email-billing.service.ts
index b47fb22d685..16f8445fe7a 100644
--- a/packages/twenty-server/src/modules/emailing/services/email-billing.service.ts
+++ b/packages/twenty-server/src/modules/emailing/services/email-billing.service.ts
@@ -3,21 +3,19 @@ import { Injectable } from '@nestjs/common';
import { NO_BILLING_SUBSCRIPTION } from 'src/engine/core-modules/billing/constants/no-billing-subscription.constant';
import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';
import { BillingService } from 'src/engine/core-modules/billing/services/billing.service';
-import { USAGE_RECORDED } from 'src/engine/core-modules/usage/constants/usage-recorded.constant';
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 { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
-import { type UsageEvent } from 'src/engine/core-modules/usage/types/usage-event.type';
+import { UsageRecorderService } from 'src/engine/core-modules/usage/services/usage-recorder.service';
import { convertDollarsToBillingCredits } from 'src/engine/metadata-modules/ai/ai-billing/utils/convert-dollars-to-billing-credits.util';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
-import { WorkspaceEventEmitter } from 'src/engine/workspace-event-emitter/workspace-event-emitter';
import { EMAIL_MARGIN_MULTIPLIER } from 'src/modules/emailing/constants/email-margin-multiplier';
import { SES_EMAIL_COST_PER_THOUSAND_DOLLARS } from 'src/modules/emailing/constants/ses-email-cost-per-thousand-dollars';
@Injectable()
export class EmailBillingService {
constructor(
- private readonly workspaceEventEmitter: WorkspaceEventEmitter,
+ private readonly usageRecorderService: UsageRecorderService,
private readonly billingService: BillingService,
private readonly billingUsageService: BillingUsageService,
private readonly workspaceCacheService: WorkspaceCacheService,
@@ -51,8 +49,6 @@ export class EmailBillingService {
convertDollarsToBillingCredits(chargedInDollars),
);
- let periodStart: Date | undefined;
-
if (this.billingService.isBillingEnabled()) {
const { currentBillingSubscription } =
await this.workspaceCacheService.getOrRecompute(workspaceId, [
@@ -60,8 +56,6 @@ export class EmailBillingService {
]);
if (currentBillingSubscription !== NO_BILLING_SUBSCRIPTION) {
- periodStart = currentBillingSubscription.currentPeriodStart;
-
await this.billingUsageService.decrementAvailableCreditsInCache({
workspaceId,
usedCredits: creditsUsedMicro,
@@ -69,20 +63,15 @@ export class EmailBillingService {
}
}
- this.workspaceEventEmitter.emitCustomBatchEvent<UsageEvent>(
- USAGE_RECORDED,
- [
- {
- resourceType: UsageResourceType.EMAIL,
- operationType: UsageOperationType.EMAIL_SEND,
- creditsUsedMicro,
- quantity: sentEmailCount,
- unit: UsageUnit.INVOCATION,
- userWorkspaceId: userWorkspaceId || null,
- periodStart,
- },
- ],
- workspaceId,
- );
+ await this.usageRecorderService.record(workspaceId, [
+ {
+ resourceType: UsageResourceType.EMAIL,
+ operationType: UsageOperationType.EMAIL_SEND,
+ creditsUsedMicro,
+ quantity: sentEmailCount,
+ unit: UsageUnit.INVOCATION,
+ spenders: { userWorkspaceId },
+ },
+ ]);
}
}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-executor.module.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-executor.module.ts
index 8a69de11ac9..a2625bbdda8 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-executor.module.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-executor.module.ts
@@ -4,6 +4,7 @@ import { BillingModule } from 'src/engine/core-modules/billing/billing.module';
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';
import { MetricsModule } from 'src/engine/core-modules/metrics/metrics.module';
+import { UsageModule } from 'src/engine/core-modules/usage/usage.module';
import { WorkflowCommonModule } from 'src/modules/workflow/common/workflow-common.module';
import { WorkflowActionFactory } from 'src/modules/workflow/workflow-executor/factories/workflow-action.factory';
import { AiAgentActionModule } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent-action.module';
@@ -43,6 +44,7 @@ import { WorkflowRunModule } from 'src/modules/workflow/workflow-runner/workflow
MailSenderActionModule,
CreateCalendarEventActionModule,
MetricsModule,
+ UsageModule,
],
providers: [WorkflowExecutorWorkspaceService, WorkflowActionFactory],
exports: [WorkflowExecutorWorkspaceService],
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.ts
index c5d01a13a9d..e290103c2fd 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.ts
@@ -17,13 +17,11 @@ import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queu
import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
import { MetricsService } from 'src/engine/core-modules/metrics/metrics.service';
import { MetricsKeys } from 'src/engine/core-modules/metrics/types/metrics-keys.type';
-import { USAGE_RECORDED } from 'src/engine/core-modules/usage/constants/usage-recorded.constant';
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 { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
-import { type UsageEvent } from 'src/engine/core-modules/usage/types/usage-event.type';
+import { UsageRecorderService } from 'src/engine/core-modules/usage/services/usage-recorder.service';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
-import { WorkspaceEventEmitter } from 'src/engine/workspace-event-emitter/workspace-event-emitter';
import { WorkflowRunStatus } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';
import { workflowHasRunningSteps } from 'src/modules/workflow/common/utils/workflow-has-running-steps.util';
import {
@@ -58,7 +56,7 @@ const MAX_EXECUTED_STEPS_COUNT = 20;
export class WorkflowExecutorWorkspaceService {
constructor(
private readonly workflowActionFactory: WorkflowActionFactory,
- private readonly workspaceEventEmitter: WorkspaceEventEmitter,
+ private readonly usageRecorderService: UsageRecorderService,
private readonly workflowRunWorkspaceService: WorkflowRunWorkspaceService,
private readonly billingService: BillingService,
private readonly billingUsageService: BillingUsageService,
@@ -324,7 +322,6 @@ export class WorkflowExecutorWorkspaceService {
workspaceId: string,
workflowId: string,
) {
- let periodStart: Date | undefined;
if (this.billingService.isBillingEnabled()) {
const { currentBillingSubscription } =
await this.workspaceCacheService.getOrRecompute(workspaceId, [
@@ -332,8 +329,6 @@ export class WorkflowExecutorWorkspaceService {
]);
if (currentBillingSubscription !== NO_BILLING_SUBSCRIPTION) {
- periodStart = currentBillingSubscription.currentPeriodStart;
-
await this.billingUsageService.decrementAvailableCreditsInCache({
workspaceId,
usedCredits: 100,
@@ -341,21 +336,17 @@ export class WorkflowExecutorWorkspaceService {
}
}
- this.workspaceEventEmitter.emitCustomBatchEvent<UsageEvent>(
- USAGE_RECORDED,
- [
- {
- resourceType: UsageResourceType.WORKFLOW,
- operationType: UsageOperationType.WORKFLOW_EXECUTION,
- creditsUsedMicro: 100,
- quantity: 1,
- unit: UsageUnit.INVOCATION,
- resourceId: workflowId,
- periodStart,
- },
- ],
- workspaceId,
- );
+ await this.usageRecorderService.record(workspaceId, [
+ {
+ resourceType: UsageResourceType.WORKFLOW,
+ operationType: UsageOperationType.WORKFLOW_EXECUTION,
+ creditsUsedMicro: 100,
+ quantity: 1,
+ unit: UsageUnit.INVOCATION,
+ resourceId: workflowId,
+ spenders: { workflowId },
+ },
+ ]);
}
private async processStepExecutionResult({