The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
fix(usage-limit): only a row on the default's period replaces it (#27272)
Etiennee286f73bdd14
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-overridden-quota-default-counter-keys.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-overridden-quota-default-counter-keys.util.spec.tsindex 5f321181671..d9e22763c31 100644--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-overridden-quota-default-counter-keys.util.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-overridden-quota-default-counter-keys.util.spec.ts@@ -65,25 +65,9 @@ describe('buildOverriddenQuotaDefaultCounterKeys', () => {expect(buildKeys()).toEqual([DEFAULT_COUNTER_KEY]);});- it('keys it whatever period the row itself spans', () => {+ it('leaves alone a default the row does not suppress', () => {expect(buildKeys({ usageLimit: buildUsageLimit({ periodUnit: 'month' }) }),- ).toEqual([DEFAULT_COUNTER_KEY]);- });-- it.each([- { spenderType: 'userWorkspace' as const },- { unit: UsageUnit.CREDIT },- { operationType: UsageOperationType.ALL },- ])('leaves a default on another scope alone: %j', (overrides) => {- expect(buildKeys({ usageLimit: buildUsageLimit(overrides) })).toEqual([]);- });-- it('leaves a default no row can suppress alone', () => {- expect(- buildKeys({- quotaLimitDefaults: [buildDefault({ isOverridable: false })],- }),).toEqual([]);});diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-counters.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-counters.util.spec.tsindex d7309fdeb80..ba0c9397966 100644--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-counters.util.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-counters.util.spec.ts@@ -196,28 +196,6 @@ describe('buildQuotaCounters', () => {},);- it('keeps a non-overridable default alongside a stored limit', () => {- const counters = buildCounters({- limits: [buildLimit({})],- quotaLimitDefaults: [buildDefault({ isOverridable: false })],- });-- expect(counters.map((counter) => counter.isDefault)).toEqual([false, true]);- expect(new Set(counters.map((counter) => counter.key)).size).toBe(2);- });-- it.each([- { spenderType: 'userWorkspace' as const, spenderId: 'user-1' },- { unit: UsageUnit.TOKEN },- ])('preserves the default for a different scope: %j', (overrides) => {- const counters = buildCounters({- limits: [buildLimit(overrides)],- quotaLimitDefaults: [buildDefault()],- });-- expect(counters.map((counter) => counter.isDefault)).toEqual([false, true]);- });-it('skips a default whose period was not resolved', () => {const counters = buildCounters({quotaLimitDefaults: [buildDefault({ periodUnit: 'day' })],@@ -234,15 +212,6 @@ describe('buildQuotaCounters', () => {expect(counters).toEqual([]);});- it('preserves the default against a row scoped to every operation', () => {- const counters = buildCounters({- limits: [buildLimit({ operationType: UsageOperationType.ALL })],- quotaLimitDefaults: [buildDefault()],- });-- expect(counters.map((counter) => counter.isDefault)).toEqual([true, false]);- });-it('ignores a default declared on another operation', () => {const counters = buildCounters({quotaLimitDefaults: [@@ -253,7 +222,7 @@ describe('buildQuotaCounters', () => {expect(counters).toEqual([]);});- it('overrides the default whatever period the stored limit spans', () => {+ it('keeps the default alongside a stored limit on another period', () => {const counters = buildCounters({limits: [buildLimit({ periodUnit: 'week' })],quotaLimitDefaults: [buildDefault()],@@ -261,6 +230,8 @@ describe('buildQuotaCounters', () => {expect(counters).toEqual([expect.objectContaining({ isDefault: false, periodUnit: 'week' }),+ expect.objectContaining({ isDefault: true, periodUnit: 'month' }),]);+ expect(new Set(counters.map((counter) => counter.key)).size).toBe(2);});});diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/does-usage-limit-row-suppress-default.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/does-usage-limit-row-suppress-default.util.spec.tsindex 2fb1e3fde83..2bfa9b5d987 100644--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/does-usage-limit-row-suppress-default.util.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/does-usage-limit-row-suppress-default.util.spec.ts@@ -80,6 +80,7 @@ describe('doesUsageLimitRowSuppressDefault', () => {{ resourceType: UsageResourceType.RECORD } as Partial<UsageLimitScope>,],['limit kind', { limitKind: 'quota' } as Partial<UsageLimitScope>],+ ['period unit', { periodUnit: 'day' } as Partial<UsageLimitScope>],])('does not suppress across a different %s', (_label, overrides) => {expect(doesUsageLimitRowSuppressDefault({@@ -98,11 +99,11 @@ describe('doesUsageLimitRowSuppressDefault', () => {).toBe(false);});- it('ignores the period, which no builder matches on', () => {+ it('ignores the period count, which a speed window can change', () => {expect(doesUsageLimitRowSuppressDefault({- scope: buildScope({ periodCount: 60, periodUnit: 'second' }),- usageLimitDefault: buildDefault(),+ scope: buildScope({ periodCount: 60 }),+ usageLimitDefault: buildDefault({ periodCount: 1 }),}),).toBe(true);});diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-suppressed-usage-limit-defaults.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-suppressed-usage-limit-defaults.util.spec.tsindex e7cb95fce16..e52ed2011c3 100644--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-suppressed-usage-limit-defaults.util.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-suppressed-usage-limit-defaults.util.spec.ts@@ -3,41 +3,12 @@ import {buildUsageLimitScope,type UsageLimitScope,} from 'src/engine/core-modules/usage-limit/utils/build-usage-limit-scope.util';+import { doesUsageLimitRowSuppressDefault } from 'src/engine/core-modules/usage-limit/utils/does-usage-limit-row-suppress-default.util';import { findSuppressedUsageLimitDefaults } from 'src/engine/core-modules/usage-limit/utils/find-suppressed-usage-limit-defaults.util';import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';-const buildSpeedScope = (- overrides: Partial<UsageLimitScope> = {},-): UsageLimitScope =>- buildUsageLimitScope({- resourceType: UsageResourceType.EMAIL,- operationType: UsageOperationType.EMAIL_SEND,- spenderType: 'workspace',- spenderId: '',- limitKind: 'speed',- periodCount: 10,- periodUnit: 'second',- unit: UsageUnit.INVOCATION,- ...overrides,- });--const buildStockScope = (- overrides: Partial<UsageLimitScope> = {},-): UsageLimitScope =>- buildUsageLimitScope({- resourceType: UsageResourceType.STORAGE,- operationType: UsageOperationType.STORAGE_FILE,- spenderType: 'workspace',- spenderId: '',- limitKind: 'stock',- periodCount: 1,- periodUnit: 'lifetime',- unit: UsageUnit.BYTE,- ...overrides,- });-const buildQuotaScope = (overrides: Partial<UsageLimitScope> = {},): UsageLimitScope =>@@ -54,128 +25,52 @@ const buildQuotaScope = (});describe('findSuppressedUsageLimitDefaults', () => {- it('returns only the overridable default when a resource declares one of each', () => {- const suppressed = findSuppressedUsageLimitDefaults(buildSpeedScope());-- expect(suppressed).toHaveLength(1);- expect(suppressed[0]).toMatchObject({- isOverridable: true,- counterScope: 'perWorkspace',- limitValueConfigVariable: 'EMAIL_SEND_WORKSPACE_RATE_LIMITING_LIMIT',- });- });-- it('leaves the other operation of the same resource alone', () => {- const suppressed = findSuppressedUsageLimitDefaults(- buildSpeedScope({- operationType: UsageOperationType.MESSAGE_CAMPAIGN_SEND,- }),- );-- expect(suppressed).toHaveLength(1);- expect(suppressed[0].operationType).toBe(- UsageOperationType.MESSAGE_CAMPAIGN_SEND,- );- });-- it('replaces the api key default whatever period the row names', () => {- const suppressed = findSuppressedUsageLimitDefaults(- buildSpeedScope({- resourceType: UsageResourceType.API,- operationType: UsageOperationType.API_REQUEST,- spenderType: 'apiKey',- periodCount: 1,- unit: UsageUnit.REQUEST,- }),- );-- expect(suppressed.map((entry) => entry.limitValueConfigVariable)).toEqual([- 'API_RATE_LIMITING_LONG_LIMIT',- ]);- });-- it('returns nothing where only a non-overridable default stands', () => {- expect(- findSuppressedUsageLimitDefaults(- buildSpeedScope({- resourceType: UsageResourceType.API,- operationType: UsageOperationType.API_REQUEST,- spenderType: 'application',- unit: UsageUnit.REQUEST,- }),- ),- ).toEqual([]);- });-- it('returns nothing for a unit no default is declared on', () => {- expect(- findSuppressedUsageLimitDefaults(- buildStockScope({ unit: UsageUnit.FILE }),- ),- ).toEqual([]);- });-- it('returns nothing for a row scoped to one spender', () => {- expect(- findSuppressedUsageLimitDefaults(- buildStockScope({ spenderId: 'ef0cfbbd-8b6e-4f9d-9a7c-1a2b3c4d5e6f' }),- ),- ).toEqual([]);- });-- it('declares at most one overridable default per suppressible scope', () => {- const suppressionKeysWithTwoDefaults = Object.values(UsageResourceType)- .flatMap((resourceType) => findUsageLimitDefaults({ resourceType }))- .filter((usageLimitDefault) => usageLimitDefault.isOverridable)- .map(- (usageLimitDefault) =>- `${usageLimitDefault.resourceType}:${usageLimitDefault.operationType}:${usageLimitDefault.spenderType}:${usageLimitDefault.limitKind}:${usageLimitDefault.unit}`,- )- .filter(- (suppressionKey, _index, suppressionKeys) =>- suppressionKeys.filter((key) => key === suppressionKey).length > 1,- );-- expect(suppressionKeysWithTwoDefaults).toEqual([]);- });-- it('replaces the email quota default whatever period the row names', () => {- const suppressed = findSuppressedUsageLimitDefaults(- buildQuotaScope({ periodUnit: 'month', periodCount: 3 }),- );+ it('returns the default the row replaces', () => {+ const suppressed = findSuppressedUsageLimitDefaults(buildQuotaScope());expect(suppressed.map((entry) => entry.limitValueConfigVariable)).toEqual(['EMAIL_SEND_WORKSPACE_DAILY_LIMIT',]);});- it('leaves the email quota default alone for a row on every operation', () => {+ it('returns nothing when the row replaces no default', () => {expect(findSuppressedUsageLimitDefaults(- buildQuotaScope({ operationType: UsageOperationType.ALL }),+ buildQuotaScope({ periodUnit: 'month' }),),).toEqual([]);});- it('leaves the email quota default alone for the speed kind', () => {- expect(- findSuppressedUsageLimitDefaults(- buildQuotaScope({ limitKind: 'speed', periodUnit: 'second' }),- ).map((entry) => entry.limitKind),- ).toEqual(['speed']);- });-it('returns nothing for a resource that declares no default', () => {expect(findSuppressedUsageLimitDefaults(- buildStockScope({+ buildQuotaScope({resourceType: UsageResourceType.AI,operationType: UsageOperationType.AI_CHAT_TOKEN,- limitKind: 'quota',periodUnit: 'month',unit: UsageUnit.CREDIT,}),),).toEqual([]);});++ it('declares at most one overridable default per suppressible scope', () => {+ const overridableDefaults = Object.values(UsageResourceType)+ .flatMap((resourceType) => findUsageLimitDefaults({ resourceType }))+ .filter((usageLimitDefault) => usageLimitDefault.isOverridable);++ const defaultsSharingAScope = overridableDefaults.filter(+ (usageLimitDefault) =>+ overridableDefaults.some(+ (otherDefault) =>+ otherDefault !== usageLimitDefault &&+ doesUsageLimitRowSuppressDefault({+ scope: usageLimitDefault,+ usageLimitDefault: otherDefault,+ }),+ ),+ );++ expect(defaultsSharingAScope).toEqual([]);+ });});diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/does-usage-limit-row-suppress-default.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/does-usage-limit-row-suppress-default.util.tsindex 1dce1fc2f43..386ed5701bd 100644--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/does-usage-limit-row-suppress-default.util.ts+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/does-usage-limit-row-suppress-default.util.ts@@ -1,6 +1,6 @@import { type UsageLimitScope } from 'src/engine/core-modules/usage-limit/utils/build-usage-limit-scope.util';-type SuppressibleScope = Omit<UsageLimitScope, 'periodCount' | 'periodUnit'>;+type SuppressibleScope = Omit<UsageLimitScope, 'periodCount'>;export const doesUsageLimitRowSuppressDefault = ({scope,@@ -15,4 +15,5 @@ export const doesUsageLimitRowSuppressDefault = ({scope.spenderType === usageLimitDefault.spenderType &&scope.spenderId === usageLimitDefault.spenderId &&scope.limitKind === usageLimitDefault.limitKind &&+ scope.periodUnit === usageLimitDefault.periodUnit &&scope.unit === usageLimitDefault.unit;diff --git a/packages/twenty-server/test/integration/usage-limit/usage-limit-mutations.integration-spec.ts b/packages/twenty-server/test/integration/usage-limit/usage-limit-mutations.integration-spec.tsindex 9d88d272070..af4da5d5068 100644--- a/packages/twenty-server/test/integration/usage-limit/usage-limit-mutations.integration-spec.ts+++ b/packages/twenty-server/test/integration/usage-limit/usage-limit-mutations.integration-spec.ts@@ -347,6 +347,17 @@ describe('Usage limit mutations', () => {...overrides,});+ const emailQuotaPayload = (+ overrides: Partial<CreateUsageLimitInput> = {},+ ) =>+ buildPayload({+ resourceType: UsageResourceType.EMAIL,+ operationType: UsageOperationType.EMAIL_SEND,+ unit: UsageUnit.INVOCATION,+ limitValue: 5_000,+ ...overrides,+ });+const seedOperatorOverride = async () => {await usageLimitRepository.insert({workspaceId: SEED_APPLE_WORKSPACE_ID,@@ -381,6 +392,24 @@ describe('Usage limit mutations', () => {).toBe(0);});+ it('refuses a workspace email quota on the daily default period', async () => {+ const response = await createUsageLimitRequest(+ emailQuotaPayload({ periodUnit: 'day' }),+ );++ expect(response.body.errors?.[0]?.message).toEqual(+ expect.stringContaining(OPERATOR_ONLY_MESSAGE),+ );+ });++ it('allows a workspace email quota on another period, stacked on the daily default', async () => {+ const response = await createUsageLimitRequest(+ emailQuotaPayload({ periodUnit: 'month' }),+ );++ expect(response.body.errors).toBeUndefined();+ });+it('allows a workspace write on a unit no default covers', async () => {const response = await makeMetadataApiRequest({query: CREATE_USAGE_LIMIT,