The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
refactor(server): extract a single LRU eviction primitive (#25733)
Etienne079b6e0ce379
diff --git a/packages/twenty-server/src/engine/workspace-cache/utils/sweep-local-cache.util.ts b/packages/twenty-server/src/engine/workspace-cache/utils/sweep-local-cache.util.tsindex 9cb7fccb585..18b87fc18c8 100644--- a/packages/twenty-server/src/engine/workspace-cache/utils/sweep-local-cache.util.ts+++ b/packages/twenty-server/src/engine/workspace-cache/utils/sweep-local-cache.util.ts@@ -1,4 +1,5 @@import { type WorkspaceLocalCacheEntry } from 'src/engine/workspace-cache/types/workspace-local-cache-entry.type';+import { evictLeastRecentlyUsed } from 'src/utils/lru-map.util';export type LocalCacheSweepConfig = {ttlMs: number;@@ -10,43 +11,6 @@ export type LocalCacheSweepConfig = {const lastReadAtOf = <T>(entry: WorkspaceLocalCacheEntry<T>): number =>entry.versions.get(entry.latestHash)?.lastReadAt ?? 0;-const evictLeastRecentlyRead = <T>({- localCache,- matches,- maxEntries,- minEvict,-}: {- localCache: Map<string, WorkspaceLocalCacheEntry<T>>;- matches: (key: string) => boolean;- maxEntries: number;- minEvict: number;-}): number => {- const matching: [string, WorkspaceLocalCacheEntry<T>][] = [];-- for (const keyEntry of localCache) {- if (matches(keyEntry[0])) {- matching.push(keyEntry);- }- }-- if (matching.length <= maxEntries) {- return 0;- }-- matching.sort((a, b) => lastReadAtOf(a[1]) - lastReadAtOf(b[1]));-- const evictCount = Math.min(- matching.length,- Math.max(minEvict, matching.length - maxEntries),- );-- for (let index = 0; index < evictCount; index += 1) {- localCache.delete(matching[index][0]);- }-- return evictCount;-};-// Mutates the cache: expire versions idle past the TTL (dropping any entry left without a current// version), then trim each capped provider and the global total to budget by least-recently-read.// Returns the number of entries evicted.@@ -71,20 +35,21 @@ export const sweepLocalCache = <T>(}for (const [keyName, maxEntries] of config.maxEntriesByKeyName) {- evicted += evictLeastRecentlyRead({- localCache,- matches: (key) => key.startsWith(`${keyName}:`),+ evicted += evictLeastRecentlyUsed({+ map: localCache,maxEntries,- minEvict: 0,+ recencyOf: lastReadAtOf,+ matches: (key) => key.startsWith(`${keyName}:`),});}- evicted += evictLeastRecentlyRead({- localCache,- matches: () => true,- maxEntries: config.globalMaxEntries,- minEvict: config.minEvict,- });-- return evicted;+ return (+ evicted ++ evictLeastRecentlyUsed({+ map: localCache,+ maxEntries: config.globalMaxEntries,+ minEvict: config.minEvict,+ recencyOf: lastReadAtOf,+ })+ );};diff --git a/packages/twenty-server/src/modules/emailing/services/campaign-variable.service.ts b/packages/twenty-server/src/modules/emailing/services/campaign-variable.service.tsindex 0e30fc552ab..6eba8792ddd 100644--- a/packages/twenty-server/src/modules/emailing/services/campaign-variable.service.ts+++ b/packages/twenty-server/src/modules/emailing/services/campaign-variable.service.ts@@ -18,6 +18,7 @@ import { type FlatFieldMetadataMaps } from 'src/engine/metadata-modules/flat-fieimport { type FlatObjectMetadataMaps } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata-maps.type';import { WorkspaceManyOrAllFlatEntityMapsCacheService } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.service';import { type PersonWorkspaceEntity } from 'src/modules/person/standard-objects/person.workspace-entity';+import { readLruEntry, writeLruEntry } from 'src/utils/lru-map.util';export type PersonCampaignVariables = {definitions: CampaignVariableDefinition[];@@ -68,12 +69,12 @@ export class CampaignVariableService {(cacheKey) => hashes[cacheKey] ?? '',).join(':');- const cached = this.schemaByWorkspaceId.get(workspaceId);+ const cached = readLruEntry({+ map: this.schemaByWorkspaceId,+ key: workspaceId,+ });if (cached?.hash === hash) {- this.schemaByWorkspaceId.delete(workspaceId);- this.schemaByWorkspaceId.set(workspaceId, cached);-return cached.schema;}@@ -88,26 +89,16 @@ export class CampaignVariableService {fieldsByName: new Map(fields.map((field) => [field.name, field])),};- this.schemaByWorkspaceId.set(workspaceId, { hash, schema });- this.evictLeastRecentlyUsedSchemas();+ writeLruEntry({+ map: this.schemaByWorkspaceId,+ key: workspaceId,+ value: { hash, schema },+ maxEntries: MAX_CACHED_WORKSPACE_SCHEMAS,+ });return schema;}- private evictLeastRecentlyUsedSchemas(): void {- while (this.schemaByWorkspaceId.size > MAX_CACHED_WORKSPACE_SCHEMAS) {- const leastRecentlyUsedWorkspaceId = this.schemaByWorkspaceId- .keys()- .next().value;-- if (!isDefined(leastRecentlyUsedWorkspaceId)) {- return;- }-- this.schemaByWorkspaceId.delete(leastRecentlyUsedWorkspaceId);- }- }-async assertKnownVariables(workspaceId: string,usedVariableNames: Iterable<string>,diff --git a/packages/twenty-server/src/utils/__tests__/lru-map.util.spec.ts b/packages/twenty-server/src/utils/__tests__/lru-map.util.spec.tsindex fd824752291..2999247eb74 100644--- a/packages/twenty-server/src/utils/__tests__/lru-map.util.spec.ts+++ b/packages/twenty-server/src/utils/__tests__/lru-map.util.spec.ts@@ -1,4 +1,8 @@-import { readLruEntry, writeLruEntry } from 'src/utils/lru-map.util';+import {+ evictLeastRecentlyUsed,+ readLruEntry,+ writeLruEntry,+} from 'src/utils/lru-map.util';describe('readLruEntry', () => {it('returns undefined for a missing key', () => {@@ -52,3 +56,128 @@ describe('writeLruEntry', () => {expect(map.get('a')).toBe(2);});});++describe('evictLeastRecentlyUsed', () => {+ const mapOf = (...keys: string[]) =>+ new Map(keys.map((key, index) => [key, index]));++ it('returns 0 and mutates nothing at or under the cap', () => {+ const map = mapOf('a', 'b', 'c');++ expect(evictLeastRecentlyUsed({ map, maxEntries: 3 })).toBe(0);+ expect([...map.keys()]).toEqual(['a', 'b', 'c']);+ });++ it('evicts from the front in insertion-order mode', () => {+ const map = mapOf('a', 'b', 'c', 'd');++ expect(evictLeastRecentlyUsed({ map, maxEntries: 2 })).toBe(2);+ expect([...map.keys()]).toEqual(['c', 'd']);+ });++ it('spares a key refreshed by readLruEntry', () => {+ const map = mapOf('a', 'b', 'c');++ readLruEntry({ map, key: 'a' });+ evictLeastRecentlyUsed({ map, maxEntries: 2 });++ expect([...map.keys()]).toEqual(['c', 'a']);+ });++ it('evicts the lowest recency regardless of insertion order', () => {+ const map = new Map([+ ['a', { lastReadAt: 30 }],+ ['b', { lastReadAt: 10 }],+ ['c', { lastReadAt: 20 }],+ ]);++ const evicted = evictLeastRecentlyUsed({+ map,+ maxEntries: 2,+ recencyOf: (value) => value.lastReadAt,+ });++ expect(evicted).toBe(1);+ expect([...map.keys()]).toEqual(['a', 'c']);+ });++ it('scopes counting and eviction to matching keys', () => {+ const map = mapOf('x:1', 'x:2', 'x:3', 'y:1', 'y:2');++ const evicted = evictLeastRecentlyUsed({+ map,+ maxEntries: 2,+ matches: (key) => key.startsWith('x:'),+ });++ expect(evicted).toBe(1);+ expect([...map.keys()]).toEqual(['x:2', 'x:3', 'y:1', 'y:2']);+ });++ it('evicts a whole batch of minEvict once over cap', () => {+ const map = mapOf('a', 'b', 'c', 'd', 'e', 'f');++ expect(evictLeastRecentlyUsed({ map, maxEntries: 5, minEvict: 4 })).toBe(4);+ expect([...map.keys()]).toEqual(['e', 'f']);+ });++ it('never deletes more entries than exist, and reports the true count', () => {+ const map = mapOf('a', 'b', 'c');++ expect(evictLeastRecentlyUsed({ map, maxEntries: 1, minEvict: 99 })).toBe(+ 3,+ );+ expect(map.size).toBe(0);+ });++ it('omitting recencyOf matches supplying one that follows insertion order', () => {+ const implied = mapOf('a', 'b', 'c', 'd', 'e');+ const explicit = new Map(+ ['a', 'b', 'c', 'd', 'e'].map((key, index) => [key, { at: index }]),+ );++ const impliedEvicted = evictLeastRecentlyUsed({+ map: implied,+ maxEntries: 4,+ minEvict: 3,+ });+ const explicitEvicted = evictLeastRecentlyUsed({+ map: explicit,+ maxEntries: 4,+ minEvict: 3,+ recencyOf: (value) => value.at,+ });++ expect(impliedEvicted).toBe(explicitEvicted);+ expect([...implied.keys()]).toEqual([...explicit.keys()]);+ });++ // CoreEntityCacheService.evictLRUEntriesIfNeeded is not migrated yet; this+ // pins that the primitive already expresses it, so the follow-up is a call+ // swap rather than a redesign.+ it('expresses the core entity cache shape: timestamp recency with a batch floor', () => {+ const map = new Map(+ Array.from({ length: 10 }, (_, index) => [+ `key-${index}`,+ { lastHashCheckedAt: index },+ ]),+ );++ const evicted = evictLeastRecentlyUsed({+ map,+ maxEntries: 8,+ minEvict: 4,+ recencyOf: (value) => value.lastHashCheckedAt,+ });++ expect(evicted).toBe(4);+ expect([...map.keys()]).toEqual([+ 'key-4',+ 'key-5',+ 'key-6',+ 'key-7',+ 'key-8',+ 'key-9',+ ]);+ });+});diff --git a/packages/twenty-server/src/utils/lru-map.util.ts b/packages/twenty-server/src/utils/lru-map.util.tsindex 2827e6260f0..5ab9e87d6a8 100644--- a/packages/twenty-server/src/utils/lru-map.util.ts+++ b/packages/twenty-server/src/utils/lru-map.util.ts@@ -1,3 +1,5 @@+import { isDefined } from 'twenty-shared/utils';+export const readLruEntry = <Key, Value>({map,key,@@ -17,6 +19,56 @@ export const readLruEntry = <Key, Value>({return value;};+// Insertion-order LRU and timestamp LRU differ only in where the rank comes+// from, so both go through here rather than each keeping its own eviction loop.+export const evictLeastRecentlyUsed = <Key, Value>({+ map,+ maxEntries,+ minEvict = 0,+ recencyOf,+ matches,+}: {+ map: Map<Key, Value>;+ maxEntries: number;+ // Evict at least this many once over cap, so a periodic sweep drops a batch+ // instead of trimming one entry per call. Defaults to the exact overflow.+ minEvict?: number;+ // Higher = more recently used. Omit when recency is the map's own insertion+ // order, which readLruEntry and writeLruEntry maintain by re-inserting: with+ // no sort, candidates stay in map order and the oldest are evicted first.+ recencyOf?: (value: Value) => number;+ // Restricts the cap to a subset: non-matching entries neither count towards+ // maxEntries nor get evicted. Omit to apply to the whole map.+ matches?: (key: Key) => boolean;+}): number => {+ const candidates: [Key, Value][] = [];++ for (const keyEntry of map) {+ if (!isDefined(matches) || matches(keyEntry[0])) {+ candidates.push(keyEntry);+ }+ }++ if (candidates.length <= maxEntries) {+ return 0;+ }++ if (isDefined(recencyOf)) {+ candidates.sort((a, b) => recencyOf(a[1]) - recencyOf(b[1]));+ }++ const evictCount = Math.min(+ candidates.length,+ Math.max(minEvict, candidates.length - maxEntries),+ );++ for (let index = 0; index < evictCount; index += 1) {+ map.delete(candidates[index][0]);+ }++ return evictCount;+};+export const writeLruEntry = <Key, Value>({map,key,@@ -31,13 +83,5 @@ export const writeLruEntry = <Key, Value>({map.delete(key);map.set(key, value);- while (map.size > maxEntries) {- const leastRecentlyUsed = map.keys().next();-- if (leastRecentlyUsed.done) {- return;- }-- map.delete(leastRecentlyUsed.value);- }+ evictLeastRecentlyUsed({ map, maxEntries });};