Skip to content

The open alternative to Salesforce, designed for AI.

chore(usage-limit): remove the quota engine credit bound feature flag (#26174)

Etienne1f3d618ee5c2
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index d70189a88b4..dbed6541ebf 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -2000,7 +2000,6 @@ enum FeatureFlagKey {
IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED
IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED
IS_MESSAGE_CALENDAR_TARGET_READ_ENABLED
- IS_QUOTA_ENGINE_CREDIT_BOUND_ENABLED
IS_RECORD_SHARING_ENABLED
IS_INITIAL_OBJECT_VIEW_ENABLED
IS_WEBHOOK_RATE_LIMIT_ENABLED
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index f672cca193c..596f37c63a2 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -1611,7 +1611,7 @@ export interface FeatureFlag {
__typename: 'FeatureFlag'
}
-export type FeatureFlagKey = 'IS_ASYNC_CSV_EXPORT_ENABLED' | 'IS_UNIQUE_INDEXES_ENABLED' | 'IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED' | 'IS_JSON_FILTER_ENABLED' | 'IS_MESSAGE_CAMPAIGN_ENABLED' | 'IS_JUNCTION_RELATIONS_ENABLED' | 'IS_REST_METADATA_API_NEW_FORMAT_DIRECT' | 'IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED' | 'IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED' | 'IS_MESSAGE_CALENDAR_TARGET_READ_ENABLED' | 'IS_QUOTA_ENGINE_CREDIT_BOUND_ENABLED' | 'IS_RECORD_SHARING_ENABLED' | 'IS_INITIAL_OBJECT_VIEW_ENABLED' | 'IS_WEBHOOK_RATE_LIMIT_ENABLED'
+export type FeatureFlagKey = 'IS_ASYNC_CSV_EXPORT_ENABLED' | 'IS_UNIQUE_INDEXES_ENABLED' | 'IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED' | 'IS_JSON_FILTER_ENABLED' | 'IS_MESSAGE_CAMPAIGN_ENABLED' | 'IS_JUNCTION_RELATIONS_ENABLED' | 'IS_REST_METADATA_API_NEW_FORMAT_DIRECT' | 'IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED' | 'IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED' | 'IS_MESSAGE_CALENDAR_TARGET_READ_ENABLED' | 'IS_RECORD_SHARING_ENABLED' | 'IS_INITIAL_OBJECT_VIEW_ENABLED' | 'IS_WEBHOOK_RATE_LIMIT_ENABLED'
export interface WorkspaceUrls {
customUrl?: Scalars['String']
@@ -10845,7 +10845,6 @@ export const enumFeatureFlagKey = {
IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED: 'IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED' as const,
IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED: 'IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED' as const,
IS_MESSAGE_CALENDAR_TARGET_READ_ENABLED: 'IS_MESSAGE_CALENDAR_TARGET_READ_ENABLED' as const,
- IS_QUOTA_ENGINE_CREDIT_BOUND_ENABLED: 'IS_QUOTA_ENGINE_CREDIT_BOUND_ENABLED' as const,
IS_RECORD_SHARING_ENABLED: 'IS_RECORD_SHARING_ENABLED' as const,
IS_INITIAL_OBJECT_VIEW_ENABLED: 'IS_INITIAL_OBJECT_VIEW_ENABLED' as const,
IS_WEBHOOK_RATE_LIMIT_ENABLED: 'IS_WEBHOOK_RATE_LIMIT_ENABLED' as const
diff --git a/packages/twenty-front/src/generated-admin/graphql.ts b/packages/twenty-front/src/generated-admin/graphql.ts
index 78b293c23a3..a015ec7387c 100644
--- a/packages/twenty-front/src/generated-admin/graphql.ts
+++ b/packages/twenty-front/src/generated-admin/graphql.ts
@@ -432,7 +432,6 @@ export enum FeatureFlagKey {
IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED = 'IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED',
IS_MESSAGE_CALENDAR_TARGET_READ_ENABLED = 'IS_MESSAGE_CALENDAR_TARGET_READ_ENABLED',
IS_MESSAGE_CAMPAIGN_ENABLED = 'IS_MESSAGE_CAMPAIGN_ENABLED',
- IS_QUOTA_ENGINE_CREDIT_BOUND_ENABLED = 'IS_QUOTA_ENGINE_CREDIT_BOUND_ENABLED',
IS_RECORD_SHARING_ENABLED = 'IS_RECORD_SHARING_ENABLED',
IS_REST_METADATA_API_NEW_FORMAT_DIRECT = 'IS_REST_METADATA_API_NEW_FORMAT_DIRECT',
IS_UNIQUE_INDEXES_ENABLED = 'IS_UNIQUE_INDEXES_ENABLED',
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index e68c833cae8..35a49b6f622 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -2078,7 +2078,6 @@ export enum FeatureFlagKey {
IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED = 'IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED',
IS_MESSAGE_CALENDAR_TARGET_READ_ENABLED = 'IS_MESSAGE_CALENDAR_TARGET_READ_ENABLED',
IS_MESSAGE_CAMPAIGN_ENABLED = 'IS_MESSAGE_CAMPAIGN_ENABLED',
- IS_QUOTA_ENGINE_CREDIT_BOUND_ENABLED = 'IS_QUOTA_ENGINE_CREDIT_BOUND_ENABLED',
IS_RECORD_SHARING_ENABLED = 'IS_RECORD_SHARING_ENABLED',
IS_REST_METADATA_API_NEW_FORMAT_DIRECT = 'IS_REST_METADATA_API_NEW_FORMAT_DIRECT',
IS_UNIQUE_INDEXES_ENABLED = 'IS_UNIQUE_INDEXES_ENABLED',
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminFeatureFlagMetadata.ts b/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminFeatureFlagMetadata.ts
index 24ce0f00d3e..563f3dea6c9 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminFeatureFlagMetadata.ts
+++ b/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminFeatureFlagMetadata.ts
@@ -46,10 +46,6 @@ export const SETTINGS_ADMIN_FEATURE_FLAG_METADATA: Partial<
label: msg`Message and calendar target reads`,
description: msg`Use target relations to find messages and calendar events linked to records.`,
},
- [FeatureFlagKey.IS_QUOTA_ENGINE_CREDIT_BOUND_ENABLED]: {
- label: msg`Credit allowance quotas`,
- description: msg`Use the quota engine to enforce credit allowances.`,
- },
[FeatureFlagKey.IS_RECORD_SHARING_ENABLED]: {
label: msg`Record sharing`,
description: msg`Allow sharing individual records with workspace members.`,
diff --git a/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-subscription.service.ts b/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-subscription.service.ts
index a5403dc2ef1..31c06b7c85b 100644
--- a/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-subscription.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-subscription.service.ts
@@ -24,7 +24,6 @@ import { BillingSubscriptionItemEntity } from 'src/engine/core-modules/billing/e
import { BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';
import { SubscriptionStatus } from 'src/engine/core-modules/billing/enums/billing-subscription-status.enum';
import { BillingWebhookEvent } from 'src/engine/core-modules/billing/enums/billing-webhook-events.enum';
-import { BillingUsageCacheService } from 'src/engine/core-modules/billing/services/billing-usage-cache.service';
import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';
import { StripeCustomerService } from 'src/engine/core-modules/billing/stripe/services/stripe-customer.service';
import { StripeSubscriptionScheduleService } from 'src/engine/core-modules/billing/stripe/services/stripe-subscription-schedule.service';
@@ -65,7 +64,6 @@ export class BillingWebhookSubscriptionService {
private readonly billingCustomerRepository: WorkspaceScopedRepository<BillingCustomerEntity>,
private readonly workspaceService: WorkspaceService,
private readonly stripeSubscriptionScheduleService: StripeSubscriptionScheduleService,
- private readonly billingUsageCacheService: BillingUsageCacheService,
private readonly usageLimitQuotaService: UsageLimitQuotaService,
private readonly workspaceCacheService: WorkspaceCacheService,
) {}
@@ -186,7 +184,6 @@ export class BillingWebhookSubscriptionService {
workspaceId,
);
- await this.billingUsageCacheService.flushAvailableCredits(workspace.id);
await this.workspaceCacheService.invalidateAndRecompute(workspace.id, [
'currentBillingSubscription',
]);
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 f863039d0fe..b4a1149d1e9 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
@@ -36,7 +36,6 @@ import { BillingRecordSharingEntitlementProvider } from 'src/engine/core-modules
import { BillingUsageLimitEntitlementProvider } from 'src/engine/core-modules/billing/services/billing-usage-limit-entitlement-provider.service';
import { BillingSubscriptionUpdateService } from 'src/engine/core-modules/billing/services/billing-subscription-update.service';
import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';
-import { BillingUsageCacheService } from 'src/engine/core-modules/billing/services/billing-usage-cache.service';
import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';
import { BillingService } from 'src/engine/core-modules/billing/services/billing.service';
import { ResourceCreditService } from 'src/engine/core-modules/billing/services/resource-credit.service';
@@ -104,7 +103,6 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
BillingUpdateSubscriptionPriceCommand,
BillingSyncPlansDataCommand,
BillingUsageService,
- BillingUsageCacheService,
BillingCreditAllowanceProvider,
BillingRecordSharingEntitlementProvider,
BillingUsageLimitEntitlementProvider,
@@ -128,7 +126,6 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
BillingPortalWorkspaceService,
BillingService,
BillingUsageService,
- BillingUsageCacheService,
BillingCreditRolloverService,
BillingCreditGrantService,
BillingCreditService,
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-allowance-provider.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-allowance-provider.service.ts
index 38617f5592a..fddaa412018 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-allowance-provider.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-allowance-provider.service.ts
@@ -28,8 +28,8 @@ export class BillingCreditAllowanceProvider extends CreditAllowanceProvider {
super();
}
- async isCreditAllowanceEnabled(workspaceId: string): Promise<boolean> {
- return this.billingUsageService.isAllowanceCounterEnabled(workspaceId);
+ async isCreditAllowanceEnabled(): Promise<boolean> {
+ return this.twentyConfigService.get('IS_BILLING_ENABLED');
}
async getCreditAllowancePeriod(
@@ -71,15 +71,19 @@ export class BillingCreditAllowanceProvider extends CreditAllowanceProvider {
return null;
}
- const creditBalanceMicro =
- await this.billingCreditGrantService.getActiveCreditsMicro(workspaceId);
+ const { balanceMicro, earliestExpiryBefore } =
+ await this.billingCreditGrantService.getActiveCreditBalance({
+ workspaceId,
+ boundary: subscription.currentPeriodEnd,
+ });
return {
periodStart: subscription.currentPeriodStart,
periodEnd: subscription.currentPeriodEnd,
allowanceMicro:
this.billingUsageService.getResourceUsageCap(subscription) +
- creditBalanceMicro,
+ balanceMicro,
+ validUntil: earliestExpiryBefore ?? subscription.currentPeriodEnd,
};
} catch (error) {
this.logger.error(
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-grant.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-grant.service.ts
index 388bfce15fc..7b4656cf817 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-grant.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-grant.service.ts
@@ -3,7 +3,7 @@
import { Injectable } from '@nestjs/common';
import { isDefined } from 'twenty-shared/utils';
-import { And, type EntityManager, IsNull, LessThan, MoreThan } from 'typeorm';
+import { type EntityManager, IsNull, LessThan, MoreThan } from 'typeorm';
import {
BillingException,
@@ -107,9 +107,34 @@ export class BillingCreditGrantService {
}
async getActiveCreditsMicro(workspaceId: string): Promise<number> {
+ const { balanceMicro } = await this.getActiveCreditBalance({
+ workspaceId,
+ boundary: null,
+ });
+
+ return balanceMicro;
+ }
+
+ // One statement, so the balance and the expiry that bounds its validity come
+ // from the same snapshot: read separately, a grant lapsing between the two
+ // reads is counted in the balance yet missing from the expiry, and the
+ // counter would keep its credits spendable until the period ends.
+ async getActiveCreditBalance({
+ workspaceId,
+ boundary,
+ }: {
+ workspaceId: string;
+ boundary: Date | null;
+ }): Promise<{ balanceMicro: number; earliestExpiryBefore: Date | null }> {
const result = await this.billingCreditGrantRepository
.createQueryBuilder('billingCreditGrant')
.select('COALESCE(SUM("billingCreditGrant"."amountMicro"), 0)', 'total')
+ .addSelect(
+ isDefined(boundary)
+ ? 'MIN("billingCreditGrant"."expiresAt") FILTER (WHERE "billingCreditGrant"."expiresAt" < :boundary)'
+ : 'NULL',
+ 'earliestExpiry',
+ )
.where('"billingCreditGrant"."workspaceId" = :workspaceId', {
workspaceId,
})
@@ -118,20 +143,29 @@ export class BillingCreditGrantService {
.andWhere(
'("billingCreditGrant"."expiresAt" IS NULL OR "billingCreditGrant"."expiresAt" > now())',
)
- .getRawOne<{ total: string | number | null }>();
+ .setParameters(isDefined(boundary) ? { boundary } : {})
+ .getRawOne<{
+ total: string | number | null;
+ earliestExpiry: Date | string | null;
+ }>();
- const total = Number(result?.total ?? 0);
+ const balanceMicro = Number(result?.total ?? 0);
// Rounding a balance would hand out or withhold credits that were never
// granted, so refuse rather than serve a number we cannot represent.
- if (!Number.isSafeInteger(total)) {
+ if (!Number.isSafeInteger(balanceMicro)) {
throw new BillingException(
- `Credit balance for workspace ${workspaceId} is not a safe integer (${total})`,
+ `Credit balance for workspace ${workspaceId} is not a safe integer (${balanceMicro})`,
BillingExceptionCode.BILLING_CREDIT_AMOUNT_INVALID,
);
}
- return total;
+ return {
+ balanceMicro,
+ earliestExpiryBefore: isDefined(result?.earliestExpiry)
+ ? new Date(result.earliestExpiry)
+ : null,
+ };
}
// Grants that were spendable at any point during the given period.
@@ -164,29 +198,6 @@ export class BillingCreditGrantService {
});
}
- // The one place that says when a credit balance stops being trustworthy
- // before the period is out: an operator-set expiry falling inside it would
- // otherwise go unnoticed until the next one, and the workspace would keep
- // spending credits that already lapsed.
- async findEarliestExpiryBefore({
- workspaceId,
- boundary,
- }: {
- workspaceId: string;
- boundary: Date;
- }): Promise<Date | null> {
- const [row] = await this.billingCreditGrantRepository.find(workspaceId, {
- where: {
- revokedAt: IsNull(),
- expiresAt: And(MoreThan(new Date()), LessThan(boundary)),
- },
- order: { expiresAt: 'ASC' },
- take: 1,
- });
-
- return row?.expiresAt ?? null;
- }
-
// The previous transition pulled every grant it closed back to the instant
// the period ended, so the ledger records where the closing period started.
// Calendar arithmetic cannot recover it once the subscription has moved on:
@@ -246,8 +257,6 @@ export class BillingCreditGrantService {
});
}
- // wasRevokedNow tells a retried revocation apart from the one that actually
- // took the credits away, so callers only adjust balances once.
async revokeGrant({
workspaceId,
grantId,
@@ -256,7 +265,7 @@ export class BillingCreditGrantService {
workspaceId: string;
grantId: string;
revokedByUserId?: string | null;
- }): Promise<{ grant: BillingCreditGrantEntity; wasRevokedNow: boolean }> {
+ }): Promise<BillingCreditGrantEntity> {
const grant = await this.billingCreditGrantRepository.findOne(workspaceId, {
where: { id: grantId },
});
@@ -269,26 +278,18 @@ export class BillingCreditGrantService {
}
if (isDefined(grant.revokedAt)) {
- return { grant, wasRevokedNow: false };
+ return grant;
}
- const { affected } = await this.billingCreditGrantRepository.update(
+ await this.billingCreditGrantRepository.update(
workspaceId,
{ id: grantId, revokedAt: IsNull() },
{ revokedAt: new Date(), revokedByUserId: revokedByUserId ?? null },
);
- const revokedGrant = await this.billingCreditGrantRepository.findOneOrFail(
- workspaceId,
- { where: { id: grantId } },
- );
-
- // Two concurrent revocations both read an unrevoked grant; only the one
- // whose UPDATE matched may move the balance.
- return {
- grant: revokedGrant,
- wasRevokedNow: isDefined(affected) && affected > 0,
- };
+ return this.billingCreditGrantRepository.findOneOrFail(workspaceId, {
+ where: { id: grantId },
+ });
}
async findGrantByIdempotencyKey(
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-rollover.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-rollover.service.ts
index 6f830121029..2fd63ee5100 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-rollover.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-rollover.service.ts
@@ -86,7 +86,7 @@ export class BillingCreditRolloverService {
private async carryGrantsForward(
params: ProcessRolloverParams & { usageMicro: number },
): Promise<void> {
- const { workspaceId, nextPeriodStart, nextAllowanceMicro } = params;
+ const { workspaceId, nextAllowanceMicro } = params;
const rolloverCapMultiplier = this.twentyConfigService.get(
'BILLING_ROLLOVER_TOTAL_CAP_MULTIPLIER',
@@ -95,21 +95,15 @@ export class BillingCreditRolloverService {
// Closing the old grants and writing their successors is one settlement:
// committing the first half alone would leave the workspace with every
// grant closed and nothing carrying the unspent part forward.
- const { carriedForwardMicro, hasReplayedGrant } =
- await this.dataSource.transaction(async (entityManager) =>
- this.settleGrants({
- ...params,
- entityManager,
- rolloverCapMicro: (rolloverCapMultiplier - 1) * nextAllowanceMicro,
- }),
- );
+ await this.dataSource.transaction(async (entityManager) =>
+ this.settleGrants({
+ ...params,
+ entityManager,
+ rolloverCapMicro: (rolloverCapMultiplier - 1) * nextAllowanceMicro,
+ }),
+ );
- await this.billingCreditService.refreshWorkspaceCreditState({
- workspaceId,
- availableDeltaMicro: carriedForwardMicro,
- isReplay: hasReplayedGrant,
- adjustmentKey: buildRolloverAdjustmentKey(nextPeriodStart),
- });
+ await this.billingCreditService.refreshWorkspaceCreditState(workspaceId);
}
private async settleGrants({
@@ -125,7 +119,7 @@ export class BillingCreditRolloverService {
usageMicro: number;
rolloverCapMicro: number;
entityManager: EntityManager;
- }): Promise<{ carriedForwardMicro: number; hasReplayedGrant: boolean }> {
+ }): Promise<void> {
const closingGrants =
await this.billingCreditGrantService.findGrantsLiveDuringPeriod(
{
@@ -155,11 +149,8 @@ export class BillingCreditRolloverService {
entityManager,
);
- let carriedForwardMicro = 0;
- let hasReplayedGrant = false;
-
for (const carryForwardGrant of carryForwardGrants) {
- const grant = await this.billingCreditGrantService.createGrant(
+ await this.billingCreditGrantService.createGrant(
{
workspaceId,
amountMicro: carryForwardGrant.amountMicro,
@@ -187,21 +178,10 @@ export class BillingCreditRolloverService {
},
entityManager,
);
-
- if (isDefined(grant)) {
- carriedForwardMicro += grant.amountMicro;
- } else {
- hasReplayedGrant = true;
- }
}
-
- return { carriedForwardMicro, hasReplayedGrant };
}
}
-const buildRolloverAdjustmentKey = (nextPeriodStart: Date): string =>
- `rollover:${nextPeriodStart.toISOString()}`;
-
// Stripe redelivers webhooks, so the whole transition has to be replayable.
const buildCarryForwardIdempotencyKey = ({
workspaceId,
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit.service.ts
index 17d1c8dab42..279ec795a44 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit.service.ts
@@ -13,8 +13,6 @@ import { type BillingSubscriptionEntity } from 'src/engine/core-modules/billing/
import { type BillingCreditGrantType } from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';
import { BillingCreditGrantService } from 'src/engine/core-modules/billing/services/billing-credit-grant.service';
import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';
-import { BillingUsageCacheService } from 'src/engine/core-modules/billing/services/billing-usage-cache.service';
-import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';
import { BillingService } from 'src/engine/core-modules/billing/services/billing.service';
import { alignGrantExpiryToPeriodEnd } from 'src/engine/core-modules/billing/utils/align-grant-expiry-to-period-end.util';
import { buildBillingCreditStateLockKey } from 'src/engine/core-modules/billing/utils/build-billing-credit-state-lock-key.util';
@@ -46,8 +44,6 @@ export class BillingCreditService {
private readonly billingService: BillingService,
private readonly billingCreditGrantService: BillingCreditGrantService,
private readonly billingSubscriptionService: BillingSubscriptionService,
- private readonly billingUsageCacheService: BillingUsageCacheService,
- private readonly billingUsageService: BillingUsageService,
private readonly cacheLockService: CacheLockService,
private readonly workspaceCacheService: WorkspaceCacheService,
private readonly usageLimitQuotaService: UsageLimitQuotaService,
@@ -71,7 +67,7 @@ export class BillingCreditService {
private async writeGrantAndRefreshState(
params: GrantCreditsParams,
): Promise<BillingCreditGrantEntity | null> {
- const { workspaceId, amountMicro } = params;
+ const { workspaceId } = params;
const subscription =
await this.billingSubscriptionService.getCurrentBillingSubscription({
@@ -112,21 +108,12 @@ export class BillingCreditService {
`Replayed credit grant for workspace ${workspaceId} (idempotency key ${params.idempotencyKey}), repairing derived state`,
);
- await this.refreshWorkspaceCreditState({
- workspaceId,
- availableDeltaMicro: 0,
- isReplay: true,
- subscription,
- });
+ await this.refreshWorkspaceCreditState(workspaceId);
return alreadyWrittenGrant;
}
- await this.refreshWorkspaceCreditState({
- workspaceId,
- availableDeltaMicro: amountMicro,
- subscription,
- });
+ await this.refreshWorkspaceCreditState(workspaceId);
return grant;
}
@@ -174,186 +161,23 @@ export class BillingCreditService {
grantId: string;
revokedByUserId?: string | null;
}): Promise<BillingCreditGrantEntity> {
- const { grant, wasRevokedNow } =
- await this.billingCreditGrantService.revokeGrant({
- workspaceId,
- grantId,
- revokedByUserId,
- });
-
- const adjustmentKey = buildRevocationAdjustmentKey(grantId);
-
- if (!wasRevokedNow) {
- await this.refreshWorkspaceCreditState({
- workspaceId,
- availableDeltaMicro: 0,
- isReplay: true,
- adjustmentKey,
- });
-
- return grant;
- }
-
- const revokedAtMs = (grant.revokedAt ?? new Date()).getTime();
- const wasActiveWhenRevoked =
- grant.effectiveAt.getTime() <= revokedAtMs &&
- (!isDefined(grant.expiresAt) || grant.expiresAt.getTime() > revokedAtMs);
-
- await this.refreshWorkspaceCreditState({
+ const grant = await this.billingCreditGrantService.revokeGrant({
workspaceId,
- availableDeltaMicro: wasActiveWhenRevoked ? -grant.amountMicro : 0,
- adjustmentKey,
+ grantId,
+ revokedByUserId,
});
+ await this.refreshWorkspaceCreditState(workspaceId);
+
return grant;
}
- async refreshWorkspaceCreditState({
- workspaceId,
- availableDeltaMicro,
- isReplay = false,
- adjustmentKey,
- subscription: knownSubscription,
- }: {
- workspaceId: string;
- availableDeltaMicro: number;
- isReplay?: boolean;
- adjustmentKey?: string;
- subscription?: BillingSubscriptionEntity;
- }): Promise<void> {
- const subscription =
- knownSubscription ??
- (await this.billingSubscriptionService.getCurrentBillingSubscription({
- workspaceId,
- }));
-
- if (!isDefined(subscription)) {
- return;
- }
-
- // Not getBillingSubscriptionPeriod: while trialing it reports the trial window, and the counter is keyed off currentPeriodStart.
- const periodStart = subscription.currentPeriodStart;
-
- if (await this.billingUsageService.isAllowanceCounterEnabled(workspaceId)) {
- await this.billingUsageCacheService.invalidateAvailableCredits(
- workspaceId,
- periodStart,
- );
- } else {
- await this.adjustAvailableCreditsCounter({
- workspaceId,
- periodStart,
- periodEnd: subscription.currentPeriodEnd,
- availableDeltaMicro,
- isReplay,
- adjustmentKey,
- // Incrementing a warm counter leaves its lifetime in place, so credits
- // lapsing before the period ends would stay spendable through the
- // cache. Checked here rather than at each call site so that the
- // rollover, which carries deadlines forward too, cannot miss it.
- mustRebuildCounter: isDefined(
- await this.billingCreditGrantService.findEarliestExpiryBefore({
- workspaceId,
- boundary: subscription.currentPeriodEnd,
- }),
- ),
- });
- }
-
+ async refreshWorkspaceCreditState(workspaceId: string): Promise<void> {
await this.workspaceCacheService.invalidateAndRecompute(workspaceId, [
'currentBillingSubscription',
]);
- const isPureReplay = isReplay && availableDeltaMicro === 0;
-
- if (!isPureReplay) {
- await this.usageLimitQuotaService.dropAllowanceCounter(workspaceId);
- }
- }
-
- private async adjustAvailableCreditsCounter({
- workspaceId,
- periodStart,
- periodEnd,
- availableDeltaMicro,
- isReplay,
- adjustmentKey,
- mustRebuildCounter,
- }: {
- workspaceId: string;
- periodStart: Date;
- periodEnd: Date;
- availableDeltaMicro: number;
- isReplay: boolean;
- adjustmentKey?: string;
- mustRebuildCounter: boolean;
- }): Promise<void> {
- const rebuildCounter =
- mustRebuildCounter ||
- (isReplay &&
- (!isDefined(adjustmentKey) ||
- !(await this.billingUsageCacheService.hasCounterAdjustmentBeenApplied(
- workspaceId,
- adjustmentKey,
- ))));
-
- await this.applyCounterWrite({
- workspaceId,
- periodStart,
- availableDeltaMicro,
- shouldRebuild: rebuildCounter,
- });
-
- if (isDefined(adjustmentKey)) {
- await this.billingUsageCacheService.markCounterAdjustmentApplied(
- workspaceId,
- adjustmentKey,
- periodEnd,
- );
- }
- }
-
- private async applyCounterWrite({
- workspaceId,
- periodStart,
- availableDeltaMicro,
- shouldRebuild,
- }: {
- workspaceId: string;
- periodStart: Date;
- availableDeltaMicro: number;
- shouldRebuild: boolean;
- }): Promise<number | null> {
- if (shouldRebuild) {
- await this.billingUsageCacheService.invalidateAvailableCredits(
- workspaceId,
- periodStart,
- );
-
- return null;
- }
-
- if (availableDeltaMicro === 0) {
- return null;
- }
-
- const cachedAvailableCredits =
- await this.billingUsageCacheService.getAvailableCredits(
- workspaceId,
- periodStart,
- );
-
- if (!isDefined(cachedAvailableCredits)) {
- return null;
- }
-
- await this.billingUsageCacheService.adjustAvailableCredits(
- workspaceId,
- periodStart,
- availableDeltaMicro,
- );
-
- return cachedAvailableCredits + availableDeltaMicro;
+ await this.usageLimitQuotaService.dropAllowanceCounter(workspaceId);
}
}
@@ -362,9 +186,6 @@ export class BillingCreditService {
// by an hour across a DST change.
const MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000;
-const buildRevocationAdjustmentKey = (grantId: string): string =>
- `revoke:${grantId}`;
-
// Null unless the caller asked for a time-boxed grant, and then a period end
// rather than the exact day, for the reasons alignGrantExpiryToPeriodEnd
// documents.
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.ts
index 7f7915d6de9..00517eb0bf3 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.ts
@@ -29,7 +29,6 @@ import { BillingEntitlementKey } from 'src/engine/core-modules/billing/enums/bil
import { WORKSPACE_ACTIVATING_SUBSCRIPTION_STATUSES } from 'src/engine/core-modules/billing/constants/workspace-activating-subscription-statuses.constant';
import { SubscriptionStatus } from 'src/engine/core-modules/billing/enums/billing-subscription-status.enum';
import { BillingPriceService } from 'src/engine/core-modules/billing/services/billing-price.service';
-import { BillingUsageCacheService } from 'src/engine/core-modules/billing/services/billing-usage-cache.service';
import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';
import { StripeCustomerService } from 'src/engine/core-modules/billing/stripe/services/stripe-customer.service';
import { StripeSubscriptionScheduleService } from 'src/engine/core-modules/billing/stripe/services/stripe-subscription-schedule.service';
@@ -69,7 +68,6 @@ export class BillingSubscriptionService {
private readonly billingCustomerRepository: WorkspaceScopedRepository<BillingCustomerEntity>,
private readonly enterprisePlanService: EnterprisePlanService,
private readonly workspaceCacheService: WorkspaceCacheService,
- private readonly billingUsageCacheService: BillingUsageCacheService,
private readonly usageLimitQuotaService: UsageLimitQuotaService,
) {}
@@ -326,8 +324,6 @@ export class BillingSubscriptionService {
updatedSubscription.id,
);
- await this.billingUsageCacheService.flushAvailableCredits(workspace.id);
-
await this.workspaceCacheService.invalidateAndRecompute(workspace.id, [
'currentBillingSubscription',
]);
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage-cache.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage-cache.service.ts
deleted file mode 100644
index dd6e5ba14d3..00000000000
--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage-cache.service.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-/* @license Enterprise */
-
-import { Injectable } from '@nestjs/common';
-
-import { buildBillingUsageAvailableCreditsCacheKey } from 'src/engine/core-modules/billing/utils/build-billing-usage-available-credits-cache-key.util';
-import { buildBillingUsageAvailableCreditsCachePattern } from 'src/engine/core-modules/billing/utils/build-billing-usage-available-credits-cache-pattern.util';
-import { buildBillingUsageCounterAdjustmentKey } from 'src/engine/core-modules/billing/utils/build-billing-usage-counter-adjustment-key.util';
-import { buildBillingUsageCounterAdjustmentPattern } from 'src/engine/core-modules/billing/utils/build-billing-usage-counter-adjustment-pattern.util';
-import { InjectCacheStorage } from 'src/engine/core-modules/cache-storage/decorators/cache-storage.decorator';
-import { CacheStorageService } from 'src/engine/core-modules/cache-storage/services/cache-storage.service';
-import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';
-
-@Injectable()
-export class BillingUsageCacheService {
- constructor(
- @InjectCacheStorage(CacheStorageNamespace.EngineBillingUsage)
- private readonly billingUsageCacheStorage: CacheStorageService,
- ) {}
-
- async getAvailableCredits(
- workspaceId: string,
- periodStart: Date | string,
- ): Promise<number | undefined> {
- return this.billingUsageCacheStorage.get<number>(
- buildBillingUsageAvailableCreditsCacheKey(workspaceId, periodStart),
- );
- }
-
- async warmAvailableCredits(
- workspaceId: string,
- periodStart: Date | string,
- periodEnd: Date | string,
- availableCredits: number,
- ): Promise<void> {
- await this.billingUsageCacheStorage.set(
- buildBillingUsageAvailableCreditsCacheKey(workspaceId, periodStart),
- availableCredits,
- msUntil(periodEnd),
- );
- }
-
- async hasCounterAdjustmentBeenApplied(
- workspaceId: string,
- adjustmentKey: string,
- ): Promise<boolean> {
- const marker = await this.billingUsageCacheStorage.get<boolean>(
- buildBillingUsageCounterAdjustmentKey(workspaceId, adjustmentKey),
- );
-
- return marker === true;
- }
-
- async markCounterAdjustmentApplied(
- workspaceId: string,
- adjustmentKey: string,
- periodEnd: Date | string,
- ): Promise<void> {
- await this.billingUsageCacheStorage.set(
- buildBillingUsageCounterAdjustmentKey(workspaceId, adjustmentKey),
- true,
- msUntil(periodEnd),
- );
- }
-
- async adjustAvailableCredits(
- workspaceId: string,
- periodStart: Date | string,
- deltaCredits: number,
- ): Promise<number> {
- return this.billingUsageCacheStorage.incrBy(
- buildBillingUsageAvailableCreditsCacheKey(workspaceId, periodStart),
- deltaCredits,
- );
- }
-
- async invalidateAvailableCredits(
- workspaceId: string,
- periodStart: Date | string,
- ): Promise<void> {
- await this.billingUsageCacheStorage.del(
- buildBillingUsageAvailableCreditsCacheKey(workspaceId, periodStart),
- );
- }
-
- async flushAvailableCredits(workspaceId: string): Promise<void> {
- await this.billingUsageCacheStorage.flushByPattern(
- buildBillingUsageAvailableCreditsCachePattern(workspaceId),
- );
- }
-
- async flushCounterAdjustmentMarkers(workspaceId: string): Promise<void> {
- await this.billingUsageCacheStorage.flushByPattern(
- buildBillingUsageCounterAdjustmentPattern(workspaceId),
- );
- }
-}
-
-const msUntil = (date: Date | string): number =>
- Math.max(new Date(date).getTime() - Date.now(), 0);
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 41a1fd2504b..7d8c4e9194b 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
@@ -2,7 +2,6 @@
import { Injectable, Logger } from '@nestjs/common';
-import { FeatureFlagKey } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { WorkspaceActivationStatus } from 'twenty-shared/workspace';
@@ -22,19 +21,10 @@ import { SubscriptionStatus } from 'src/engine/core-modules/billing/enums/billin
import { BillingCreditGrantService } from 'src/engine/core-modules/billing/services/billing-credit-grant.service';
import { BillingSubscriptionItemService } from 'src/engine/core-modules/billing/services/billing-subscription-item.service';
import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';
-import { BillingUsageCacheService } from 'src/engine/core-modules/billing/services/billing-usage-cache.service';
import { type CreditAvailability } from 'src/engine/core-modules/billing/types/credit-availability.type';
import { type CurrentBillingSubscription } from 'src/engine/core-modules/billing/types/flat-billing-subscription.type';
import { type SubscriptionInactiveReason } from 'src/engine/core-modules/billing/types/subscription-inactive-reason.type';
-import { buildBillingCreditStateLockKey } from 'src/engine/core-modules/billing/utils/build-billing-credit-state-lock-key.util';
import { getBillingSubscriptionPeriod } from 'src/engine/core-modules/billing/utils/get-billing-subscription-period.util';
-import { isValidCreditAmountMicro } from 'src/engine/core-modules/usage/utils/is-valid-credit-amount-micro.util';
-import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';
-import {
- CacheLockException,
- CacheLockExceptionCode,
-} from 'src/engine/core-modules/cache-lock/exceptions/cache-lock.exception';
-import { FeatureFlagService } from 'src/engine/core-modules/feature-flag/services/feature-flag.service';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.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';
@@ -42,8 +32,6 @@ 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 { type UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';
import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
-import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
-import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
type UsageSumRow = {
@@ -57,23 +45,6 @@ type UsageQuotaScope = {
spenders: UsageSpenders;
};
-type AvailableCreditsParams = {
- workspaceId: string;
- currentPeriodStart: Date;
- currentPeriodEnd: Date;
-};
-
-type AvailableCreditsRead = {
- availableCredits: number;
- isCounterWarm: boolean;
-};
-
-const AVAILABLE_CREDITS_WARM_UP_LOCK_OPTIONS = {
- ms: 50,
- maxRetries: 20,
- ttl: 10_000,
-};
-
@Injectable()
export class BillingUsageService {
protected readonly logger = new Logger(BillingUsageService.name);
@@ -82,33 +53,12 @@ export class BillingUsageService {
private readonly billingSubscriptionService: BillingSubscriptionService,
private readonly twentyConfigService: TwentyConfigService,
private readonly billingSubscriptionItemService: BillingSubscriptionItemService,
- private readonly billingUsageCacheService: BillingUsageCacheService,
- @InjectWorkspaceScopedRepository(BillingSubscriptionEntity)
- private readonly billingSubscriptionRepository: WorkspaceScopedRepository<BillingSubscriptionEntity>,
private readonly workspaceCacheService: WorkspaceCacheService,
private readonly clickHouseService: ClickHouseService,
- private readonly cacheLockService: CacheLockService,
private readonly coreEntityCacheService: CoreEntityCacheService,
- private readonly featureFlagService: FeatureFlagService,
private readonly usageLimitQuotaService: UsageLimitQuotaService,
) {}
- async isAllowanceCounterEnabled(workspaceId: string): Promise<boolean> {
- return this.featureFlagService.isFeatureEnabled(
- FeatureFlagKey.IS_QUOTA_ENGINE_CREDIT_BOUND_ENABLED,
- workspaceId,
- );
- }
-
- private async isAvailableCreditsCounterEnabled(
- workspaceId: string,
- ): Promise<boolean> {
- return (
- this.twentyConfigService.get('IS_BILLING_ENABLED') &&
- !(await this.isAllowanceCounterEnabled(workspaceId))
- );
- }
-
async assertUsageAllowed({
workspaceId,
resourceType,
@@ -117,10 +67,6 @@ export class BillingUsageService {
}: UsageQuotaScope): Promise<void> {
await this.assertSubscriptionActive(workspaceId);
- if (await this.isAvailableCreditsCounterEnabled(workspaceId)) {
- await this.assertAvailableCreditsNotExhausted(workspaceId);
- }
-
await this.usageLimitQuotaService.assertQuotaNotExhausted({
workspaceId,
resourceType,
@@ -150,18 +96,7 @@ export class BillingUsageService {
(scope) => scope.exhaustedKind === 'allowance',
);
- if (!(await this.isAvailableCreditsCounterEnabled(workspaceId))) {
- return { hasNoMoreAvailableCredits: isAllowanceExhausted };
- }
-
- const availableCredits = await this.decrementAvailableCreditsInCache({
- workspaceId,
- usedCredits: cost.creditsUsedMicro,
- });
-
- return {
- hasNoMoreAvailableCredits: isAllowanceExhausted || availableCredits <= 0,
- };
+ return { hasNoMoreAvailableCredits: isAllowanceExhausted };
}
async getSubscriptionInactiveReason(
@@ -221,11 +156,8 @@ export class BillingUsageService {
return { hasAvailableCredits: false, reason: subscriptionInactiveReason };
}
- const remainingMicro = (await this.isAllowanceCounterEnabled(workspaceId))
- ? await this.usageLimitQuotaService.getAllowanceRemainingMicro(
- workspaceId,
- )
- : await this.getAvailableCreditsOrNull(workspaceId);
+ const remainingMicro =
+ await this.usageLimitQuotaService.getAllowanceRemainingMicro(workspaceId);
if (isDefined(remainingMicro) && remainingMicro <= 0) {
return { hasAvailableCredits: false, reason: 'NO_CREDITS' };
@@ -310,45 +242,6 @@ export class BillingUsageService {
};
}
- private async getAvailableCreditsFromClickHouse({
- workspaceId,
- currentPeriodStart,
- }: {
- workspaceId: string;
- currentPeriodStart: Date | string;
- }): Promise<number> {
- const subscription = await this.billingSubscriptionRepository.findOne(
- workspaceId,
- {
- where: { currentPeriodStart: new Date(currentPeriodStart) },
- relations: [
- 'billingSubscriptionItems',
- 'billingSubscriptionItems.billingProduct',
- 'billingSubscriptionItems.billingProduct.billingPrices',
- ],
- },
- );
-
- if (!isDefined(subscription)) {
- throw new BillingException(
- `Subscription not found for workspace ${workspaceId}`,
- BillingExceptionCode.BILLING_SUBSCRIPTION_NOT_FOUND,
- );
- }
-
- const resourceUsageCap = this.getResourceUsageCap(subscription);
-
- const [creditBalance, usage] = await Promise.all([
- this.billingCreditGrantService.getActiveCreditsMicro(workspaceId),
- this.getCurrentPeriodCreditsUsed(
- subscription.workspaceId,
- subscription.currentPeriodStart,
- ),
- ]);
-
- return resourceUsageCap + creditBalance - usage;
- }
-
getTrialResourceUsageCap(subscription: BillingSubscriptionEntity): number {
return this.billingSubscriptionService.getTrialPeriodFreeWorkflowCredits(
subscription,
@@ -383,160 +276,6 @@ export class BillingUsageService {
return Number(resourceCreditPrice.metadata?.credit_amount ?? 0);
}
- private async assertAvailableCreditsNotExhausted(
- workspaceId: string,
- ): Promise<void> {
- const availableCredits = await this.getAvailableCreditsOrNull(workspaceId);
-
- if (isDefined(availableCredits) && availableCredits <= 0) {
- throw new BillingException(
- 'Credits exhausted',
- BillingExceptionCode.BILLING_CREDITS_EXHAUSTED,
- );
- }
- }
-
- private async getAvailableCreditsOrNull(
- workspaceId: string,
- ): Promise<number | null> {
- if (!this.twentyConfigService.get('IS_BILLING_ENABLED')) {
- return null;
- }
-
- const currentBillingSubscription =
- await this.getCachedCurrentBillingSubscription(workspaceId);
-
- if (currentBillingSubscription === NO_BILLING_SUBSCRIPTION) {
- return null;
- }
-
- const { availableCredits } = await this.getOrWarmAvailableCredits({
- workspaceId: currentBillingSubscription.workspaceId,
- currentPeriodStart: currentBillingSubscription.currentPeriodStart,
- currentPeriodEnd: currentBillingSubscription.currentPeriodEnd,
- });
-
- return availableCredits;
- }
-
- private async decrementAvailableCreditsInCache({
- workspaceId,
- usedCredits,
- }: {
- workspaceId: string;
- usedCredits: number;
- }): Promise<number> {
- const creditsToDecrement = isValidCreditAmountMicro(usedCredits)
- ? usedCredits
- : 0;
-
- if (creditsToDecrement !== usedCredits) {
- this.logger.error(
- `Refusing to decrement ${usedCredits} credits for workspace ${workspaceId}; treating as 0`,
- );
- }
-
- const currentBillingSubscription =
- await this.getCachedCurrentBillingSubscription(workspaceId);
-
- if (currentBillingSubscription === NO_BILLING_SUBSCRIPTION) {
- return 0;
- }
-
- const { currentPeriodStart, currentPeriodEnd } = currentBillingSubscription;
-
- const { availableCredits, isCounterWarm } =
- await this.getOrWarmAvailableCredits({
- workspaceId,
- currentPeriodStart,
- currentPeriodEnd,
- });
-
- return isCounterWarm
- ? await this.billingUsageCacheService.adjustAvailableCredits(
- workspaceId,
- currentPeriodStart,
- -creditsToDecrement,
- )
- : availableCredits - creditsToDecrement;
- }
-
- private async readWarmAvailableCredits(
- params: AvailableCreditsParams,
- ): Promise<AvailableCreditsRead | undefined> {
- const availableCredits =
- await this.billingUsageCacheService.getAvailableCredits(
- params.workspaceId,
- params.currentPeriodStart,
- );
-
- return isDefined(availableCredits)
- ? { availableCredits, isCounterWarm: true }
- : undefined;
- }
-
- private async getOrWarmAvailableCredits(
- params: AvailableCreditsParams,
- ): Promise<AvailableCreditsRead> {
- const warmAvailableCredits = await this.readWarmAvailableCredits(params);
-
- if (isDefined(warmAvailableCredits)) {
- return warmAvailableCredits;
- }
-
- try {
- return await this.cacheLockService.withLock(
- async () =>
- (await this.readWarmAvailableCredits(params)) ??
- (await this.computeAndWarmAvailableCredits(params)),
- buildBillingCreditStateLockKey(params.workspaceId),
- AVAILABLE_CREDITS_WARM_UP_LOCK_OPTIONS,
- );
- } catch (error) {
- if (
- !(error instanceof CacheLockException) ||
- error.code !== CacheLockExceptionCode.LOCK_ACQUISITION_TIMEOUT
- ) {
- throw error;
- }
-
- this.logger.warn(
- `Computing available credits for workspace ${params.workspaceId} without the credit state lock: ${error.message}`,
- );
-
- return {
- availableCredits: await this.getAvailableCreditsFromClickHouse(params),
- isCounterWarm: false,
- };
- }
- }
-
- private async computeAndWarmAvailableCredits(
- params: AvailableCreditsParams,
- ): Promise<AvailableCreditsRead> {
- const [availableCredits, earliestExpiry] = await Promise.all([
- this.getAvailableCreditsFromClickHouse(params),
- this.billingCreditGrantService.findEarliestExpiryBefore({
- workspaceId: params.workspaceId,
- boundary: params.currentPeriodEnd,
- }),
- ]);
-
- // A time-boxed grant lapsing before the period ends has to shorten the
- // cache with it, otherwise the counter keeps handing out credits that
- // getActiveCreditsMicro no longer counts.
- const cacheUntil = earliestExpiry ?? params.currentPeriodEnd;
-
- await this.billingUsageCacheService.warmAvailableCredits(
- params.workspaceId,
- params.currentPeriodStart,
- cacheUntil,
- availableCredits,
- );
-
- return { availableCredits, isCounterWarm: true };
- }
-
// Returns null when usage could not be read. ClickHouseService.select
// swallows query errors and returns [], but a bare sum() aggregate always
// yields exactly one row, so an empty result means the read failed rather
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-credit-state-lock-key.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-credit-state-lock-key.util.ts
index b9e4f8f8932..7b06fd35d7d 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-credit-state-lock-key.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-credit-state-lock-key.util.ts
@@ -1,11 +1,7 @@
/* @license Enterprise */
-// Serializes everything that moves a workspace's credit state: writing to the
-// ledger and adjusting the counter derived from it. Readers take it too, but
-// only when the counter is cold, so the warm path stays lock-free.
-//
-// Without it the ledger write and the counter update are two independent
-// steps, and a reader computing availability in between either counts a grant
-// that the writer then adds again, or installs a balance that predates it.
+// Serializes every write to a workspace's credit ledger. The rollover reads the
+// ledger, decides from that snapshot, then writes it back, so a grant landing
+// in between would be carried twice or dropped.
export const buildBillingCreditStateLockKey = (workspaceId: string): string =>
`billing-credit-state:${workspaceId}`;
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-usage-available-credits-cache-key.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-usage-available-credits-cache-key.util.ts
deleted file mode 100644
index 3f82adfacab..00000000000
--- a/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-usage-available-credits-cache-key.util.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-export const buildBillingUsageAvailableCreditsCacheKey = (
- workspaceId: string,
- periodStart: Date | string,
-): string => {
- return `available-credits:${workspaceId}:${new Date(periodStart).getTime()}`;
-};
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-usage-available-credits-cache-pattern.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-usage-available-credits-cache-pattern.util.ts
deleted file mode 100644
index b07ca6eb510..00000000000
--- a/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-usage-available-credits-cache-pattern.util.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-export const buildBillingUsageAvailableCreditsCachePattern = (
- workspaceId: string,
-): string => {
- return `available-credits:${workspaceId}:*`;
-};
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-usage-counter-adjustment-key.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-usage-counter-adjustment-key.util.ts
deleted file mode 100644
index 504db8119ef..00000000000
--- a/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-usage-counter-adjustment-key.util.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-export const buildBillingUsageCounterAdjustmentKey = (
- workspaceId: string,
- adjustmentKey: string,
-): string => {
- return `available-credits-adjusted:${workspaceId}:${adjustmentKey}`;
-};
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-usage-counter-adjustment-pattern.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-usage-counter-adjustment-pattern.util.ts
deleted file mode 100644
index 517bf5dd029..00000000000
--- a/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-usage-counter-adjustment-pattern.util.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-export const buildBillingUsageCounterAdjustmentPattern = (
- workspaceId: string,
-): string => {
- return `available-credits-adjusted:${workspaceId}:*`;
-};
diff --git a/packages/twenty-server/src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum.ts b/packages/twenty-server/src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum.ts
index d5af821115a..0cfc56a9aef 100644
--- a/packages/twenty-server/src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum.ts
+++ b/packages/twenty-server/src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum.ts
@@ -12,7 +12,6 @@ export enum CacheStorageNamespace {
EngineMetrics = 'engine:metrics',
EngineRecordExport = 'engine:record-export',
EngineSubscriptions = 'engine:subscriptions',
- EngineBillingUsage = 'engine:billing-usage',
EngineUsageLimit = 'engine:usage-limit',
EngineOnboardingInviteSuggestions = 'engine:onboarding-invite-suggestions',
IntegrationTests = 'integration-tests',
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/interfaces/credit-allowance-provider.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/interfaces/credit-allowance-provider.service.ts
index 964874b072a..cb944c57f98 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/interfaces/credit-allowance-provider.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/interfaces/credit-allowance-provider.service.ts
@@ -5,7 +5,7 @@ import { type UsagePeriod } from 'src/engine/core-modules/usage-limit/types/usag
@Injectable()
export abstract class CreditAllowanceProvider {
- abstract isCreditAllowanceEnabled(workspaceId: string): Promise<boolean>;
+ abstract isCreditAllowanceEnabled(): Promise<boolean>;
abstract getCreditAllowancePeriod(
workspaceId: string,
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/__tests__/usage-limit-quota.service.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/__tests__/usage-limit-quota.service.spec.ts
index a50fc509576..e6c0a700922 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/__tests__/usage-limit-quota.service.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/__tests__/usage-limit-quota.service.spec.ts
@@ -137,7 +137,13 @@ describe('UsageLimitQuotaService', () => {
ALLOWANCE_PERIOD,
);
creditAllowanceProvider.getCreditAllowance.mockResolvedValue(
- allowanceMicro === null ? null : { ...ALLOWANCE_PERIOD, allowanceMicro },
+ allowanceMicro === null
+ ? null
+ : {
+ ...ALLOWANCE_PERIOD,
+ allowanceMicro,
+ validUntil: ALLOWANCE_PERIOD.periodEnd,
+ },
);
};
@@ -287,6 +293,25 @@ describe('UsageLimitQuotaService', () => {
]);
});
+ it('expires a warm allowance counter with the earliest lapsing grant', async () => {
+ const validUntil = new Date(Date.now() + 60_000);
+
+ setAllowance(100);
+ creditAllowanceProvider.getCreditAllowance.mockResolvedValue({
+ ...ALLOWANCE_PERIOD,
+ allowanceMicro: 100,
+ validUntil,
+ });
+ cacheStorage.mget.mockResolvedValue([undefined]);
+
+ await assertQuotaNotExhausted();
+
+ const [[entries]] = cacheStorage.mset.mock.calls;
+
+ expect(entries[0].ttl).toBeLessThanOrEqual(60_000);
+ expect(entries[0].ttl).toBeGreaterThan(0);
+ });
+
it('scopes a spent allowance counter over the live allowance', async () => {
setAllowance(2_000_000);
cacheStorage.mget.mockResolvedValue([0]);
@@ -332,6 +357,7 @@ describe('UsageLimitQuotaService', () => {
allowanceMicro: 100,
periodStart: new Date('2026-09-15T09:00:00.000Z'),
periodEnd: new Date('2100-10-15T09:00:00.000Z'),
+ validUntil: new Date('2100-10-15T09:00:00.000Z'),
});
cacheStorage.mget.mockResolvedValue([undefined]);
@@ -703,6 +729,7 @@ describe('UsageLimitQuotaService', () => {
...ALLOWANCE_PERIOD,
periodStart: new Date('2026-09-15T09:00:00.000Z'),
allowanceMicro: 2000,
+ validUntil: ALLOWANCE_PERIOD.periodEnd,
});
await expect(service.getAllowanceUsage('workspace-1')).resolves.toEqual({
limitValue: 2000,
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 7b2444ca95f..292f7642fe9 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
@@ -596,11 +596,7 @@ export class UsageLimitQuotaService implements OnModuleInit {
private async buildAllowanceCounter(
workspaceId: string,
): Promise<AllowanceQuotaCounter | null> {
- if (
- !(await this.creditAllowanceProvider.isCreditAllowanceEnabled(
- workspaceId,
- ))
- ) {
+ if (!(await this.creditAllowanceProvider.isCreditAllowanceEnabled())) {
return null;
}
@@ -811,13 +807,7 @@ export class UsageLimitQuotaService implements OnModuleInit {
counter: AllowanceQuotaCounter | undefined;
now: number;
}): Promise<{ key: string; value: number; ttl: number }[]> {
- if (!isDefined(counter)) {
- return [];
- }
-
- const ttl = counter.periodEnd.getTime() - now;
-
- if (ttl <= 0) {
+ if (!isDefined(counter) || counter.periodEnd.getTime() <= now) {
return [];
}
@@ -831,6 +821,14 @@ export class UsageLimitQuotaService implements OnModuleInit {
return [];
}
+ const ttl =
+ Math.min(counter.periodEnd.getTime(), allowance.validUntil.getTime()) -
+ now;
+
+ if (ttl <= 0) {
+ return [];
+ }
+
const consumedMicro =
await this.usageAnalyticsService.getCreditsUsedMicroForBillingPeriod({
workspaceId,
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/credit-allowance.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/credit-allowance.type.ts
index 8f98e0b8402..6168f850977 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/credit-allowance.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/credit-allowance.type.ts
@@ -2,4 +2,7 @@ import { type UsagePeriod } from 'src/engine/core-modules/usage-limit/types/usag
export type CreditAllowance = UsagePeriod & {
allowanceMicro: number;
+ // When the figure stops being right before the period ends: a grant lapsing
+ // inside the period lowers it with no ledger write to drop the counter.
+ validUntil: Date;
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-exhausted-scope.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-exhausted-scope.util.spec.ts
index d3707c0d829..477ad11a318 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-exhausted-scope.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-exhausted-scope.util.spec.ts
@@ -73,6 +73,7 @@ describe('buildQuotaExhaustedScope', () => {
periodStart: PERIOD_START,
periodEnd: PERIOD_END,
allowanceMicro: 2_000_000,
+ validUntil: PERIOD_END,
},
}),
).toEqual({
diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-feature-flags.util.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-feature-flags.util.ts
index f2deb8ba39e..20b75c82c26 100644
--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-feature-flags.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-feature-flags.util.ts
@@ -8,7 +8,6 @@ const DEFAULT_SEEDED_FEATURE_FLAGS: Partial<Record<FeatureFlagKey, boolean>> = {
[FeatureFlagKey.IS_JUNCTION_RELATIONS_ENABLED]: true,
[FeatureFlagKey.IS_MESSAGE_CALENDAR_TARGET_READ_ENABLED]: true,
[FeatureFlagKey.IS_MESSAGE_CAMPAIGN_ENABLED]: true,
- [FeatureFlagKey.IS_QUOTA_ENGINE_CREDIT_BOUND_ENABLED]: false,
[FeatureFlagKey.IS_RECORD_SHARING_ENABLED]: false,
[FeatureFlagKey.IS_INITIAL_OBJECT_VIEW_ENABLED]: false,
};
diff --git a/packages/twenty-server/test/integration/billing/suites/billing-credit-grant-admin.integration-spec.ts b/packages/twenty-server/test/integration/billing/suites/billing-credit-grant-admin.integration-spec.ts
index 432e9a8cedf..7fc6ad4bfad 100644
--- a/packages/twenty-server/test/integration/billing/suites/billing-credit-grant-admin.integration-spec.ts
+++ b/packages/twenty-server/test/integration/billing/suites/billing-credit-grant-admin.integration-spec.ts
@@ -4,7 +4,6 @@ import { randomUUID } from 'node:crypto';
import { addDays, addMonths, startOfMonth } from 'date-fns';
import request from 'supertest';
import {
- getBillingUsageCacheService,
getSeededBillingWorkspaceId,
listCreditGrants,
quitBillingFixtureRedis,
@@ -186,15 +185,8 @@ describe('Admin credit grant and revoke (integration)', () => {
expect(await listCreditGrants(workspaceId)).toHaveLength(0);
});
- it('adds the granted amount to a warm available-credits counter', async () => {
- const cache = getBillingUsageCacheService();
-
- await cache.warmAvailableCredits(
- workspaceId,
- PERIOD_START,
- PERIOD_END,
- 500_000,
- );
+ it('drops the warm allowance counter when a grant lands', async () => {
+ await warmAllowanceCounter(workspaceId, PERIOD_START, 500_000);
await grantCredits({
workspaceId,
@@ -203,46 +195,10 @@ describe('Admin credit grant and revoke (integration)', () => {
reason: null,
});
- expect(await cache.getAvailableCredits(workspaceId, PERIOD_START)).toBe(
- 500_000 + 2 * INTERNAL_CREDITS_PER_DISPLAY_CREDIT,
- );
- });
-
- // The aligned deadline lands on the period end the counter already expires
- // with, so the cached balance stays valid and can simply be incremented.
- it('keeps a warm available-credits counter usable for a time-boxed grant', async () => {
- const cache = getBillingUsageCacheService();
-
- await cache.warmAvailableCredits(
- workspaceId,
- PERIOD_START,
- PERIOD_END,
- 500_000,
- );
-
- await grantCredits({
- workspaceId,
- amount: 2,
- type: BillingCreditGrantType.SALES,
- reason: null,
- expiresInDays: 1,
- });
-
- expect(await cache.getAvailableCredits(workspaceId, PERIOD_START)).toBe(
- 500_000 + 2 * INTERNAL_CREDITS_PER_DISPLAY_CREDIT,
- );
+ expect(await readAllowanceCounter(workspaceId, PERIOD_START)).toBeNull();
});
- it('takes a revoked grant back off the ledger and the available-credits counter', async () => {
- const cache = getBillingUsageCacheService();
-
- await cache.warmAvailableCredits(
- workspaceId,
- PERIOD_START,
- PERIOD_END,
- 500_000,
- );
-
+ it('takes a revoked grant off the ledger and drops the counter', async () => {
const granted = await grantCredits({
workspaceId,
amount: 2,
@@ -251,6 +207,8 @@ describe('Admin credit grant and revoke (integration)', () => {
});
const creditGrantId = granted.body.data.grantWorkspaceCredits.id;
+ await warmAllowanceCounter(workspaceId, PERIOD_START, 500_000);
+
const revoked = await callAdminGraphql(REVOKE_MUTATION, {
workspaceId,
creditGrantId,
@@ -264,42 +222,10 @@ describe('Admin credit grant and revoke (integration)', () => {
const grants = await listCreditGrants(workspaceId);
expect(grants[0].revokedAt).not.toBeNull();
- expect(await cache.getAvailableCredits(workspaceId, PERIOD_START)).toBe(
- 500_000,
- );
- });
-
- it.each([
- BillingCreditGrantType.ROLLOVER,
- BillingCreditGrantType.ONBOARDING_REWARD,
- ])('refuses to grant a %s by hand', async (type) => {
- const response = await grantCredits({
- workspaceId,
- amount: 1,
- type,
- reason: null,
- });
-
- expect(response.body.errors?.[0]?.extensions?.subCode).toBe(
- 'BILLING_CREDIT_GRANT_TYPE_NOT_GRANTABLE',
- );
- expect(await listCreditGrants(workspaceId)).toHaveLength(0);
- });
-
- it('drops the warm allowance counter when a grant lands', async () => {
- await warmAllowanceCounter(workspaceId, PERIOD_START, 500_000);
-
- await grantCredits({
- workspaceId,
- amount: 2,
- type: BillingCreditGrantType.COMPENSATION,
- reason: null,
- });
-
expect(await readAllowanceCounter(workspaceId, PERIOD_START)).toBeNull();
});
- it('takes a revoked grant off the ledger and drops the counter', async () => {
+ it('drops the counter again when a revocation is retried', async () => {
const granted = await grantCredits({
workspaceId,
amount: 2,
@@ -308,21 +234,15 @@ describe('Admin credit grant and revoke (integration)', () => {
});
const creditGrantId = granted.body.data.grantWorkspaceCredits.id;
+ await callAdminGraphql(REVOKE_MUTATION, { workspaceId, creditGrantId });
await warmAllowanceCounter(workspaceId, PERIOD_START, 500_000);
- const revoked = await callAdminGraphql(REVOKE_MUTATION, {
+ const retried = await callAdminGraphql(REVOKE_MUTATION, {
workspaceId,
creditGrantId,
});
- expect(revoked.body.errors).toBeUndefined();
- expect(
- revoked.body.data.revokeWorkspaceCreditGrant.revokedAt,
- ).not.toBeNull();
-
- const grants = await listCreditGrants(workspaceId);
-
- expect(grants[0].revokedAt).not.toBeNull();
+ expect(retried.body.errors).toBeUndefined();
expect(await readAllowanceCounter(workspaceId, PERIOD_START)).toBeNull();
});
@@ -374,12 +294,14 @@ describe('Admin credit grant and revoke (integration)', () => {
};
const first = await callAdminGraphql(GRANT_MUTATION, variables);
+ await warmAllowanceCounter(workspaceId, PERIOD_START, 500_000);
const second = await callAdminGraphql(GRANT_MUTATION, variables);
expect(second.body.data.grantWorkspaceCredits.id).toBe(
first.body.data.grantWorkspaceCredits.id,
);
expect(await listCreditGrants(workspaceId)).toHaveLength(1);
+ expect(await readAllowanceCounter(workspaceId, PERIOD_START)).toBeNull();
});
// The refusal to time-box a grant with no billing period must not reach a
diff --git a/packages/twenty-server/test/integration/billing/suites/billing-credit-rollover.integration-spec.ts b/packages/twenty-server/test/integration/billing/suites/billing-credit-rollover.integration-spec.ts
index 882f50c8481..b3fffdb8f17 100644
--- a/packages/twenty-server/test/integration/billing/suites/billing-credit-rollover.integration-spec.ts
+++ b/packages/twenty-server/test/integration/billing/suites/billing-credit-rollover.integration-spec.ts
@@ -2,7 +2,6 @@ import { addMonths, startOfMonth, subMonths } from 'date-fns';
import request from 'supertest';
import { createMockStripeInvoiceFinalizedData } from 'test/integration/billing/utils/create-mock-stripe-invoice-finalized-data.util';
import {
- getBillingUsageCacheService,
getSeededBillingWorkspaceId,
insertCreditGrant,
listCreditGrants,
@@ -209,55 +208,25 @@ describe('Billing credit rollover (integration)', () => {
expect(await listCreditGrants(workspaceId)).toHaveLength(0);
});
- it('adds the carried balance to a warm available-credits counter', async () => {
+ it('drops the allowance counter on the period transition', async () => {
usageSpy.mockResolvedValue(300_000);
- const cache = getBillingUsageCacheService();
- await cache.warmAvailableCredits(
- workspaceId,
- CLOSING_PERIOD_START,
- NEXT_PERIOD_END,
- 120_000,
- );
+ // The counter is keyed by the period the subscription is currently in,
+ // which is the one the invoice is closing: Stripe moves the subscription
+ // forward in a separate event.
+ await warmAllowanceCounter(workspaceId, CLOSING_PERIOD_START, 120_000);
await postInvoiceFinalized().expect(200);
expect(
- await cache.getAvailableCredits(workspaceId, CLOSING_PERIOD_START),
- ).toBe(120_000 + 700_000);
+ await readAllowanceCounter(workspaceId, CLOSING_PERIOD_START),
+ ).toBeNull();
});
- it('leaves a warm available-credits counter alone when a successful delivery is repeated', async () => {
+ it('drops the allowance counter again when a successful delivery is repeated', async () => {
usageSpy.mockResolvedValue(300_000);
- const cache = getBillingUsageCacheService();
-
- await cache.warmAvailableCredits(
- workspaceId,
- CLOSING_PERIOD_START,
- NEXT_PERIOD_END,
- 120_000,
- );
-
- await postInvoiceFinalized().expect(200);
- const afterFirst = await cache.getAvailableCredits(
- workspaceId,
- CLOSING_PERIOD_START,
- );
await postInvoiceFinalized().expect(200);
-
- expect(afterFirst).toBe(120_000 + 700_000);
- expect(
- await cache.getAvailableCredits(workspaceId, CLOSING_PERIOD_START),
- ).toBe(afterFirst);
- });
-
- it('drops the allowance counter on the period transition', async () => {
- usageSpy.mockResolvedValue(300_000);
-
- // The counter is keyed by the period the subscription is currently in,
- // which is the one the invoice is closing: Stripe moves the subscription
- // forward in a separate event.
await warmAllowanceCounter(workspaceId, CLOSING_PERIOD_START, 120_000);
await postInvoiceFinalized().expect(200);
diff --git a/packages/twenty-server/test/integration/billing/utils/billing-credit-fixtures.util.ts b/packages/twenty-server/test/integration/billing/utils/billing-credit-fixtures.util.ts
index 86d27df8894..234470014d8 100644
--- a/packages/twenty-server/test/integration/billing/utils/billing-credit-fixtures.util.ts
+++ b/packages/twenty-server/test/integration/billing/utils/billing-credit-fixtures.util.ts
@@ -3,12 +3,9 @@ import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
import { type BillingCreditGrantType } from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';
import { type SubscriptionStatus } from 'src/engine/core-modules/billing/enums/billing-subscription-status.enum';
-import { type BillingUsageCacheService } from 'src/engine/core-modules/billing/services/billing-usage-cache.service';
import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';
import { buildAllowanceCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-allowance-counter-key.util';
-import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
-
// The dev seeder gives every workspace a billingCustomer and an active
// billingSubscription, but no subscription item, and no period. Rollover needs
// the whole chain — subscription -> item -> product -> price with a
@@ -229,11 +226,6 @@ export const resetBillingCreditState = async (
[workspaceId],
);
- const cache = getBillingUsageCacheService();
-
- await cache.flushAvailableCredits(workspaceId);
- await cache.flushCounterAdjustmentMarkers(workspaceId);
-
const redis = await getRedisClient();
const staleKeys = [
...(await redis.keys(`*{${workspaceId}}:quota:allowance:*`)),
@@ -245,11 +237,6 @@ export const resetBillingCreditState = async (
}
};
-export const getBillingUsageCacheService = (): BillingUsageCacheService =>
- getAppProviderByClassName<BillingUsageCacheService>(
- 'BillingUsageCacheService',
- );
-
// Cancelling is what makes getCurrentBillingSubscription stop returning it, so
// this is how a test reaches the no-subscription path without deleting rows the
// rest of the suite shares.
diff --git a/packages/twenty-shared/src/types/FeatureFlagKey.ts b/packages/twenty-shared/src/types/FeatureFlagKey.ts
index 26634655fcf..245f1a46b54 100644
--- a/packages/twenty-shared/src/types/FeatureFlagKey.ts
+++ b/packages/twenty-shared/src/types/FeatureFlagKey.ts
@@ -9,7 +9,6 @@ export enum FeatureFlagKey {
IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED = 'IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED',
IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED = 'IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED',
IS_MESSAGE_CALENDAR_TARGET_READ_ENABLED = 'IS_MESSAGE_CALENDAR_TARGET_READ_ENABLED',
- IS_QUOTA_ENGINE_CREDIT_BOUND_ENABLED = 'IS_QUOTA_ENGINE_CREDIT_BOUND_ENABLED',
IS_RECORD_SHARING_ENABLED = 'IS_RECORD_SHARING_ENABLED',
IS_INITIAL_OBJECT_VIEW_ENABLED = 'IS_INITIAL_OBJECT_VIEW_ENABLED',
IS_WEBHOOK_RATE_LIMIT_ENABLED = 'IS_WEBHOOK_RATE_LIMIT_ENABLED',