Skip to content

The open alternative to Salesforce, designed for AI.

Read credits used this period through one ClickHouse reader (#27419)

Félix Malfaitc1135611665a
diff --git a/packages/twenty-server/src/engine/core-modules/billing/billing.module.ts b/packages/twenty-server/src/engine/core-modules/billing/billing.module.ts
index 48158e2de0b..d570367d5d4 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/billing.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/billing.module.ts
@@ -52,6 +52,7 @@ import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.ent
import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permissions.module';
import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/provide-workspace-scoped-repository';
import { UsageLimitModule } from 'src/engine/core-modules/usage-limit/usage-limit.module';
+import { UsageAnalyticsModule } from 'src/engine/core-modules/usage/usage-analytics.module';
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
@Module({
@@ -81,6 +82,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
]),
MetricsModule,
EnterpriseModule,
+ UsageAnalyticsModule,
UsageLimitModule,
WorkspaceIteratorModule,
],
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.ts
index 4ebdd2c6a1d..b3325db8ad7 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.ts
@@ -31,6 +31,7 @@ import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/serv
import { type QuotaCost } from 'src/engine/core-modules/usage-limit/types/quota-cost.type';
import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { type UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+import { UsageAnalyticsService } from 'src/engine/core-modules/usage/services/usage-analytics.service';
import { type UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';
import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
@@ -59,6 +60,7 @@ export class BillingUsageService {
private readonly clickHouseService: ClickHouseService,
private readonly coreEntityCacheService: CoreEntityCacheService,
private readonly usageLimitQuotaService: UsageLimitQuotaService,
+ private readonly usageAnalyticsService: UsageAnalyticsService,
) {}
async assertUsageAllowed(scope: UsageQuotaScope): Promise<void> {
@@ -202,7 +204,17 @@ export class BillingUsageService {
periodEnd: Date,
): Promise<BillingResourceCreditUsageDTO> {
const [usedCredits, rolloverCredits] = await Promise.all([
- this.getCurrentPeriodCreditsUsed(workspaceId, periodStart),
+ // Fails open: an unreadable usage total must never block a paying workspace
+ this.usageAnalyticsService
+ .getCreditsUsedMicroForBillingPeriod({ workspaceId, periodStart })
+ .catch((error) => {
+ this.logger.error(
+ `Could not read credits used for workspace ${workspaceId}`,
+ error,
+ );
+
+ return 0;
+ }),
this.billingCreditGrantService.getActiveCreditsMicro(workspaceId),
]);
@@ -257,30 +269,8 @@ export class BillingUsageService {
return Number(resourceCreditPrice.metadata?.credit_amount ?? 0);
}
- // Null on a failed read: select swallows errors into [], while sum() always yields one row
- private async sumCreditsUsedMicroOrNull(
- condition: string,
- params: Record<string, unknown>,
- ): Promise<number | null> {
- const rows = await this.clickHouseService.select<UsageSumRow>(
- `SELECT sum(creditsUsedMicro) AS total
- FROM usageEvent
- WHERE workspaceId = {workspaceId:String}
- AND ${condition}`,
- params,
- );
-
- if (rows.length === 0) {
- return null;
- }
-
- const rawTotal = rows[0]?.total ?? 0;
- const total = typeof rawTotal === 'string' ? Number(rawTotal) : rawTotal;
-
- return Number.isFinite(total) ? total : 0;
- }
-
// By event timestamp: at a transition currentPeriodStart has moved on, so periodStart would read the new period
+ // Null on a failed read: select swallows errors into [], while sum() always yields one row
async getCreditsUsedBetweenOrNull({
workspaceId,
from,
@@ -290,30 +280,26 @@ export class BillingUsageService {
from: Date;
to: Date;
}): Promise<number | null> {
- return this.sumCreditsUsedMicroOrNull(
- 'timestamp >= {from:DateTime64(3)} AND timestamp < {to:DateTime64(3)}',
+ const rows = await this.clickHouseService.select<UsageSumRow>(
+ `SELECT sum(creditsUsedMicro) AS total
+ FROM usageEvent
+ WHERE workspaceId = {workspaceId:String}
+ AND timestamp >= {from:DateTime64(3)} AND timestamp < {to:DateTime64(3)}`,
{
workspaceId,
from: formatDateTimeForClickHouse(from),
to: formatDateTimeForClickHouse(to),
},
);
- }
- // Fails open: an unreadable usage total must never block a paying workspace.
- async getCurrentPeriodCreditsUsed(
- workspaceId: string,
- periodStart: Date,
- ): Promise<number> {
- const usedMicro = await this.sumCreditsUsedMicroOrNull(
- 'periodStart = {periodStart:DateTime64(3)}',
- {
- workspaceId,
- periodStart: formatDateTimeForClickHouse(periodStart),
- },
- );
+ if (rows.length === 0) {
+ return null;
+ }
- return usedMicro ?? 0;
+ const rawTotal = rows[0]?.total ?? 0;
+ const total = typeof rawTotal === 'string' ? Number(rawTotal) : rawTotal;
+
+ return Number.isFinite(total) ? total : 0;
}
async getCachedCurrentBillingSubscription(