Skip to content

The open alternative to Salesforce, designed for AI.

refactor(usage-limit): charge usage rows through one call that debits then records (#27286)

Etiennefa512ae4d42d
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index 69d8fe7bcb3..fecc75289b2 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -1633,6 +1633,100 @@ enum LogicFunctionExecutionStatus {
ERROR
}
+type UserSession {
+ id: UUID!
+ workspaceId: UUID
+ authProvider: String!
+ isImpersonating: Boolean!
+ userAgent: String
+ ipAddress: String
+ createdAt: DateTime!
+ lastActiveAt: DateTime!
+ expiresAt: DateTime!
+ isCurrent: Boolean!
+}
+
+type BillingEndTrialPeriod {
+ """Updated subscription status"""
+ status: SubscriptionStatus
+
+ """Boolean that confirms if a payment method was found"""
+ hasPaymentMethod: Boolean!
+
+ """
+ Billing portal URL for payment method update (returned when no payment method exists)
+ """
+ billingPortalUrl: String
+
+ """Updated current billing subscription"""
+ currentBillingSubscription: BillingSubscription
+
+ """All billing subscriptions"""
+ billingSubscriptions: [BillingSubscription!]
+}
+
+type BillingResourceCreditUsage {
+ productKey: BillingProductKey!
+ periodStart: DateTime!
+ periodEnd: DateTime!
+ usedCredits: Float!
+ grantedCredits: Float!
+ rolloverCredits: Float!
+ totalGrantedCredits: Float!
+ unitPriceCents: Float!
+}
+
+type BillingPlan {
+ planKey: BillingPlanKey!
+ baseProducts: [BillingLicensedProduct!]!
+ resourceCreditProducts: [BillingLicensedProduct!]!
+ meteredProducts: [BillingMeteredProduct!]!
+}
+
+type BillingPaymentIntent {
+ clientSecret: String!
+ paymentIntentType: String!
+}
+
+type BillingSession {
+ url: String
+}
+
+type BillingUpdate {
+ """Current billing subscription"""
+ currentBillingSubscription: BillingSubscription!
+
+ """All billing subscriptions"""
+ billingSubscriptions: [BillingSubscription!]!
+}
+
+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!]!
+ usageByApplication: [UsageBreakdownItem!]!
+ usageByModel: [UsageBreakdownItem!]!
+ timeSeries: [UsageTimeSeries!]!
+ periodStart: DateTime!
+ periodEnd: DateTime!
+ userDailyUsage: UsageUserDaily
+}
+
type UsageLimitOperationDefinition {
operationType: UsageOperationType!
allowedUnits: [UsageUnit!]!
@@ -1932,100 +2026,6 @@ type EventSubscription {
queueJobEvents: [JobStatus!]!
}
-type UserSession {
- id: UUID!
- workspaceId: UUID
- authProvider: String!
- isImpersonating: Boolean!
- userAgent: String
- ipAddress: String
- createdAt: DateTime!
- lastActiveAt: DateTime!
- expiresAt: DateTime!
- isCurrent: Boolean!
-}
-
-type BillingEndTrialPeriod {
- """Updated subscription status"""
- status: SubscriptionStatus
-
- """Boolean that confirms if a payment method was found"""
- hasPaymentMethod: Boolean!
-
- """
- Billing portal URL for payment method update (returned when no payment method exists)
- """
- billingPortalUrl: String
-
- """Updated current billing subscription"""
- currentBillingSubscription: BillingSubscription
-
- """All billing subscriptions"""
- billingSubscriptions: [BillingSubscription!]
-}
-
-type BillingResourceCreditUsage {
- productKey: BillingProductKey!
- periodStart: DateTime!
- periodEnd: DateTime!
- usedCredits: Float!
- grantedCredits: Float!
- rolloverCredits: Float!
- totalGrantedCredits: Float!
- unitPriceCents: Float!
-}
-
-type BillingPlan {
- planKey: BillingPlanKey!
- baseProducts: [BillingLicensedProduct!]!
- resourceCreditProducts: [BillingLicensedProduct!]!
- meteredProducts: [BillingMeteredProduct!]!
-}
-
-type BillingPaymentIntent {
- clientSecret: String!
- paymentIntentType: String!
-}
-
-type BillingSession {
- url: String
-}
-
-type BillingUpdate {
- """Current billing subscription"""
- currentBillingSubscription: BillingSubscription!
-
- """All billing subscriptions"""
- billingSubscriptions: [BillingSubscription!]!
-}
-
-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!]!
- usageByApplication: [UsageBreakdownItem!]!
- usageByModel: [UsageBreakdownItem!]!
- timeSeries: [UsageTimeSeries!]!
- periodStart: DateTime!
- periodEnd: DateTime!
- userDailyUsage: UsageUserDaily
-}
-
type ApprovedAccessDomain {
id: UUID!
domain: String!
@@ -3878,6 +3878,7 @@ type Query {
usageQuotasWithConsumption: [UsageQuotaWithConsumption!]!
usageQuotaDefinitions: UsageQuotaDefinitions!
usageQuotaScopeConsumption(input: UsageQuotaScopeInput!): UsageQuotaScopeConsumption
+ getUsageAnalytics(input: UsageAnalyticsInput): UsageAnalytics!
getPageLayoutWidgets(pageLayoutTabId: String!): [PageLayoutWidget!]!
getPageLayoutWidget(id: String!): PageLayoutWidget!
getPageLayoutTabs(pageLayoutId: String!): [PageLayoutTab!]!
@@ -3920,7 +3921,6 @@ type Query {
frontComponent(id: UUID!): FrontComponent
getInviteSuggestions: [InviteSuggestion!]!
applicationConnectionProviders(applicationId: UUID!): [ApplicationConnectionProvider!]!
- getUsageAnalytics(input: UsageAnalyticsInput): UsageAnalytics!
billingPortalSession(returnUrlPath: String, forPaymentMethodUpdate: Boolean): BillingSession!
listPlans: [BillingPlan!]!
getResourceCreditUsage: [BillingResourceCreditUsage!]!
@@ -4033,6 +4033,13 @@ input UsageQuotaScopeInput {
unit: UsageUnit!
}
+input UsageAnalyticsInput {
+ periodStart: DateTime
+ periodEnd: DateTime
+ userWorkspaceId: String
+ operationTypes: [UsageOperationType!]
+}
+
input AgentIdInput {
"""The id of the agent."""
id: UUID!
@@ -4057,13 +4064,6 @@ input LogicFunctionIdInput {
id: ID!
}
-input UsageAnalyticsInput {
- periodStart: DateTime
- periodEnd: DateTime
- userWorkspaceId: String
- operationTypes: [UsageOperationType!]
-}
-
input GetApiKeyInput {
id: UUID!
}
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index cad8ca95fa6..981410306fc 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -1267,6 +1267,104 @@ export interface LogicFunctionExecutionResult {
/** Status of the logic function execution */
export type LogicFunctionExecutionStatus = 'IDLE' | 'SUCCESS' | 'ERROR'
+export interface UserSession {
+ id: Scalars['UUID']
+ workspaceId?: Scalars['UUID']
+ authProvider: Scalars['String']
+ isImpersonating: Scalars['Boolean']
+ userAgent?: Scalars['String']
+ ipAddress?: Scalars['String']
+ createdAt: Scalars['DateTime']
+ lastActiveAt: Scalars['DateTime']
+ expiresAt: Scalars['DateTime']
+ isCurrent: Scalars['Boolean']
+ __typename: 'UserSession'
+}
+
+export interface BillingEndTrialPeriod {
+ /** Updated subscription status */
+ status?: SubscriptionStatus
+ /** Boolean that confirms if a payment method was found */
+ hasPaymentMethod: Scalars['Boolean']
+ /** Billing portal URL for payment method update (returned when no payment method exists) */
+ billingPortalUrl?: Scalars['String']
+ /** Updated current billing subscription */
+ currentBillingSubscription?: BillingSubscription
+ /** All billing subscriptions */
+ billingSubscriptions?: BillingSubscription[]
+ __typename: 'BillingEndTrialPeriod'
+}
+
+export interface BillingResourceCreditUsage {
+ productKey: BillingProductKey
+ periodStart: Scalars['DateTime']
+ periodEnd: Scalars['DateTime']
+ usedCredits: Scalars['Float']
+ grantedCredits: Scalars['Float']
+ rolloverCredits: Scalars['Float']
+ totalGrantedCredits: Scalars['Float']
+ unitPriceCents: Scalars['Float']
+ __typename: 'BillingResourceCreditUsage'
+}
+
+export interface BillingPlan {
+ planKey: BillingPlanKey
+ baseProducts: BillingLicensedProduct[]
+ resourceCreditProducts: BillingLicensedProduct[]
+ meteredProducts: BillingMeteredProduct[]
+ __typename: 'BillingPlan'
+}
+
+export interface BillingPaymentIntent {
+ clientSecret: Scalars['String']
+ paymentIntentType: Scalars['String']
+ __typename: 'BillingPaymentIntent'
+}
+
+export interface BillingSession {
+ url?: Scalars['String']
+ __typename: 'BillingSession'
+}
+
+export interface BillingUpdate {
+ /** Current billing subscription */
+ currentBillingSubscription: BillingSubscription
+ /** All billing subscriptions */
+ billingSubscriptions: BillingSubscription[]
+ __typename: 'BillingUpdate'
+}
+
+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[]
+ usageByApplication: UsageBreakdownItem[]
+ usageByModel: UsageBreakdownItem[]
+ timeSeries: UsageTimeSeries[]
+ periodStart: Scalars['DateTime']
+ periodEnd: Scalars['DateTime']
+ userDailyUsage?: UsageUserDaily
+ __typename: 'UsageAnalytics'
+}
+
export interface UsageLimitOperationDefinition {
operationType: UsageOperationType
allowedUnits: UsageUnit[]
@@ -1502,104 +1600,6 @@ export interface EventSubscription {
__typename: 'EventSubscription'
}
-export interface UserSession {
- id: Scalars['UUID']
- workspaceId?: Scalars['UUID']
- authProvider: Scalars['String']
- isImpersonating: Scalars['Boolean']
- userAgent?: Scalars['String']
- ipAddress?: Scalars['String']
- createdAt: Scalars['DateTime']
- lastActiveAt: Scalars['DateTime']
- expiresAt: Scalars['DateTime']
- isCurrent: Scalars['Boolean']
- __typename: 'UserSession'
-}
-
-export interface BillingEndTrialPeriod {
- /** Updated subscription status */
- status?: SubscriptionStatus
- /** Boolean that confirms if a payment method was found */
- hasPaymentMethod: Scalars['Boolean']
- /** Billing portal URL for payment method update (returned when no payment method exists) */
- billingPortalUrl?: Scalars['String']
- /** Updated current billing subscription */
- currentBillingSubscription?: BillingSubscription
- /** All billing subscriptions */
- billingSubscriptions?: BillingSubscription[]
- __typename: 'BillingEndTrialPeriod'
-}
-
-export interface BillingResourceCreditUsage {
- productKey: BillingProductKey
- periodStart: Scalars['DateTime']
- periodEnd: Scalars['DateTime']
- usedCredits: Scalars['Float']
- grantedCredits: Scalars['Float']
- rolloverCredits: Scalars['Float']
- totalGrantedCredits: Scalars['Float']
- unitPriceCents: Scalars['Float']
- __typename: 'BillingResourceCreditUsage'
-}
-
-export interface BillingPlan {
- planKey: BillingPlanKey
- baseProducts: BillingLicensedProduct[]
- resourceCreditProducts: BillingLicensedProduct[]
- meteredProducts: BillingMeteredProduct[]
- __typename: 'BillingPlan'
-}
-
-export interface BillingPaymentIntent {
- clientSecret: Scalars['String']
- paymentIntentType: Scalars['String']
- __typename: 'BillingPaymentIntent'
-}
-
-export interface BillingSession {
- url?: Scalars['String']
- __typename: 'BillingSession'
-}
-
-export interface BillingUpdate {
- /** Current billing subscription */
- currentBillingSubscription: BillingSubscription
- /** All billing subscriptions */
- billingSubscriptions: BillingSubscription[]
- __typename: 'BillingUpdate'
-}
-
-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[]
- usageByApplication: UsageBreakdownItem[]
- usageByModel: UsageBreakdownItem[]
- timeSeries: UsageTimeSeries[]
- periodStart: Scalars['DateTime']
- periodEnd: Scalars['DateTime']
- userDailyUsage?: UsageUserDaily
- __typename: 'UsageAnalytics'
-}
-
export interface ApprovedAccessDomain {
id: Scalars['UUID']
domain: Scalars['String']
@@ -3381,6 +3381,7 @@ export interface Query {
usageQuotasWithConsumption: UsageQuotaWithConsumption[]
usageQuotaDefinitions: UsageQuotaDefinitions
usageQuotaScopeConsumption?: UsageQuotaScopeConsumption
+ getUsageAnalytics: UsageAnalytics
getPageLayoutWidgets: PageLayoutWidget[]
getPageLayoutWidget: PageLayoutWidget
getPageLayoutTabs: PageLayoutTab[]
@@ -3414,7 +3415,6 @@ export interface Query {
frontComponent?: FrontComponent
getInviteSuggestions: InviteSuggestion[]
applicationConnectionProviders: ApplicationConnectionProvider[]
- getUsageAnalytics: UsageAnalytics
billingPortalSession: BillingSession
listPlans: BillingPlan[]
getResourceCreditUsage: BillingResourceCreditUsage[]
@@ -5102,6 +5102,115 @@ export interface LogicFunctionExecutionResultGenqlSelection{
__scalar?: boolean | number
}
+export interface UserSessionGenqlSelection{
+ id?: boolean | number
+ workspaceId?: boolean | number
+ authProvider?: boolean | number
+ isImpersonating?: boolean | number
+ userAgent?: boolean | number
+ ipAddress?: boolean | number
+ createdAt?: boolean | number
+ lastActiveAt?: boolean | number
+ expiresAt?: boolean | number
+ isCurrent?: boolean | number
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
+export interface BillingEndTrialPeriodGenqlSelection{
+ /** Updated subscription status */
+ status?: boolean | number
+ /** Boolean that confirms if a payment method was found */
+ hasPaymentMethod?: boolean | number
+ /** Billing portal URL for payment method update (returned when no payment method exists) */
+ billingPortalUrl?: boolean | number
+ /** Updated current billing subscription */
+ currentBillingSubscription?: BillingSubscriptionGenqlSelection
+ /** All billing subscriptions */
+ billingSubscriptions?: BillingSubscriptionGenqlSelection
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
+export interface BillingResourceCreditUsageGenqlSelection{
+ productKey?: boolean | number
+ periodStart?: boolean | number
+ periodEnd?: boolean | number
+ usedCredits?: boolean | number
+ grantedCredits?: boolean | number
+ rolloverCredits?: boolean | number
+ totalGrantedCredits?: boolean | number
+ unitPriceCents?: boolean | number
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
+export interface BillingPlanGenqlSelection{
+ planKey?: boolean | number
+ baseProducts?: BillingLicensedProductGenqlSelection
+ resourceCreditProducts?: BillingLicensedProductGenqlSelection
+ meteredProducts?: BillingMeteredProductGenqlSelection
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
+export interface BillingPaymentIntentGenqlSelection{
+ clientSecret?: boolean | number
+ paymentIntentType?: boolean | number
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
+export interface BillingSessionGenqlSelection{
+ url?: boolean | number
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
+export interface BillingUpdateGenqlSelection{
+ /** Current billing subscription */
+ currentBillingSubscription?: BillingSubscriptionGenqlSelection
+ /** All billing subscriptions */
+ billingSubscriptions?: BillingSubscriptionGenqlSelection
+ __typename?: boolean | number
+ __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
+ usageByApplication?: UsageBreakdownItemGenqlSelection
+ usageByModel?: UsageBreakdownItemGenqlSelection
+ timeSeries?: UsageTimeSeriesGenqlSelection
+ periodStart?: boolean | number
+ periodEnd?: boolean | number
+ userDailyUsage?: UsageUserDailyGenqlSelection
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
export interface UsageLimitOperationDefinitionGenqlSelection{
operationType?: boolean | number
allowedUnits?: boolean | number
@@ -5251,188 +5360,79 @@ export interface RecordSharingRoleDTOGenqlSelection{
export interface RecordSharingDTOGenqlSelection{
sharingMode?: boolean | number
- canManageSharing?: boolean | number
- permissions?: RecordPermissionsDTOGenqlSelection
- generalAccessLevel?: boolean | number
- defaultGeneralAccessLevel?: boolean | number
- hasManagedGeneralAccess?: boolean | number
- roles?: RecordSharingRoleDTOGenqlSelection
- shares?: RecordSharingGrantDTOGenqlSelection
- __typename?: boolean | number
- __scalar?: boolean | number
-}
-
-export interface RecordPermissionsResultGenqlSelection{
- objectMetadataId?: boolean | number
- recordId?: boolean | number
- permissions?: RecordPermissionsDTOGenqlSelection
- __typename?: boolean | number
- __scalar?: boolean | number
-}
-
-export interface JobStatusGenqlSelection{
- jobId?: boolean | number
- state?: boolean | number
- attemptsMade?: boolean | number
- failedReason?: boolean | number
- enqueuedAt?: boolean | number
- startedAt?: boolean | number
- finishedAt?: boolean | number
- __typename?: boolean | number
- __scalar?: boolean | number
-}
-
-export interface ObjectRecordEventPropertiesGenqlSelection{
- updatedFields?: boolean | number
- before?: boolean | number
- after?: boolean | number
- diff?: boolean | number
- __typename?: boolean | number
- __scalar?: boolean | number
-}
-
-export interface MetadataEventGenqlSelection{
- type?: boolean | number
- metadataName?: boolean | number
- recordId?: boolean | number
- properties?: ObjectRecordEventPropertiesGenqlSelection
- updatedCollectionHash?: boolean | number
- __typename?: boolean | number
- __scalar?: boolean | number
-}
-
-export interface ObjectRecordEventGenqlSelection{
- action?: boolean | number
- objectNameSingular?: boolean | number
- recordId?: boolean | number
- userId?: boolean | number
- workspaceMemberId?: boolean | number
- properties?: ObjectRecordEventPropertiesGenqlSelection
- __typename?: boolean | number
- __scalar?: boolean | number
-}
-
-export interface ObjectRecordEventWithQueryIdsGenqlSelection{
- queryIds?: boolean | number
- objectRecordEvent?: ObjectRecordEventGenqlSelection
- __typename?: boolean | number
- __scalar?: boolean | number
-}
-
-export interface EventSubscriptionGenqlSelection{
- eventStreamId?: boolean | number
- objectRecordEventsWithQueryIds?: ObjectRecordEventWithQueryIdsGenqlSelection
- metadataEvents?: MetadataEventGenqlSelection
- queueJobEvents?: JobStatusGenqlSelection
- __typename?: boolean | number
- __scalar?: boolean | number
-}
-
-export interface UserSessionGenqlSelection{
- id?: boolean | number
- workspaceId?: boolean | number
- authProvider?: boolean | number
- isImpersonating?: boolean | number
- userAgent?: boolean | number
- ipAddress?: boolean | number
- createdAt?: boolean | number
- lastActiveAt?: boolean | number
- expiresAt?: boolean | number
- isCurrent?: boolean | number
- __typename?: boolean | number
- __scalar?: boolean | number
-}
-
-export interface BillingEndTrialPeriodGenqlSelection{
- /** Updated subscription status */
- status?: boolean | number
- /** Boolean that confirms if a payment method was found */
- hasPaymentMethod?: boolean | number
- /** Billing portal URL for payment method update (returned when no payment method exists) */
- billingPortalUrl?: boolean | number
- /** Updated current billing subscription */
- currentBillingSubscription?: BillingSubscriptionGenqlSelection
- /** All billing subscriptions */
- billingSubscriptions?: BillingSubscriptionGenqlSelection
- __typename?: boolean | number
- __scalar?: boolean | number
-}
-
-export interface BillingResourceCreditUsageGenqlSelection{
- productKey?: boolean | number
- periodStart?: boolean | number
- periodEnd?: boolean | number
- usedCredits?: boolean | number
- grantedCredits?: boolean | number
- rolloverCredits?: boolean | number
- totalGrantedCredits?: boolean | number
- unitPriceCents?: boolean | number
- __typename?: boolean | number
- __scalar?: boolean | number
-}
-
-export interface BillingPlanGenqlSelection{
- planKey?: boolean | number
- baseProducts?: BillingLicensedProductGenqlSelection
- resourceCreditProducts?: BillingLicensedProductGenqlSelection
- meteredProducts?: BillingMeteredProductGenqlSelection
+ canManageSharing?: boolean | number
+ permissions?: RecordPermissionsDTOGenqlSelection
+ generalAccessLevel?: boolean | number
+ defaultGeneralAccessLevel?: boolean | number
+ hasManagedGeneralAccess?: boolean | number
+ roles?: RecordSharingRoleDTOGenqlSelection
+ shares?: RecordSharingGrantDTOGenqlSelection
__typename?: boolean | number
__scalar?: boolean | number
}
-export interface BillingPaymentIntentGenqlSelection{
- clientSecret?: boolean | number
- paymentIntentType?: boolean | number
+export interface RecordPermissionsResultGenqlSelection{
+ objectMetadataId?: boolean | number
+ recordId?: boolean | number
+ permissions?: RecordPermissionsDTOGenqlSelection
__typename?: boolean | number
__scalar?: boolean | number
}
-export interface BillingSessionGenqlSelection{
- url?: boolean | number
+export interface JobStatusGenqlSelection{
+ jobId?: boolean | number
+ state?: boolean | number
+ attemptsMade?: boolean | number
+ failedReason?: boolean | number
+ enqueuedAt?: boolean | number
+ startedAt?: boolean | number
+ finishedAt?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
-export interface BillingUpdateGenqlSelection{
- /** Current billing subscription */
- currentBillingSubscription?: BillingSubscriptionGenqlSelection
- /** All billing subscriptions */
- billingSubscriptions?: BillingSubscriptionGenqlSelection
+export interface ObjectRecordEventPropertiesGenqlSelection{
+ updatedFields?: boolean | number
+ before?: boolean | number
+ after?: boolean | number
+ diff?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
-export interface UsageBreakdownItemGenqlSelection{
- key?: boolean | number
- label?: boolean | number
- creditsUsed?: boolean | number
+export interface MetadataEventGenqlSelection{
+ type?: boolean | number
+ metadataName?: boolean | number
+ recordId?: boolean | number
+ properties?: ObjectRecordEventPropertiesGenqlSelection
+ updatedCollectionHash?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
-export interface UsageTimeSeriesGenqlSelection{
- date?: boolean | number
- creditsUsed?: boolean | number
+export interface ObjectRecordEventGenqlSelection{
+ action?: boolean | number
+ objectNameSingular?: boolean | number
+ recordId?: boolean | number
+ userId?: boolean | number
+ workspaceMemberId?: boolean | number
+ properties?: ObjectRecordEventPropertiesGenqlSelection
__typename?: boolean | number
__scalar?: boolean | number
}
-export interface UsageUserDailyGenqlSelection{
- userWorkspaceId?: boolean | number
- dailyUsage?: UsageTimeSeriesGenqlSelection
+export interface ObjectRecordEventWithQueryIdsGenqlSelection{
+ queryIds?: boolean | number
+ objectRecordEvent?: ObjectRecordEventGenqlSelection
__typename?: boolean | number
__scalar?: boolean | number
}
-export interface UsageAnalyticsGenqlSelection{
- usageByUser?: UsageBreakdownItemGenqlSelection
- usageByOperationType?: UsageBreakdownItemGenqlSelection
- usageByApplication?: UsageBreakdownItemGenqlSelection
- usageByModel?: UsageBreakdownItemGenqlSelection
- timeSeries?: UsageTimeSeriesGenqlSelection
- periodStart?: boolean | number
- periodEnd?: boolean | number
- userDailyUsage?: UsageUserDailyGenqlSelection
+export interface EventSubscriptionGenqlSelection{
+ eventStreamId?: boolean | number
+ objectRecordEventsWithQueryIds?: ObjectRecordEventWithQueryIdsGenqlSelection
+ metadataEvents?: MetadataEventGenqlSelection
+ queueJobEvents?: JobStatusGenqlSelection
__typename?: boolean | number
__scalar?: boolean | number
}
@@ -7318,6 +7318,7 @@ export interface QueryGenqlSelection{
usageQuotasWithConsumption?: UsageQuotaWithConsumptionGenqlSelection
usageQuotaDefinitions?: UsageQuotaDefinitionsGenqlSelection
usageQuotaScopeConsumption?: (UsageQuotaScopeConsumptionGenqlSelection & { __args: {input: UsageQuotaScopeInput} })
+ getUsageAnalytics?: (UsageAnalyticsGenqlSelection & { __args?: {input?: (UsageAnalyticsInput | null)} })
getPageLayoutWidgets?: (PageLayoutWidgetGenqlSelection & { __args: {pageLayoutTabId: Scalars['String']} })
getPageLayoutWidget?: (PageLayoutWidgetGenqlSelection & { __args: {id: Scalars['String']} })
getPageLayoutTabs?: (PageLayoutTabGenqlSelection & { __args: {pageLayoutId: Scalars['String']} })
@@ -7357,7 +7358,6 @@ export interface QueryGenqlSelection{
frontComponent?: (FrontComponentGenqlSelection & { __args: {id: Scalars['UUID']} })
getInviteSuggestions?: InviteSuggestionGenqlSelection
applicationConnectionProviders?: (ApplicationConnectionProviderGenqlSelection & { __args: {applicationId: Scalars['UUID']} })
- getUsageAnalytics?: (UsageAnalyticsGenqlSelection & { __args?: {input?: (UsageAnalyticsInput | null)} })
billingPortalSession?: (BillingSessionGenqlSelection & { __args?: {returnUrlPath?: (Scalars['String'] | null), forPaymentMethodUpdate?: (Scalars['Boolean'] | null)} })
listPlans?: BillingPlanGenqlSelection
getResourceCreditUsage?: BillingResourceCreditUsageGenqlSelection
@@ -7459,6 +7459,8 @@ export interface RecordTargetInput {objectMetadataId: Scalars['UUID'],recordId:
export interface UsageQuotaScopeInput {resourceType: UsageResourceType,operationType: UsageOperationType,spenderType: Scalars['String'],spenderId?: (Scalars['String'] | null),periodUnit: Scalars['String'],unit: UsageUnit}
+export interface UsageAnalyticsInput {periodStart?: (Scalars['DateTime'] | null),periodEnd?: (Scalars['DateTime'] | null),userWorkspaceId?: (Scalars['String'] | null),operationTypes?: (UsageOperationType[] | null)}
+
export interface AgentIdInput {
/** The id of the agent. */
id: Scalars['UUID']}
@@ -7469,8 +7471,6 @@ export interface LogicFunctionIdInput {
/** The id of the function. */
id: Scalars['ID']}
-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 PreviewMessageCampaignAudienceInput {listId: Scalars['String'],unsubscribeTopicId?: (Scalars['String'] | null)}
@@ -9000,6 +9000,94 @@ export interface CreateRecordExportInput {objectMetadataId: Scalars['UUID'],fiel
+ const UserSession_possibleTypes: string[] = ['UserSession']
+ export const isUserSession = (obj?: { __typename?: any } | null): obj is UserSession => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isUserSession"')
+ return UserSession_possibleTypes.includes(obj.__typename)
+ }
+
+
+
+ const BillingEndTrialPeriod_possibleTypes: string[] = ['BillingEndTrialPeriod']
+ export const isBillingEndTrialPeriod = (obj?: { __typename?: any } | null): obj is BillingEndTrialPeriod => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isBillingEndTrialPeriod"')
+ return BillingEndTrialPeriod_possibleTypes.includes(obj.__typename)
+ }
+
+
+
+ const BillingResourceCreditUsage_possibleTypes: string[] = ['BillingResourceCreditUsage']
+ export const isBillingResourceCreditUsage = (obj?: { __typename?: any } | null): obj is BillingResourceCreditUsage => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isBillingResourceCreditUsage"')
+ return BillingResourceCreditUsage_possibleTypes.includes(obj.__typename)
+ }
+
+
+
+ const BillingPlan_possibleTypes: string[] = ['BillingPlan']
+ export const isBillingPlan = (obj?: { __typename?: any } | null): obj is BillingPlan => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isBillingPlan"')
+ return BillingPlan_possibleTypes.includes(obj.__typename)
+ }
+
+
+
+ const BillingPaymentIntent_possibleTypes: string[] = ['BillingPaymentIntent']
+ export const isBillingPaymentIntent = (obj?: { __typename?: any } | null): obj is BillingPaymentIntent => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isBillingPaymentIntent"')
+ return BillingPaymentIntent_possibleTypes.includes(obj.__typename)
+ }
+
+
+
+ const BillingSession_possibleTypes: string[] = ['BillingSession']
+ export const isBillingSession = (obj?: { __typename?: any } | null): obj is BillingSession => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isBillingSession"')
+ return BillingSession_possibleTypes.includes(obj.__typename)
+ }
+
+
+
+ const BillingUpdate_possibleTypes: string[] = ['BillingUpdate']
+ export const isBillingUpdate = (obj?: { __typename?: any } | null): obj is BillingUpdate => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isBillingUpdate"')
+ return BillingUpdate_possibleTypes.includes(obj.__typename)
+ }
+
+
+
+ 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 UsageLimitOperationDefinition_possibleTypes: string[] = ['UsageLimitOperationDefinition']
export const isUsageLimitOperationDefinition = (obj?: { __typename?: any } | null): obj is UsageLimitOperationDefinition => {
if (!obj?.__typename) throw new Error('__typename is missing in "isUsageLimitOperationDefinition"')
@@ -9168,94 +9256,6 @@ export interface CreateRecordExportInput {objectMetadataId: Scalars['UUID'],fiel
- const UserSession_possibleTypes: string[] = ['UserSession']
- export const isUserSession = (obj?: { __typename?: any } | null): obj is UserSession => {
- if (!obj?.__typename) throw new Error('__typename is missing in "isUserSession"')
- return UserSession_possibleTypes.includes(obj.__typename)
- }
-
-
-
- const BillingEndTrialPeriod_possibleTypes: string[] = ['BillingEndTrialPeriod']
- export const isBillingEndTrialPeriod = (obj?: { __typename?: any } | null): obj is BillingEndTrialPeriod => {
- if (!obj?.__typename) throw new Error('__typename is missing in "isBillingEndTrialPeriod"')
- return BillingEndTrialPeriod_possibleTypes.includes(obj.__typename)
- }
-
-
-
- const BillingResourceCreditUsage_possibleTypes: string[] = ['BillingResourceCreditUsage']
- export const isBillingResourceCreditUsage = (obj?: { __typename?: any } | null): obj is BillingResourceCreditUsage => {
- if (!obj?.__typename) throw new Error('__typename is missing in "isBillingResourceCreditUsage"')
- return BillingResourceCreditUsage_possibleTypes.includes(obj.__typename)
- }
-
-
-
- const BillingPlan_possibleTypes: string[] = ['BillingPlan']
- export const isBillingPlan = (obj?: { __typename?: any } | null): obj is BillingPlan => {
- if (!obj?.__typename) throw new Error('__typename is missing in "isBillingPlan"')
- return BillingPlan_possibleTypes.includes(obj.__typename)
- }
-
-
-
- const BillingPaymentIntent_possibleTypes: string[] = ['BillingPaymentIntent']
- export const isBillingPaymentIntent = (obj?: { __typename?: any } | null): obj is BillingPaymentIntent => {
- if (!obj?.__typename) throw new Error('__typename is missing in "isBillingPaymentIntent"')
- return BillingPaymentIntent_possibleTypes.includes(obj.__typename)
- }
-
-
-
- const BillingSession_possibleTypes: string[] = ['BillingSession']
- export const isBillingSession = (obj?: { __typename?: any } | null): obj is BillingSession => {
- if (!obj?.__typename) throw new Error('__typename is missing in "isBillingSession"')
- return BillingSession_possibleTypes.includes(obj.__typename)
- }
-
-
-
- const BillingUpdate_possibleTypes: string[] = ['BillingUpdate']
- export const isBillingUpdate = (obj?: { __typename?: any } | null): obj is BillingUpdate => {
- if (!obj?.__typename) throw new Error('__typename is missing in "isBillingUpdate"')
- return BillingUpdate_possibleTypes.includes(obj.__typename)
- }
-
-
-
- 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 ApprovedAccessDomain_possibleTypes: string[] = ['ApprovedAccessDomain']
export const isApprovedAccessDomain = (obj?: { __typename?: any } | null): obj is ApprovedAccessDomain => {
if (!obj?.__typename) throw new Error('__typename is missing in "isApprovedAccessDomain"')
diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.ts
index aa5d373b2ad..a66f56635d4 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts
@@ -56,19 +56,19 @@ export default {
136,
151,
155,
- 157,
- 158,
- 160,
- 163,
- 170,
- 173,
+ 168,
+ 169,
+ 171,
174,
- 175,
- 176,
- 179,
- 182,
+ 181,
+ 184,
185,
+ 186,
187,
+ 190,
+ 193,
+ 196,
+ 198,
208,
213,
220,
@@ -3139,12 +3139,208 @@ export default {
]
},
"LogicFunctionExecutionStatus": {},
+ "UserSession": {
+ "id": [
+ 3
+ ],
+ "workspaceId": [
+ 3
+ ],
+ "authProvider": [
+ 1
+ ],
+ "isImpersonating": [
+ 8
+ ],
+ "userAgent": [
+ 1
+ ],
+ "ipAddress": [
+ 1
+ ],
+ "createdAt": [
+ 4
+ ],
+ "lastActiveAt": [
+ 4
+ ],
+ "expiresAt": [
+ 4
+ ],
+ "isCurrent": [
+ 8
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "BillingEndTrialPeriod": {
+ "status": [
+ 95
+ ],
+ "hasPaymentMethod": [
+ 8
+ ],
+ "billingPortalUrl": [
+ 1
+ ],
+ "currentBillingSubscription": [
+ 94
+ ],
+ "billingSubscriptions": [
+ 94
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "BillingResourceCreditUsage": {
+ "productKey": [
+ 85
+ ],
+ "periodStart": [
+ 4
+ ],
+ "periodEnd": [
+ 4
+ ],
+ "usedCredits": [
+ 15
+ ],
+ "grantedCredits": [
+ 15
+ ],
+ "rolloverCredits": [
+ 15
+ ],
+ "totalGrantedCredits": [
+ 15
+ ],
+ "unitPriceCents": [
+ 15
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "BillingPlan": {
+ "planKey": [
+ 83
+ ],
+ "baseProducts": [
+ 91
+ ],
+ "resourceCreditProducts": [
+ 91
+ ],
+ "meteredProducts": [
+ 92
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "BillingPaymentIntent": {
+ "clientSecret": [
+ 1
+ ],
+ "paymentIntentType": [
+ 1
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "BillingSession": {
+ "url": [
+ 1
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "BillingUpdate": {
+ "currentBillingSubscription": [
+ 94
+ ],
+ "billingSubscriptions": [
+ 94
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "UsageBreakdownItem": {
+ "key": [
+ 1
+ ],
+ "label": [
+ 1
+ ],
+ "creditsUsed": [
+ 15
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "UsageTimeSeries": {
+ "date": [
+ 1
+ ],
+ "creditsUsed": [
+ 15
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "UsageUserDaily": {
+ "userWorkspaceId": [
+ 1
+ ],
+ "dailyUsage": [
+ 164
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "UsageAnalytics": {
+ "usageByUser": [
+ 163
+ ],
+ "usageByOperationType": [
+ 163
+ ],
+ "usageByApplication": [
+ 163
+ ],
+ "usageByModel": [
+ 163
+ ],
+ "timeSeries": [
+ 164
+ ],
+ "periodStart": [
+ 4
+ ],
+ "periodEnd": [
+ 4
+ ],
+ "userDailyUsage": [
+ 165
+ ],
+ "__typename": [
+ 1
+ ]
+ },
"UsageLimitOperationDefinition": {
"operationType": [
- 157
+ 168
],
"allowedUnits": [
- 158
+ 169
],
"__typename": [
1
@@ -3154,13 +3350,13 @@ export default {
"UsageUnit": {},
"UsageQuotaDefinition": {
"resourceType": [
- 160
+ 171
],
"limitKind": [
1
],
"allowedOperations": [
- 156
+ 167
],
"allowedSpenderTypes": [
1
@@ -3172,7 +3368,7 @@ export default {
"UsageResourceType": {},
"UsageQuotaDefinitions": {
"definitions": [
- 159
+ 170
],
"isIntraWorkspaceLimitEntitled": [
8
@@ -3189,10 +3385,10 @@ export default {
3
],
"resourceType": [
- 160
+ 171
],
"operationType": [
- 157
+ 168
],
"spenderType": [
1
@@ -3207,19 +3403,19 @@ export default {
1
],
"unit": [
- 158
+ 169
],
"limitValue": [
- 163
+ 174
],
"isEnforced": [
8
],
"consumedValue": [
- 163
+ 174
],
"remainingValue": [
- 163
+ 174
],
"periodStart": [
4
@@ -3234,7 +3430,7 @@ export default {
"BigInt": {},
"UsageQuotaScopeConsumption": {
"consumedValue": [
- 163
+ 174
],
"periodStart": [
4
@@ -3251,10 +3447,10 @@ export default {
3
],
"resourceType": [
- 160
+ 171
],
"operationType": [
- 157
+ 168
],
"spenderType": [
1
@@ -3272,13 +3468,13 @@ export default {
1
],
"unit": [
- 158
+ 169
],
"limitValue": [
- 163
+ 174
],
"burstValue": [
- 163
+ 174
],
"createdAt": [
4
@@ -3358,7 +3554,7 @@ export default {
3
],
"type": [
- 170
+ 181
],
"name": [
1
@@ -3391,7 +3587,7 @@ export default {
4
],
"targetRecordIdentifier": [
- 168
+ 179
],
"__typename": [
1
@@ -3417,10 +3613,10 @@ export default {
},
"RecordSharingGrantDTO": {
"id": [
- 173
+ 184
],
"principalType": [
- 174
+ 185
],
"principalId": [
3
@@ -3429,10 +3625,10 @@ export default {
3
],
"accessLevel": [
- 175
+ 186
],
"rowCause": [
- 176
+ 187
],
"__typename": [
1
@@ -3461,28 +3657,28 @@ export default {
},
"RecordSharingDTO": {
"sharingMode": [
- 179
+ 190
],
"canManageSharing": [
8
],
"permissions": [
- 171
+ 182
],
"generalAccessLevel": [
- 175
+ 186
],
"defaultGeneralAccessLevel": [
- 175
+ 186
],
"hasManagedGeneralAccess": [
8
],
"roles": [
- 177
+ 188
],
"shares": [
- 172
+ 183
],
"__typename": [
1
@@ -3497,7 +3693,7 @@ export default {
3
],
"permissions": [
- 171
+ 182
],
"__typename": [
1
@@ -3508,309 +3704,113 @@ export default {
1
],
"state": [
- 182
+ 193
],
"attemptsMade": [
31
],
"failedReason": [
- 1
- ],
- "enqueuedAt": [
- 15
- ],
- "startedAt": [
- 15
- ],
- "finishedAt": [
- 15
- ],
- "__typename": [
- 1
- ]
- },
- "JobState": {},
- "ObjectRecordEventProperties": {
- "updatedFields": [
- 1
- ],
- "before": [
- 9
- ],
- "after": [
- 9
- ],
- "diff": [
- 9
- ],
- "__typename": [
- 1
- ]
- },
- "MetadataEvent": {
- "type": [
- 185
- ],
- "metadataName": [
- 1
- ],
- "recordId": [
- 1
- ],
- "properties": [
- 183
- ],
- "updatedCollectionHash": [
- 1
- ],
- "__typename": [
- 1
- ]
- },
- "MetadataEventAction": {},
- "ObjectRecordEvent": {
- "action": [
- 187
- ],
- "objectNameSingular": [
- 1
- ],
- "recordId": [
- 1
- ],
- "userId": [
- 1
- ],
- "workspaceMemberId": [
- 1
- ],
- "properties": [
- 183
- ],
- "__typename": [
- 1
- ]
- },
- "DatabaseEventAction": {},
- "ObjectRecordEventWithQueryIds": {
- "queryIds": [
- 1
- ],
- "objectRecordEvent": [
- 186
- ],
- "__typename": [
- 1
- ]
- },
- "EventSubscription": {
- "eventStreamId": [
- 1
- ],
- "objectRecordEventsWithQueryIds": [
- 188
- ],
- "metadataEvents": [
- 184
- ],
- "queueJobEvents": [
- 181
- ],
- "__typename": [
- 1
- ]
- },
- "UserSession": {
- "id": [
- 3
- ],
- "workspaceId": [
- 3
- ],
- "authProvider": [
- 1
- ],
- "isImpersonating": [
- 8
- ],
- "userAgent": [
- 1
- ],
- "ipAddress": [
- 1
- ],
- "createdAt": [
- 4
- ],
- "lastActiveAt": [
- 4
- ],
- "expiresAt": [
- 4
- ],
- "isCurrent": [
- 8
- ],
- "__typename": [
- 1
- ]
- },
- "BillingEndTrialPeriod": {
- "status": [
- 95
- ],
- "hasPaymentMethod": [
- 8
- ],
- "billingPortalUrl": [
- 1
- ],
- "currentBillingSubscription": [
- 94
- ],
- "billingSubscriptions": [
- 94
- ],
- "__typename": [
- 1
- ]
- },
- "BillingResourceCreditUsage": {
- "productKey": [
- 85
- ],
- "periodStart": [
- 4
- ],
- "periodEnd": [
- 4
- ],
- "usedCredits": [
- 15
- ],
- "grantedCredits": [
- 15
+ 1
],
- "rolloverCredits": [
+ "enqueuedAt": [
15
],
- "totalGrantedCredits": [
+ "startedAt": [
15
],
- "unitPriceCents": [
+ "finishedAt": [
15
],
"__typename": [
1
]
},
- "BillingPlan": {
- "planKey": [
- 83
+ "JobState": {},
+ "ObjectRecordEventProperties": {
+ "updatedFields": [
+ 1
],
- "baseProducts": [
- 91
+ "before": [
+ 9
],
- "resourceCreditProducts": [
- 91
+ "after": [
+ 9
],
- "meteredProducts": [
- 92
+ "diff": [
+ 9
],
"__typename": [
1
]
},
- "BillingPaymentIntent": {
- "clientSecret": [
- 1
+ "MetadataEvent": {
+ "type": [
+ 196
],
- "paymentIntentType": [
+ "metadataName": [
1
],
- "__typename": [
- 1
- ]
- },
- "BillingSession": {
- "url": [
+ "recordId": [
1
],
- "__typename": [
- 1
- ]
- },
- "BillingUpdate": {
- "currentBillingSubscription": [
- 94
+ "properties": [
+ 194
],
- "billingSubscriptions": [
- 94
+ "updatedCollectionHash": [
+ 1
],
"__typename": [
1
]
},
- "UsageBreakdownItem": {
- "key": [
- 1
+ "MetadataEventAction": {},
+ "ObjectRecordEvent": {
+ "action": [
+ 198
],
- "label": [
+ "objectNameSingular": [
1
],
- "creditsUsed": [
- 15
+ "recordId": [
+ 1
],
- "__typename": [
+ "userId": [
1
- ]
- },
- "UsageTimeSeries": {
- "date": [
+ ],
+ "workspaceMemberId": [
1
],
- "creditsUsed": [
- 15
+ "properties": [
+ 194
],
"__typename": [
1
]
},
- "UsageUserDaily": {
- "userWorkspaceId": [
+ "DatabaseEventAction": {},
+ "ObjectRecordEventWithQueryIds": {
+ "queryIds": [
1
],
- "dailyUsage": [
- 198
+ "objectRecordEvent": [
+ 197
],
"__typename": [
1
]
},
- "UsageAnalytics": {
- "usageByUser": [
- 197
- ],
- "usageByOperationType": [
- 197
- ],
- "usageByApplication": [
- 197
- ],
- "usageByModel": [
- 197
- ],
- "timeSeries": [
- 198
+ "EventSubscription": {
+ "eventStreamId": [
+ 1
],
- "periodStart": [
- 4
+ "objectRecordEventsWithQueryIds": [
+ 199
],
- "periodEnd": [
- 4
+ "metadataEvents": [
+ 195
],
- "userDailyUsage": [
- 199
+ "queueJobEvents": [
+ 192
],
"__typename": [
1
@@ -4669,7 +4669,7 @@ export default {
},
"AppConnection": {
"id": [
- 173
+ 184
],
"providerName": [
1
@@ -6788,10 +6788,10 @@ export default {
},
"AiChatUsage": {
"limitValue": [
- 163
+ 174
],
"consumedValue": [
- 163
+ 174
],
"periodEnd": [
4
@@ -6846,7 +6846,7 @@ export default {
},
"AgentChatThread": {
"id": [
- 173
+ 184
],
"title": [
1
@@ -7498,7 +7498,7 @@ export default {
},
"Query": {
"recordSharing": [
- 178,
+ 189,
{
"target": [
426,
@@ -7507,7 +7507,7 @@ export default {
}
],
"recordPermissions": [
- 180,
+ 191,
{
"targets": [
426,
@@ -7516,10 +7516,10 @@ export default {
}
],
"navigationMenuItems": [
- 169
+ 180
],
"navigationMenuItem": [
- 169,
+ 180,
{
"id": [
3,
@@ -7565,16 +7565,16 @@ export default {
}
],
"usageLimits": [
- 165
+ 176
],
"usageQuotasWithConsumption": [
- 162
+ 173
],
"usageQuotaDefinitions": [
- 161
+ 172
],
"usageQuotaScopeConsumption": [
- 164,
+ 175,
{
"input": [
427,
@@ -7582,6 +7582,14 @@ export default {
]
}
],
+ "getUsageAnalytics": [
+ 166,
+ {
+ "input": [
+ 428
+ ]
+ }
+ ],
"getPageLayoutWidgets": [
103,
{
@@ -7736,7 +7744,7 @@ export default {
10,
{
"input": [
- 428,
+ 429,
"AgentIdInput!"
]
}
@@ -7749,7 +7757,7 @@ export default {
"CursorPaging!"
],
"filter": [
- 429,
+ 430,
"ObjectFilter!"
]
}
@@ -7776,13 +7784,13 @@ export default {
}
],
"currentUserSessions": [
- 190
+ 156
],
"findOneLogicFunction": [
23,
{
"input": [
- 430,
+ 431,
"LogicFunctionIdInput!"
]
}
@@ -7794,7 +7802,7 @@ export default {
9,
{
"input": [
- 430,
+ 431,
"LogicFunctionIdInput!"
]
}
@@ -7803,7 +7811,7 @@ export default {
1,
{
"input": [
- 430,
+ 431,
"LogicFunctionIdInput!"
]
}
@@ -7844,16 +7852,8 @@ export default {
]
}
],
- "getUsageAnalytics": [
- 200,
- {
- "input": [
- 431
- ]
- }
- ],
"billingPortalSession": [
- 195,
+ 161,
{
"returnUrlPath": [
1
@@ -7864,10 +7864,10 @@ export default {
}
],
"listPlans": [
- 193
+ 159
],
"getResourceCreditUsage": [
- 192
+ 158
],
"findWorkspaceInvitations": [
205
@@ -8043,7 +8043,7 @@ export default {
}
],
"findInstallApplicationJobStatus": [
- 181,
+ 192,
{
"universalIdentifier": [
1,
@@ -8052,7 +8052,7 @@ export default {
}
],
"findUninstallApplicationJobStatus": [
- 181,
+ 192,
{
"universalIdentifier": [
1,
@@ -8234,7 +8234,7 @@ export default {
}
],
"getJobs": [
- 181,
+ 192,
{
"jobIds": [
1,
@@ -8254,7 +8254,7 @@ export default {
246,
{
"id": [
- 173,
+ 184,
"ID!"
]
}
@@ -8512,10 +8512,10 @@ export default {
},
"UsageQuotaScopeInput": {
"resourceType": [
- 160
+ 171
],
"operationType": [
- 157
+ 168
],
"spenderType": [
1
@@ -8527,7 +8527,24 @@ export default {
1
],
"unit": [
- 158
+ 169
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "UsageAnalyticsInput": {
+ "periodStart": [
+ 4
+ ],
+ "periodEnd": [
+ 4
+ ],
+ "userWorkspaceId": [
+ 1
+ ],
+ "operationTypes": [
+ 168
],
"__typename": [
1
@@ -8543,10 +8560,10 @@ export default {
},
"ObjectFilter": {
"and": [
- 429
+ 430
],
"or": [
- 429
+ 430
],
"id": [
34
@@ -8581,24 +8598,7 @@ export default {
},
"LogicFunctionIdInput": {
"id": [
- 173
- ],
- "__typename": [
- 1
- ]
- },
- "UsageAnalyticsInput": {
- "periodStart": [
- 4
- ],
- "periodEnd": [
- 4
- ],
- "userWorkspaceId": [
- 1
- ],
- "operationTypes": [
- 157
+ 184
],
"__typename": [
1
@@ -8799,20 +8799,20 @@ export default {
}
],
"setRecordGeneralAccess": [
- 178,
+ 189,
{
"target": [
426,
"RecordTargetInput!"
],
"accessLevel": [
- 175,
+ 186,
"RecordShareAccessLevel!"
]
}
],
"setRecordShare": [
- 178,
+ 189,
{
"target": [
426,
@@ -8823,13 +8823,13 @@ export default {
"RecordSharePrincipalInput!"
],
"accessLevel": [
- 175,
+ 186,
"RecordShareAccessLevel!"
]
}
],
"removeRecordShare": [
- 178,
+ 189,
{
"target": [
426,
@@ -8842,7 +8842,7 @@ export default {
}
],
"createManyNavigationMenuItems": [
- 169,
+ 180,
{
"inputs": [
451,
@@ -8851,7 +8851,7 @@ export default {
}
],
"createNavigationMenuItem": [
- 169,
+ 180,
{
"input": [
451,
@@ -8860,7 +8860,7 @@ export default {
}
],
"updateManyNavigationMenuItems": [
- 169,
+ 180,
{
"inputs": [
452,
@@ -8869,7 +8869,7 @@ export default {
}
],
"updateNavigationMenuItem": [
- 169,
+ 180,
{
"input": [
452,
@@ -8878,7 +8878,7 @@ export default {
}
],
"deleteManyNavigationMenuItems": [
- 169,
+ 180,
{
"ids": [
3,
@@ -8887,7 +8887,7 @@ export default {
}
],
"deleteNavigationMenuItem": [
- 169,
+ 180,
{
"id": [
3,
@@ -8896,7 +8896,7 @@ export default {
}
],
"createFileUpload": [
- 167,
+ 178,
{
"filename": [
1,
@@ -8919,7 +8919,7 @@ export default {
}
],
"completeFileUpload": [
- 166,
+ 177,
{
"fileId": [
1,
@@ -8943,7 +8943,7 @@ export default {
}
],
"uploadWorkspaceLogo": [
- 166,
+ 177,
{
"file": [
454,
@@ -8952,7 +8952,7 @@ export default {
}
],
"uploadWorkspaceMemberProfilePicture": [
- 166,
+ 177,
{
"file": [
454,
@@ -8961,7 +8961,7 @@ export default {
}
],
"completeWorkspaceLogoUpload": [
- 166,
+ 177,
{
"fileId": [
1,
@@ -8970,7 +8970,7 @@ export default {
}
],
"completeWorkspaceMemberProfilePictureUpload": [
- 166,
+ 177,
{
"fileId": [
1,
@@ -8979,7 +8979,7 @@ export default {
}
],
"uploadFilesFieldFileByUniversalIdentifier": [
- 166,
+ 177,
{
"file": [
454,
@@ -8992,7 +8992,7 @@ export default {
}
],
"createUsageLimit": [
- 165,
+ 176,
{
"input": [
455,
@@ -9001,7 +9001,7 @@ export default {
}
],
"updateUsageLimit": [
- 165,
+ 176,
{
"input": [
456,
@@ -9393,7 +9393,7 @@ export default {
10,
{
"input": [
- 428,
+ 429,
"AgentIdInput!"
]
}
@@ -9468,7 +9468,7 @@ export default {
23,
{
"input": [
- 430,
+ 431,
"LogicFunctionIdInput!"
]
}
@@ -9627,7 +9627,7 @@ export default {
203
],
"checkoutSession": [
- 195,
+ 161,
{
"recurringInterval": [
87,
@@ -9647,7 +9647,7 @@ export default {
}
],
"createSubscriptionPaymentIntent": [
- 194,
+ 160,
{
"recurringInterval": [
87,
@@ -9671,22 +9671,22 @@ export default {
}
],
"createBillingPaymentMethodSetupIntent": [
- 194
+ 160
],
"switchSubscriptionInterval": [
- 196
+ 162
],
"switchBillingPlan": [
- 196
+ 162
],
"cancelSwitchBillingPlan": [
- 196
+ 162
],
"cancelSwitchBillingInterval": [
- 196
+ 162
],
"setResourceCreditSubscriptionPrice": [
- 196,
+ 162,
{
"priceId": [
1,
@@ -9695,10 +9695,10 @@ export default {
}
],
"endSubscriptionTrialPeriod": [
- 191
+ 157
],
"cancelSwitchResourceCreditPrice": [
- 196
+ 162
],
"deleteWorkspaceInvitation": [
1,
@@ -10954,7 +10954,7 @@ export default {
}
],
"uploadNewWorkspaceLogo": [
- 166,
+ 177,
{
"workspaceId": [
1,
@@ -10967,7 +10967,7 @@ export default {
}
],
"createNewWorkspaceLogoUpload": [
- 167,
+ 178,
{
"workspaceId": [
1,
@@ -10984,7 +10984,7 @@ export default {
}
],
"completeNewWorkspaceLogoUpload": [
- 166,
+ 177,
{
"workspaceId": [
1,
@@ -11519,7 +11519,7 @@ export default {
3
],
"type": [
- 170
+ 181
],
"name": [
1
@@ -11586,10 +11586,10 @@ export default {
"Upload": {},
"CreateUsageLimitInput": {
"resourceType": [
- 160
+ 171
],
"operationType": [
- 157
+ 168
],
"spenderType": [
1
@@ -11607,13 +11607,13 @@ export default {
1
],
"unit": [
- 158
+ 169
],
"limitValue": [
- 163
+ 174
],
"burstValue": [
- 163
+ 174
],
"__typename": [
1
@@ -14161,7 +14161,7 @@ export default {
},
"ReportAppConnectionAuthFailureInput": {
"id": [
- 173
+ 184
],
"reason": [
1
@@ -14580,7 +14580,7 @@ export default {
},
"Subscription": {
"onEventSubscription": [
- 189,
+ 200,
{
"eventStreamId": [
1,
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 5aed1f03b54..ee5a35b88cd 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
@@ -11,7 +11,6 @@ import { ThrottlerModule } from 'src/engine/core-modules/throttler/throttler.mod
import { TwentyConfigModule } from 'src/engine/core-modules/twenty-config/twenty-config.module';
import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
import { UsageLimitModule } from 'src/engine/core-modules/usage-limit/usage-limit.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';
@@ -24,7 +23,6 @@ import { WorkspaceEventEmitterModule } from 'src/engine/workspace-event-emitter/
TwentyConfigModule,
TypeOrmModule.forFeature([UserWorkspaceEntity]),
UsageLimitModule,
- 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 74c81e7f480..09868a01d8b 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
@@ -17,7 +17,6 @@ import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/serv
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 { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
type AppChargeableOperationType =
@@ -44,7 +43,6 @@ export class AppBillingService {
private readonly logger = new Logger(AppBillingService.name);
constructor(
- private readonly usageRecorderService: UsageRecorderService,
private readonly usageLimitQuotaService: UsageLimitQuotaService,
private readonly workspaceCacheService: WorkspaceCacheService,
@InjectRepository(UserWorkspaceEntity)
@@ -75,34 +73,24 @@ export class AppBillingService {
`${charge.creditsUsedMicro} micro-credits (${charge.quantity} ${unit}, ${operationType})`,
);
- const spenders = {
- userWorkspaceId: attributedUserWorkspaceId,
- applicationId,
- };
-
- await this.usageLimitQuotaService.consumeQuota({
+ await this.usageLimitQuotaService.charge({
workspaceId,
- resourceType: UsageResourceType.APP,
- operationType,
- spenders,
- cost: {
- [UsageUnit.CREDIT]: charge.creditsUsedMicro,
- [unit]: charge.quantity,
- },
+ events: [
+ {
+ resourceType: UsageResourceType.APP,
+ operationType,
+ creditsUsedMicro: charge.creditsUsedMicro,
+ quantity: charge.quantity,
+ unit,
+ resourceId: applicationId,
+ resourceContext: charge.operation ?? charge.resourceContext ?? null,
+ spenders: {
+ userWorkspaceId: attributedUserWorkspaceId,
+ applicationId,
+ },
+ },
+ ],
});
-
- await this.usageRecorderService.record(workspaceId, [
- {
- resourceType: UsageResourceType.APP,
- operationType,
- creditsUsedMicro: charge.creditsUsedMicro,
- quantity: charge.quantity,
- unit,
- resourceId: applicationId,
- resourceContext: charge.operation ?? charge.resourceContext ?? null,
- spenders,
- },
- ]);
}
private async resolveOperationType({
diff --git a/packages/twenty-server/src/engine/core-modules/billing/app-billing/application-recurring-charge.module.ts b/packages/twenty-server/src/engine/core-modules/billing/app-billing/application-recurring-charge.module.ts
index 7a8bbf2ec71..57622f9735d 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/app-billing/application-recurring-charge.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/application-recurring-charge.module.ts
@@ -6,7 +6,8 @@ import { TypeOrmModule } from '@nestjs/typeorm';
import { ApplicationRecurringChargeService } from 'src/engine/core-modules/billing/app-billing/application-recurring-charge.service';
import { ApplicationRecurringChargeCronCommand } from 'src/engine/core-modules/billing/app-billing/crons/commands/application-recurring-charge.cron.command';
import { BillingModule } from 'src/engine/core-modules/billing/billing.module';
-import { UsageModule } from 'src/engine/core-modules/usage/usage.module';
+import { UsageLimitModule } from 'src/engine/core-modules/usage-limit/usage-limit.module';
+import { UsageAnalyticsModule } from 'src/engine/core-modules/usage/usage-analytics.module';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
import { WorkspaceEventEmitterModule } from 'src/engine/workspace-event-emitter/workspace-event-emitter.module';
@@ -15,7 +16,8 @@ import { WorkspaceEventEmitterModule } from 'src/engine/workspace-event-emitter/
imports: [
BillingModule,
TypeOrmModule.forFeature([WorkspaceEntity]),
- UsageModule,
+ UsageAnalyticsModule,
+ UsageLimitModule,
WorkspaceCacheModule,
WorkspaceEventEmitterModule,
],
diff --git a/packages/twenty-server/src/engine/core-modules/billing/app-billing/application-recurring-charge.service.ts b/packages/twenty-server/src/engine/core-modules/billing/app-billing/application-recurring-charge.service.ts
index 697b7393881..d918c2d5bb1 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/app-billing/application-recurring-charge.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/application-recurring-charge.service.ts
@@ -11,8 +11,8 @@ import { collectDueRecurringCharges } from 'src/engine/core-modules/billing/app-
import { NO_BILLING_SUBSCRIPTION } from 'src/engine/core-modules/billing/constants/no-billing-subscription.constant';
import { SubscriptionInterval } from 'src/engine/core-modules/billing/enums/billing-subscription-interval.enum';
import { BillingService } from 'src/engine/core-modules/billing/services/billing.service';
+import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';
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 { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
@@ -28,7 +28,7 @@ export class ApplicationRecurringChargeService {
private readonly billingService: BillingService,
private readonly workspaceCacheService: WorkspaceCacheService,
private readonly usageAnalyticsService: UsageAnalyticsService,
- private readonly usageRecorderService: UsageRecorderService,
+ private readonly usageLimitQuotaService: UsageLimitQuotaService,
private readonly workspaceOrmManager: WorkspaceOrmManager,
) {}
@@ -103,7 +103,7 @@ export class ApplicationRecurringChargeService {
return 0;
}
- await this.usageRecorderService.record(workspaceId, events);
+ await this.usageLimitQuotaService.charge({ workspaceId, events });
this.logger.log(
`Raised ${events.length} recurring app charge(s) for workspace ${workspaceId}`,
diff --git a/packages/twenty-server/src/engine/core-modules/event-logs/live/event-log-live.module.ts b/packages/twenty-server/src/engine/core-modules/event-logs/live/event-log-live.module.ts
index ecfd72441d8..c05e9ec1575 100644
--- a/packages/twenty-server/src/engine/core-modules/event-logs/live/event-log-live.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/event-logs/live/event-log-live.module.ts
@@ -2,10 +2,9 @@ import { Module } from '@nestjs/common';
import { CacheStorageModule } from 'src/engine/core-modules/cache-storage/cache-storage.module';
import { EventLogLiveService } from 'src/engine/core-modules/event-logs/live/event-log-live.service';
-import { SubscriptionsModule } from 'src/engine/subscriptions/subscriptions.module';
@Module({
- imports: [CacheStorageModule, SubscriptionsModule],
+ imports: [CacheStorageModule],
providers: [EventLogLiveService],
exports: [EventLogLiveService],
})
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 0ca3d568373..47630f6d09b 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,7 +13,6 @@ import { LogicFunctionExecutorService } from 'src/engine/core-modules/logic-func
import { SecretEncryptionModule } from 'src/engine/core-modules/secret-encryption/secret-encryption.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 { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { SubscriptionsModule } from 'src/engine/subscriptions/subscriptions.module';
import { LogicFunctionPrebuiltWarmUpModule } from 'src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/logic-function-prebuilt-warm-up.module';
@@ -34,7 +33,6 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
ApplicationModule,
ApplicationVariableEntityModule,
UsageLimitModule,
- 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 03be0ebbe4f..2923ce223a2 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
@@ -53,7 +53,6 @@ import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twent
import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.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 { 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';
@@ -110,7 +109,6 @@ export class LogicFunctionExecutorService {
private readonly subscriptionService: SubscriptionService,
private readonly eventLogLiveService: EventLogLiveService,
private readonly eventLogEmitterService: EventLogEmitterService,
- private readonly usageRecorderService: UsageRecorderService,
private readonly billingUsageService: BillingUsageService,
private readonly usageLimitQuotaService: UsageLimitQuotaService,
private readonly workspaceDomainsService: WorkspaceDomainsService,
@@ -605,29 +603,20 @@ export class LogicFunctionExecutorService {
functionName: flatLogicFunction.name,
});
- const spenders = {
- logicFunctionId: flatLogicFunction.id,
- applicationId: flatApplication.id,
- };
-
// Billing-exempt apps skip the invocation charge; their explicit chargeCredits and AI usage are still billed.
- const { usageEvents, cost } = buildLogicFunctionExecutionUsage({
- durationMs: result.billedDurationMs,
- isBillingExempt: isBillingExemptApplication(
- flatApplication.universalIdentifier,
- ),
- resourceId: flatLogicFunction.id,
- spenders,
- });
-
- await this.usageLimitQuotaService.consumeQuota({
+ await this.usageLimitQuotaService.charge({
workspaceId,
- resourceType: UsageResourceType.LOGIC_FUNCTION,
- operationType: UsageOperationType.CODE_EXECUTION,
- spenders,
- cost,
+ events: buildLogicFunctionExecutionUsage({
+ durationMs: result.billedDurationMs,
+ isBillingExempt: isBillingExemptApplication(
+ flatApplication.universalIdentifier,
+ ),
+ resourceId: flatLogicFunction.id,
+ spenders: {
+ logicFunctionId: flatLogicFunction.id,
+ applicationId: flatApplication.id,
+ },
+ }),
});
-
- await this.usageRecorderService.record(workspaceId, usageEvents);
}
}
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/__tests__/build-logic-function-execution-usage.util.spec.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/__tests__/build-logic-function-execution-usage.util.spec.ts
index 42a57d326f2..5abaf9e7d94 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/__tests__/build-logic-function-execution-usage.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/__tests__/build-logic-function-execution-usage.util.spec.ts
@@ -42,23 +42,17 @@ describe('buildLogicFunctionExecutionUsage', () => {
resourceId: LOGIC_FUNCTION_ID,
spenders: SPENDERS,
}),
- ).toEqual({
- usageEvents: [
- buildExpectedUsageEvent({
- creditsUsedMicro: 0,
- quantity: 1,
- unit: UsageUnit.INVOCATION,
- }),
- buildExpectedUsageEvent({
- creditsUsedMicro: 0,
- quantity: 0,
- unit: UsageUnit.MILLISECOND,
- }),
- ],
- cost: {
- [UsageUnit.CREDIT]: 0,
- [UsageUnit.INVOCATION]: 1,
- },
- });
+ ).toEqual([
+ buildExpectedUsageEvent({
+ creditsUsedMicro: 0,
+ quantity: 1,
+ unit: UsageUnit.INVOCATION,
+ }),
+ buildExpectedUsageEvent({
+ creditsUsedMicro: 0,
+ quantity: 0,
+ unit: UsageUnit.MILLISECOND,
+ }),
+ ]);
});
});
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/build-logic-function-execution-usage.util.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/build-logic-function-execution-usage.util.ts
index 09771e68760..7672aa0647d 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/build-logic-function-execution-usage.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/build-logic-function-execution-usage.util.ts
@@ -1,5 +1,4 @@
import { computeLogicFunctionExecutionCreditsMicro } from 'src/engine/core-modules/logic-function/logic-function-executor/utils/compute-logic-function-execution-credits-micro.util';
-import { type QuotaCost } from 'src/engine/core-modules/usage-limit/types/quota-cost.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';
@@ -16,11 +15,11 @@ export const buildLogicFunctionExecutionUsage = ({
isBillingExempt: boolean;
resourceId: string;
spenders: UsageSpenders;
-}): { usageEvents: RecordUsageInput[]; cost: QuotaCost } => {
+}): RecordUsageInput[] => {
const { invocationCreditsMicro, durationCreditsMicro, billedDurationMs } =
computeLogicFunctionExecutionCreditsMicro({ durationMs, isBillingExempt });
- const usageEvents: RecordUsageInput[] = [
+ return [
{
resourceType: UsageResourceType.LOGIC_FUNCTION,
operationType: UsageOperationType.CODE_EXECUTION,
@@ -40,12 +39,4 @@ export const buildLogicFunctionExecutionUsage = ({
spenders,
},
];
-
- return {
- usageEvents,
- cost: {
- [UsageUnit.CREDIT]: invocationCreditsMicro + durationCreditsMicro,
- [UsageUnit.INVOCATION]: 1,
- },
- };
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-quota.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-quota.service.ts
index 2024b481146..b5ffb089ac3 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-quota.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-quota.service.ts
@@ -1,6 +1,7 @@
import { Injectable, Logger, type OnModuleInit } from '@nestjs/common';
import { DiscoveryService } from '@nestjs/core';
+import uniqBy from 'lodash.uniqby';
import { isDefined } from 'twenty-shared/utils';
import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';
@@ -20,6 +21,7 @@ import { CreditAllowanceProvider } from 'src/engine/core-modules/usage-limit/int
import { UsageLimitEntitlementService } from 'src/engine/core-modules/usage-limit/services/usage-limit-entitlement.service';
import { UsagePeriodService } from 'src/engine/core-modules/usage-limit/services/usage-period.service';
import { type AllowanceQuotaCounter } from 'src/engine/core-modules/usage-limit/types/allowance-quota-counter.type';
+import { type ExhaustedKind } from 'src/engine/core-modules/usage-limit/types/exhausted-kind.type';
import { type ExhaustedScope } from 'src/engine/core-modules/usage-limit/types/exhausted-scope.type';
import { type FlatQuotaLimit } from 'src/engine/core-modules/usage-limit/types/flat-quota-limit.type';
import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
@@ -40,7 +42,7 @@ import { buildQuotaCounters } from 'src/engine/core-modules/usage-limit/utils/bu
import { buildQuotaDebits } from 'src/engine/core-modules/usage-limit/utils/build-quota-debits.util';
import { buildQuotaExhaustedScope } from 'src/engine/core-modules/usage-limit/utils/build-quota-exhausted-scope.util';
import { buildQuotaWarmLockKey } from 'src/engine/core-modules/usage-limit/utils/build-quota-warm-lock-key.util';
-import { clampQuotaCost } from 'src/engine/core-modules/usage-limit/utils/clamp-quota-cost.util';
+import { buildSpendersFromUsageSpenders } from 'src/engine/core-modules/usage-limit/utils/build-spenders-from-usage-spenders.util';
import { computeQuotaConsumed } from 'src/engine/core-modules/usage-limit/utils/compute-quota-consumed.util';
import { findCreditAllowanceProvider } from 'src/engine/core-modules/usage-limit/utils/find-credit-allowance-provider.util';
import { findExhaustedCounters } from 'src/engine/core-modules/usage-limit/utils/find-exhausted-counters.util';
@@ -53,8 +55,11 @@ import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usa
import { type 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 { UsageAnalyticsService } from 'src/engine/core-modules/usage/services/usage-analytics.service';
+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 { type UsageConsumptionRow } from 'src/engine/core-modules/usage/types/usage-consumption-row.type';
import { type UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';
+import { fromRecordUsageInputToUsageConsumptionRow } from 'src/engine/core-modules/usage/utils/from-record-usage-input-to-usage-consumption-row.util';
import { WorkspaceCacheException } from 'src/engine/workspace-cache/exceptions/workspace-cache.exception';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
@@ -63,7 +68,7 @@ const QUOTA_WARM_LOCK_OPTIONS = { ms: 50, maxRetries: 20, ttl: 10_000 };
type QuotaEnforcement = {
operation: 'assert' | 'consume';
resourceType: UsageResourceType;
- cost?: QuotaCost;
+ creditsUsedMicro?: number;
};
type QuotaConsumeArgs = {
@@ -86,6 +91,7 @@ export class UsageLimitQuotaService implements OnModuleInit {
private readonly cacheLockService: CacheLockService,
private readonly usagePeriodService: UsagePeriodService,
private readonly usageAnalyticsService: UsageAnalyticsService,
+ private readonly usageRecorderService: UsageRecorderService,
private readonly discoveryService: DiscoveryService,
private readonly usageLimitEntitlementService: UsageLimitEntitlementService,
private readonly metricsService: MetricsService,
@@ -111,26 +117,38 @@ export class UsageLimitQuotaService implements OnModuleInit {
);
}
- async consumeQuota({
- cost,
- ...args
- }: QuotaConsumeArgs & { cost: QuotaCost }): Promise<{
- exhausted: ExhaustedScope[];
- }> {
- const clampedCost = clampQuotaCost(cost);
-
- if (
- Object.values(UsageUnit).some((unit) => clampedCost[unit] !== cost[unit])
- ) {
- this.logger.error(
- `Refusing to consume invalid quota cost ${JSON.stringify(cost)} for workspace ${args.workspaceId}; treating it as 0`,
- );
+ async charge({
+ workspaceId,
+ events,
+ }: {
+ workspaceId: string;
+ events: RecordUsageInput[];
+ }): Promise<{ exhaustedKind: ExhaustedKind | null }> {
+ if (events.length === 0) {
+ return { exhaustedKind: null };
}
+ const exhaustedKind = await this.debitCountersAdmittingOnFailure({
+ workspaceId,
+ events,
+ });
+
+ await this.usageRecorderService.record(workspaceId, events);
+
+ return { exhaustedKind };
+ }
+
+ async debitAheadOfRecord({
+ workspaceId,
+ event,
+ }: {
+ workspaceId: string;
+ event: RecordUsageInput;
+ }): Promise<{ exhaustedKind: ExhaustedKind | null }> {
return {
- exhausted: await this.consumeCountersAdmittingOnFailure({
- ...args,
- cost: clampedCost,
+ exhaustedKind: await this.debitCountersAdmittingOnFailure({
+ workspaceId,
+ events: [event],
}),
};
}
@@ -431,18 +449,21 @@ export class UsageLimitQuotaService implements OnModuleInit {
}
}
- private async consumeCountersAdmittingOnFailure({
- cost,
- ...args
- }: QuotaConsumeArgs & { cost: QuotaCost }): Promise<ExhaustedScope[]> {
+ private async debitCountersAdmittingOnFailure({
+ workspaceId,
+ events,
+ }: {
+ workspaceId: string;
+ events: RecordUsageInput[];
+ }): Promise<ExhaustedKind | null> {
try {
const debits = buildQuotaDebits({
- counters: await this.buildCounters(args),
- cost,
+ counters: await this.buildCountersForEvents({ workspaceId, events }),
+ events,
});
if (debits.length === 0) {
- return [];
+ return null;
}
const counters = debits.map((debit) => debit.counter);
@@ -450,7 +471,7 @@ export class UsageLimitQuotaService implements OnModuleInit {
// The consume script only debits keys that exist: warm cold counters
// first so a consume-only caller (workflow, logic function) is metered
// from its first call instead of waiting for an assert to warm the key.
- await this.readRemainings({ workspaceId: args.workspaceId, counters });
+ await this.readRemainings({ workspaceId, counters });
const consumeResults = await this.cacheStorage.runScript<number[]>({
script: CONSUME_QUOTA_COUNTERS_SCRIPT,
@@ -458,27 +479,72 @@ export class UsageLimitQuotaService implements OnModuleInit {
args: [JSON.stringify(debits.map((debit) => debit.amount))],
});
- const remainings = fromConsumeResultsToRemainings(consumeResults);
-
- return await this.buildExhaustedScopes({
- args,
+ const exhaustedCounters = findExhaustedCounters({
counters,
- remainings,
+ remainings: fromConsumeResultsToRemainings(consumeResults),
});
+
+ if (exhaustedCounters.some((counter) => counter.kind === 'allowance')) {
+ return 'allowance';
+ }
+
+ return exhaustedCounters.length > 0 ? 'limit' : null;
} catch (error) {
- return this.admitOnFailure({
- error,
- workspaceId: args.workspaceId,
- enforcement: {
+ this.logger.error(
+ `Usage quota debit degraded for workspace ${workspaceId}: ${error instanceof Error ? error.message : 'unknown error'}`,
+ );
+
+ for (const resourceType of new Set(
+ events.map((event) => event.resourceType),
+ )) {
+ this.countAdmitOnFailure({
operation: 'consume',
- resourceType: args.resourceType,
- cost,
- },
- admitted: [],
- });
+ resourceType,
+ creditsUsedMicro: events
+ .filter((event) => event.resourceType === resourceType)
+ .reduce(
+ (total, event) =>
+ total +
+ fromRecordUsageInputToUsageConsumptionRow(event)
+ .creditsUsedMicro,
+ 0,
+ ),
+ });
+ }
+
+ return null;
}
}
+ private async buildCountersForEvents({
+ workspaceId,
+ events,
+ }: {
+ workspaceId: string;
+ events: RecordUsageInput[];
+ }): Promise<QuotaCounter[]> {
+ const scopeEvents = uniqBy(events, (event) =>
+ JSON.stringify([
+ event.resourceType,
+ event.operationType,
+ buildSpendersFromUsageSpenders(event.spenders ?? {}),
+ ]),
+ );
+
+ const counters = await Promise.all(
+ scopeEvents.map(({ resourceType, operationType, spenders }) =>
+ this.buildCounters({
+ workspaceId,
+ resourceType,
+ operationType,
+ spenders: spenders ?? {},
+ }),
+ ),
+ );
+
+ return uniqBy(counters.flat(), (counter) => counter.key);
+ }
+
private async buildExhaustedScopes({
args,
counters,
@@ -547,7 +613,7 @@ export class UsageLimitQuotaService implements OnModuleInit {
private countAdmitOnFailure({
operation,
resourceType,
- cost,
+ creditsUsedMicro,
}: QuotaEnforcement): void {
const attributes = { operation, resourceType };
@@ -557,10 +623,10 @@ export class UsageLimitQuotaService implements OnModuleInit {
attributes,
});
- if (isDefined(cost) && cost[UsageUnit.CREDIT] > 0) {
+ if (isDefined(creditsUsedMicro) && creditsUsedMicro > 0) {
this.metricsService.incrementCounterBy({
key: MetricsKeys.UsageLimitQuotaAdmittedOnFailureCreditsMicro,
- amount: cost[UsageUnit.CREDIT],
+ amount: creditsUsedMicro,
attributes,
});
}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.module.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.module.ts
index 36cdcfb87dc..f9bd1913119 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.module.ts
@@ -8,6 +8,7 @@ import { MetricsModule } from 'src/engine/core-modules/metrics/metrics.module';
import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';
import { UsagePeriodService } from 'src/engine/core-modules/usage-limit/services/usage-period.service';
import { UsageAnalyticsModule } from 'src/engine/core-modules/usage/usage-analytics.module';
+import { UsageModule } from 'src/engine/core-modules/usage/usage.module';
import { ApplicationEntity } from 'src/engine/core-modules/application/application.entity';
import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
import { AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';
@@ -42,6 +43,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
CacheLockModule,
MetricsModule,
UsageAnalyticsModule,
+ UsageModule,
],
providers: [
UsageLimitQuotaService,
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-debits.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-debits.util.spec.ts
index 6e9357bcf16..8f98c745890 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-debits.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-debits.util.spec.ts
@@ -4,6 +4,7 @@ import { buildQuotaDebits } from 'src/engine/core-modules/usage-limit/utils/buil
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 RecordUsageInput } from 'src/engine/core-modules/usage/types/record-usage-input.type';
const PERIOD_START = new Date('2026-08-01T00:00:00.000Z');
const PERIOD_END = new Date('2026-09-01T00:00:00.000Z');
@@ -20,10 +21,10 @@ const buildLimitCounter = (unit: UsageUnit): LimitQuotaCounter => ({
kind: 'limit',
isDefault: false,
key: unit,
- limitValue: 1_000,
+ limitValue: 1_000_000,
unit,
resourceType: UsageResourceType.LOGIC_FUNCTION,
- operationType: UsageOperationType.CODE_EXECUTION,
+ operationType: UsageOperationType.ALL,
periodUnit: 'month',
periodStart: PERIOD_START,
periodEnd: PERIOD_END,
@@ -31,57 +32,58 @@ const buildLimitCounter = (unit: UsageUnit): LimitQuotaCounter => ({
spenderId: null,
});
+const logicFunctionEvent: RecordUsageInput = {
+ resourceType: UsageResourceType.LOGIC_FUNCTION,
+ operationType: UsageOperationType.CODE_EXECUTION,
+ creditsUsedMicro: 100,
+ quantity: 1,
+ unit: UsageUnit.INVOCATION,
+};
+
+const workflowEvent: RecordUsageInput = {
+ resourceType: UsageResourceType.WORKFLOW,
+ operationType: UsageOperationType.WORKFLOW_EXECUTION,
+ creditsUsedMicro: 300,
+ quantity: 1,
+ unit: UsageUnit.INVOCATION,
+};
+
describe('buildQuotaDebits', () => {
- it('debits each counter the amount of its own unit', () => {
+ it('debits a limit counter with the events of its resource type only', () => {
const creditCounter = buildLimitCounter(UsageUnit.CREDIT);
- const invocationCounter = buildLimitCounter(UsageUnit.INVOCATION);
expect(
buildQuotaDebits({
- counters: [allowanceCounter, creditCounter, invocationCounter],
- cost: {
- [UsageUnit.CREDIT]: 2_500,
- [UsageUnit.INVOCATION]: 1,
- [UsageUnit.MILLISECOND]: 15_000,
- },
+ counters: [creditCounter],
+ events: [logicFunctionEvent, workflowEvent],
}),
- ).toEqual([
- { counter: allowanceCounter, amount: 2_500 },
- { counter: creditCounter, amount: 2_500 },
- { counter: invocationCounter, amount: 1 },
- ]);
+ ).toEqual([{ counter: creditCounter, amount: 100 }]);
});
- it('drops a counter whose unit the cost leaves out', () => {
+ it('debits the allowance with the credits of every event', () => {
expect(
buildQuotaDebits({
- counters: [buildLimitCounter(UsageUnit.TOKEN)],
- cost: { [UsageUnit.CREDIT]: 2_500, [UsageUnit.INVOCATION]: 1 },
+ counters: [allowanceCounter],
+ events: [logicFunctionEvent, workflowEvent],
}),
- ).toEqual([]);
+ ).toEqual([{ counter: allowanceCounter, amount: 400 }]);
});
- it('drops a counter whose unit costs zero', () => {
+ it('drops a counter the events consume nothing of', () => {
expect(
buildQuotaDebits({
- counters: [buildLimitCounter(UsageUnit.INVOCATION)],
- cost: { [UsageUnit.CREDIT]: 2_500, [UsageUnit.INVOCATION]: 0 },
+ counters: [allowanceCounter],
+ events: [{ ...logicFunctionEvent, creditsUsedMicro: 0 }],
}),
).toEqual([]);
});
- it('debits only the run counter for an exempt run, leaving the allowance alone', () => {
- const invocationCounter = buildLimitCounter(UsageUnit.INVOCATION);
-
+ it('drops a counter whose amount is not a whole number', () => {
expect(
buildQuotaDebits({
- counters: [allowanceCounter, invocationCounter],
- cost: {
- [UsageUnit.CREDIT]: 0,
- [UsageUnit.INVOCATION]: 1,
- [UsageUnit.MILLISECOND]: 0,
- },
+ counters: [buildLimitCounter(UsageUnit.INVOCATION)],
+ events: [{ ...logicFunctionEvent, quantity: 1.5 }],
}),
- ).toEqual([{ counter: invocationCounter, amount: 1 }]);
+ ).toEqual([]);
});
});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-debits.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-debits.util.ts
index e4fd1b82484..19b167d309f 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-debits.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-debits.util.ts
@@ -1,16 +1,44 @@
-import { type QuotaCost } from 'src/engine/core-modules/usage-limit/types/quota-cost.type';
import { type QuotaCounter } from 'src/engine/core-modules/usage-limit/types/quota-counter.type';
import { type QuotaDebit } from 'src/engine/core-modules/usage-limit/types/quota-debit.type';
+import {
+ computeQuotaConsumed,
+ type QuotaConsumptionScope,
+} from 'src/engine/core-modules/usage-limit/utils/compute-quota-consumed.util';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
+import { type RecordUsageInput } from 'src/engine/core-modules/usage/types/record-usage-input.type';
+import { fromRecordUsageInputToUsageConsumptionRow } from 'src/engine/core-modules/usage/utils/from-record-usage-input-to-usage-consumption-row.util';
+import { isValidCreditAmountMicro } from 'src/engine/core-modules/usage/utils/is-valid-credit-amount-micro.util';
+
+const ALLOWANCE_CONSUMPTION_SCOPE: QuotaConsumptionScope = {
+ operationType: UsageOperationType.ALL,
+ spenderType: 'workspace',
+ spenderId: null,
+ unit: UsageUnit.CREDIT,
+};
export const buildQuotaDebits = ({
counters,
- cost,
+ events,
}: {
counters: QuotaCounter[];
- cost: QuotaCost;
+ events: RecordUsageInput[];
}): QuotaDebit[] =>
counters.flatMap((counter) => {
- const amount = cost[counter.unit] ?? 0;
+ const amount =
+ counter.kind === 'limit'
+ ? computeQuotaConsumed({
+ rows: events
+ .filter((event) => event.resourceType === counter.resourceType)
+ .map(fromRecordUsageInputToUsageConsumptionRow),
+ scope: counter,
+ })
+ : computeQuotaConsumed({
+ rows: events.map(fromRecordUsageInputToUsageConsumptionRow),
+ scope: ALLOWANCE_CONSUMPTION_SCOPE,
+ });
- return amount > 0 ? [{ counter, amount }] : [];
+ return amount > 0 && isValidCreditAmountMicro(amount)
+ ? [{ counter, amount }]
+ : [];
});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/clamp-quota-cost.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/clamp-quota-cost.util.ts
deleted file mode 100644
index ca49dcdbe70..00000000000
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/clamp-quota-cost.util.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { isDefined } from 'twenty-shared/utils';
-
-import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
-import { isValidCreditAmountMicro } from 'src/engine/core-modules/usage/utils/is-valid-credit-amount-micro.util';
-import { type QuotaCost } from 'src/engine/core-modules/usage-limit/types/quota-cost.type';
-
-const clampAmount = (amount: number): number =>
- isValidCreditAmountMicro(amount) ? amount : 0;
-
-export const clampQuotaCost = (cost: QuotaCost): QuotaCost =>
- Object.values(UsageUnit).reduce<QuotaCost>(
- (clampedCost, unit) => {
- const amount = cost[unit];
-
- return isDefined(amount)
- ? { ...clampedCost, [unit]: clampAmount(amount) }
- : clampedCost;
- },
- { [UsageUnit.CREDIT]: clampAmount(cost[UsageUnit.CREDIT]) },
- );
diff --git a/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/from-record-usage-input-to-usage-consumption-row.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/from-record-usage-input-to-usage-consumption-row.util.spec.ts
new file mode 100644
index 00000000000..39c4743723a
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/from-record-usage-input-to-usage-consumption-row.util.spec.ts
@@ -0,0 +1,50 @@
+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 RecordUsageInput } from 'src/engine/core-modules/usage/types/record-usage-input.type';
+import { fromRecordUsageInputToUsageConsumptionRow } from 'src/engine/core-modules/usage/utils/from-record-usage-input-to-usage-consumption-row.util';
+
+const WORKFLOW_ID = '3c4d5e6f-7a8b-4c9d-8e0f-1a2b3c4d5e6f';
+const APPLICATION_ID = '1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d';
+
+const workflowEvent: RecordUsageInput = {
+ resourceType: UsageResourceType.WORKFLOW,
+ operationType: UsageOperationType.WORKFLOW_EXECUTION,
+ creditsUsedMicro: 100,
+ quantity: 1,
+ unit: UsageUnit.INVOCATION,
+ spenders: {
+ workflowId: WORKFLOW_ID,
+ applicationId: APPLICATION_ID,
+ userWorkspaceId: null,
+ },
+};
+
+describe('fromRecordUsageInputToUsageConsumptionRow', () => {
+ it('writes each spender in its column, empty when the spender is absent', () => {
+ expect(fromRecordUsageInputToUsageConsumptionRow(workflowEvent)).toEqual({
+ operationType: UsageOperationType.WORKFLOW_EXECUTION,
+ unit: UsageUnit.INVOCATION,
+ userWorkspaceId: '',
+ apiKeyId: '',
+ applicationId: APPLICATION_ID,
+ agentId: '',
+ workflowId: WORKFLOW_ID,
+ logicFunctionId: '',
+ creditsUsedMicro: 100,
+ quantity: 1,
+ });
+ });
+
+ it.each([
+ ['missing', undefined],
+ ['invalid', -5],
+ ])('stores %s credits as zero', (_case, creditsUsedMicro) => {
+ expect(
+ fromRecordUsageInputToUsageConsumptionRow({
+ ...workflowEvent,
+ creditsUsedMicro,
+ }).creditsUsedMicro,
+ ).toBe(0);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage/utils/from-record-usage-input-to-usage-consumption-row.util.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/from-record-usage-input-to-usage-consumption-row.util.ts
new file mode 100644
index 00000000000..ba1338dc286
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage/utils/from-record-usage-input-to-usage-consumption-row.util.ts
@@ -0,0 +1,26 @@
+/* @license Enterprise */
+
+import { type RecordUsageInput } from 'src/engine/core-modules/usage/types/record-usage-input.type';
+import { type UsageConsumptionRow } from 'src/engine/core-modules/usage/types/usage-consumption-row.type';
+import { isValidCreditAmountMicro } from 'src/engine/core-modules/usage/utils/is-valid-credit-amount-micro.util';
+
+export const fromRecordUsageInputToUsageConsumptionRow = ({
+ operationType,
+ unit,
+ spenders,
+ creditsUsedMicro = 0,
+ quantity,
+}: RecordUsageInput): UsageConsumptionRow => ({
+ operationType,
+ unit,
+ userWorkspaceId: spenders?.userWorkspaceId ?? '',
+ apiKeyId: spenders?.apiKeyId ?? '',
+ applicationId: spenders?.applicationId ?? '',
+ agentId: spenders?.agentId ?? '',
+ workflowId: spenders?.workflowId ?? '',
+ logicFunctionId: spenders?.logicFunctionId ?? '',
+ creditsUsedMicro: isValidCreditAmountMicro(creditsUsedMicro)
+ ? creditsUsedMicro
+ : 0,
+ quantity,
+});
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 184b6c27277..bd0b982a1a5 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
@@ -2,11 +2,11 @@ import { Injectable, Logger } from '@nestjs/common';
import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';
import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';
-import { type QuotaCost } from 'src/engine/core-modules/usage-limit/types/quota-cost.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 { type RecordUsageInput } from 'src/engine/core-modules/usage/types/record-usage-input.type';
import { type UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';
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 { type BillingTokenUsage } from 'src/engine/metadata-modules/ai/ai-billing/types/billing-token-usage.type';
@@ -50,32 +50,6 @@ export class AiBillingService {
});
}
- private async consumeQuota({
- workspaceId,
- operationType,
- spenders,
- cost,
- }: {
- workspaceId: string;
- operationType: UsageOperationType;
- spenders: UsageSpenders;
- cost: QuotaCost;
- }): Promise<{ hasNoMoreAvailableCredits: boolean }> {
- const { exhausted } = await this.usageLimitQuotaService.consumeQuota({
- workspaceId,
- resourceType: UsageResourceType.AI,
- operationType,
- spenders,
- cost,
- });
-
- return {
- hasNoMoreAvailableCredits: exhausted.some(
- (scope) => scope.exhaustedKind === 'allowance',
- ),
- };
- }
-
// evaluation models first: getEffectiveModelConfig throws on ids outside its registry
private getCostConfig(modelId: ModelId): AiModelCostConfig {
return (
@@ -137,25 +111,18 @@ export class AiBillingService {
(billingInput.usage.inputTokens ?? 0) +
(billingInput.usage.outputTokens ?? 0);
- await this.consumeQuota({
+ await this.usageLimitQuotaService.charge({
workspaceId,
- operationType,
- spenders: { userWorkspaceId, agentId },
- cost: {
- [UsageUnit.CREDIT]: creditsUsedMicro,
- [UsageUnit.TOKEN]: totalTokens,
- },
+ events: [
+ this.buildAiTokenUsageEvent({
+ creditsUsedMicro,
+ totalTokens,
+ modelId,
+ operationType,
+ spenders: { userWorkspaceId, agentId },
+ }),
+ ],
});
-
- await this.emitAiTokenUsageEvent(
- workspaceId,
- creditsUsedMicro,
- totalTokens,
- modelId,
- operationType,
- agentId,
- userWorkspaceId,
- );
}
async decrementAndCheckAvailableCredits({
@@ -178,15 +145,19 @@ export class AiBillingService {
(billingInput.usage.inputTokens ?? 0) +
(billingInput.usage.outputTokens ?? 0);
- return this.consumeQuota({
- workspaceId,
- operationType,
- spenders,
- cost: {
- [UsageUnit.CREDIT]: creditsUsedMicro,
- [UsageUnit.TOKEN]: totalTokens,
- },
- });
+ const { exhaustedKind } =
+ await this.usageLimitQuotaService.debitAheadOfRecord({
+ workspaceId,
+ event: this.buildAiTokenUsageEvent({
+ creditsUsedMicro,
+ totalTokens,
+ modelId,
+ operationType,
+ spenders,
+ }),
+ });
+
+ return { hasNoMoreAvailableCredits: exhaustedKind === 'allowance' };
}
async billNativeWebSearchUsage(
@@ -206,26 +177,19 @@ export class AiBillingService {
`Native web search billing: ${nativeWebSearchCallCount} calls, $${costInDollars.toFixed(4)}`,
);
- await this.consumeQuota({
+ await this.usageLimitQuotaService.charge({
workspaceId,
- operationType: UsageOperationType.WEB_SEARCH,
- spenders: { userWorkspaceId },
- cost: {
- [UsageUnit.CREDIT]: creditsUsedMicro,
- [UsageUnit.INVOCATION]: nativeWebSearchCallCount,
- },
+ events: [
+ {
+ resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.WEB_SEARCH,
+ creditsUsedMicro,
+ quantity: nativeWebSearchCallCount,
+ unit: UsageUnit.INVOCATION,
+ spenders: { userWorkspaceId },
+ },
+ ],
});
-
- await this.usageRecorderService.record(workspaceId, [
- {
- resourceType: UsageResourceType.AI,
- operationType: UsageOperationType.WEB_SEARCH,
- creditsUsedMicro,
- quantity: nativeWebSearchCallCount,
- unit: UsageUnit.INVOCATION,
- spenders: { userWorkspaceId },
- },
- ]);
}
async emitAiTokenUsageEvent(
@@ -238,16 +202,38 @@ export class AiBillingService {
userWorkspaceId?: string | null,
): Promise<void> {
await this.usageRecorderService.record(workspaceId, [
- {
- resourceType: UsageResourceType.AI,
- operationType,
+ this.buildAiTokenUsageEvent({
creditsUsedMicro,
- quantity: totalTokens,
- unit: UsageUnit.TOKEN,
- resourceId: agentId || null,
- resourceContext: modelId,
+ totalTokens,
+ modelId,
+ operationType,
spenders: { userWorkspaceId, agentId },
- },
+ }),
]);
}
+
+ private buildAiTokenUsageEvent({
+ creditsUsedMicro,
+ totalTokens,
+ modelId,
+ operationType,
+ spenders,
+ }: {
+ creditsUsedMicro: number;
+ totalTokens: number;
+ modelId: ModelId;
+ operationType: UsageOperationType;
+ spenders: UsageSpenders;
+ }): RecordUsageInput {
+ return {
+ resourceType: UsageResourceType.AI,
+ operationType,
+ creditsUsedMicro,
+ quantity: totalTokens,
+ unit: UsageUnit.TOKEN,
+ resourceId: spenders.agentId || null,
+ resourceContext: modelId,
+ spenders,
+ };
+ }
}
diff --git a/packages/twenty-server/src/modules/emailing/emailing.module.ts b/packages/twenty-server/src/modules/emailing/emailing.module.ts
index 07f369ead6b..8632fd22680 100644
--- a/packages/twenty-server/src/modules/emailing/emailing.module.ts
+++ b/packages/twenty-server/src/modules/emailing/emailing.module.ts
@@ -10,7 +10,6 @@ import { ClickHouseModule } from 'src/database/clickhouse/clickhouse.module';
import { MetricsModule } from 'src/engine/core-modules/metrics/metrics.module';
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';
@@ -67,7 +66,6 @@ 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 1a6e1652f5c..5b8d5037f13 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
@@ -6,7 +6,6 @@ import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/serv
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 UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';
import { buildEmailQuotaCost } from 'src/modules/emailing/utils/build-email-quota-cost.util';
import { computeEmailCreditsUsedMicro } from 'src/modules/emailing/utils/compute-email-credits-used-micro.util';
@@ -21,7 +20,6 @@ type EmailSendScope = EmailUsageScope & { emailCount?: number };
@Injectable()
export class EmailBillingService {
constructor(
- private readonly usageRecorderService: UsageRecorderService,
private readonly billingUsageService: BillingUsageService,
private readonly usageLimitQuotaService: UsageLimitQuotaService,
) {}
@@ -63,28 +61,18 @@ export class EmailBillingService {
return;
}
- const creditsUsedMicro = computeEmailCreditsUsedMicro(sentEmailCount);
-
- await this.usageLimitQuotaService.consumeQuota({
+ await this.usageLimitQuotaService.charge({
workspaceId,
- resourceType: UsageResourceType.EMAIL,
- operationType: UsageOperationType.EMAIL_SEND,
- spenders,
- cost: {
- [UsageUnit.CREDIT]: creditsUsedMicro,
- [UsageUnit.INVOCATION]: sentEmailCount,
- },
+ events: [
+ {
+ resourceType: UsageResourceType.EMAIL,
+ operationType: UsageOperationType.EMAIL_SEND,
+ creditsUsedMicro: computeEmailCreditsUsedMicro(sentEmailCount),
+ quantity: sentEmailCount,
+ unit: UsageUnit.INVOCATION,
+ spenders,
+ },
+ ],
});
-
- await this.usageRecorderService.record(workspaceId, [
- {
- resourceType: UsageResourceType.EMAIL,
- operationType: UsageOperationType.EMAIL_SEND,
- creditsUsedMicro,
- quantity: sentEmailCount,
- unit: UsageUnit.INVOCATION,
- spenders,
- },
- ]);
}
}
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 8c32edf4e67..857393b7e7f 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
@@ -6,7 +6,6 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';
import { MetricsModule } from 'src/engine/core-modules/metrics/metrics.module';
import { UsageLimitModule } from 'src/engine/core-modules/usage-limit/usage-limit.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';
@@ -55,7 +54,6 @@ import { WorkflowStepWaitStoreModule } from 'src/modules/workflow/workflow-wait/
CreateCalendarEventActionModule,
MetricsModule,
UsageLimitModule,
- UsageModule,
WorkflowStepWaitStoreModule,
],
providers: [WorkflowExecutorWorkspaceService, WorkflowActionFactory],
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 96481f107a1..1049f984e7a 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
@@ -28,7 +28,6 @@ import { MetricsKeys } from 'src/engine/core-modules/metrics/types/metrics-keys.
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 { shouldCaptureException } from 'src/engine/utils/global-exception-handler.util';
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';
@@ -72,7 +71,6 @@ export class WorkflowExecutorWorkspaceService {
constructor(
private readonly workflowCoreSyncService: WorkflowCoreSyncService,
private readonly workflowActionFactory: WorkflowActionFactory,
- private readonly usageRecorderService: UsageRecorderService,
private readonly workflowRunWorkspaceService: WorkflowRunWorkspaceService,
private readonly billingUsageService: BillingUsageService,
private readonly usageLimitQuotaService: UsageLimitQuotaService,
@@ -254,7 +252,7 @@ export class WorkflowExecutorWorkspaceService {
!actionOutput.shouldSkipStepExecution &&
!isDefined(resumedThreadId)
) {
- await this.sendWorkflowNodeRunEvent(workspaceId, billingSpenders);
+ await this.chargeWorkflowNodeRun(workspaceId, billingSpenders);
}
const { shouldProcessNextSteps } = await this.processStepExecutionResult({
@@ -441,29 +439,24 @@ export class WorkflowExecutorWorkspaceService {
}
}
- private async sendWorkflowNodeRunEvent(
+ private async chargeWorkflowNodeRun(
workspaceId: string,
billingSpenders: WorkflowBillingSpenders,
) {
- await this.usageLimitQuotaService.consumeQuota({
+ await this.usageLimitQuotaService.charge({
workspaceId,
- resourceType: UsageResourceType.WORKFLOW,
- operationType: UsageOperationType.WORKFLOW_EXECUTION,
- spenders: billingSpenders,
- cost: { [UsageUnit.CREDIT]: 100, [UsageUnit.INVOCATION]: 1 },
+ events: [
+ {
+ resourceType: UsageResourceType.WORKFLOW,
+ operationType: UsageOperationType.WORKFLOW_EXECUTION,
+ creditsUsedMicro: 100,
+ quantity: 1,
+ unit: UsageUnit.INVOCATION,
+ resourceId: billingSpenders.workflowId,
+ spenders: billingSpenders,
+ },
+ ],
});
-
- await this.usageRecorderService.record(workspaceId, [
- {
- resourceType: UsageResourceType.WORKFLOW,
- operationType: UsageOperationType.WORKFLOW_EXECUTION,
- creditsUsedMicro: 100,
- quantity: 1,
- unit: UsageUnit.INVOCATION,
- resourceId: billingSpenders.workflowId,
- spenders: billingSpenders,
- },
- ]);
}
private async processStepExecutionResult({
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts
index 927db087d0a..5d43e92be5d 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts
@@ -368,10 +368,7 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
'bills the core-owned spender mapping (mirrorless=%s)',
async (mirrorless) => {
const fixture = await createFixture({ mirrorless });
- const consume = jest.spyOn(
- global.workflowTestServices.quota,
- 'consumeQuota',
- );
+ const charge = jest.spyOn(global.workflowTestServices.quota, 'charge');
await waitForRun(await runFixture(fixture), 'COMPLETED');
@@ -380,15 +377,17 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
[workspaceId],
);
- expect(consume).toHaveBeenCalledWith(
- expect.objectContaining({
- workspaceId,
- spenders: {
- workflowId: fixture.workflowId ?? fixture.coreWorkflowId,
- applicationId: workspace.workspaceCustomApplicationId,
- },
- }),
- );
+ expect(charge).toHaveBeenCalledWith({
+ workspaceId,
+ events: [
+ expect.objectContaining({
+ spenders: {
+ workflowId: fixture.workflowId ?? fixture.coreWorkflowId,
+ applicationId: workspace.workspaceCustomApplicationId,
+ },
+ }),
+ ],
+ });
},
);