The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
feat(server): eliminate v1 ORM from workspace write transactions on the flag (#24182)
Charles Bochete81a664e8267
diff --git a/packages/twenty-server/src/engine/core-modules/search/services/search.service.ts b/packages/twenty-server/src/engine/core-modules/search/services/search.service.tsindex 037208a096f..f9327edc4b5 100644--- a/packages/twenty-server/src/engine/core-modules/search/services/search.service.ts+++ b/packages/twenty-server/src/engine/core-modules/search/services/search.service.ts@@ -51,6 +51,7 @@ import { GlobalWorkspaceOrmManager } from 'src/engine/twenty-orm/global-workspacimport { type WorkspaceRepository } from 'src/engine/twenty-orm/repository/workspace.repository';import { getWorkspaceContext } from 'src/engine/twenty-orm/storage/orm-workspace-context.storage';import { resolveRolePermissionConfig } from 'src/engine/twenty-orm/utils/resolve-role-permission-config.util';+import { type RolePermissionConfig } from 'src/engine/twenty-orm/types/role-permission-config';type LastRanks = { tsRankCD: number; tsRank: number };@@ -124,6 +125,7 @@ export class SearchService {objectMetadataItem: flatObjectMetadata,records: await this.buildSearchQueryAndGetRecordsWithFallback({entityManager: repository,+ rolePermissionConfig,flatObjectMetadata,flatFieldMetadataMaps,searchInput,@@ -199,6 +201,7 @@ export class SearchService {Entity extends ObjectLiteral,>({entityManager,+ rolePermissionConfig,flatObjectMetadata,flatFieldMetadataMaps,searchInput,@@ -209,6 +212,7 @@ export class SearchService {after,}: {entityManager: WorkspaceRepository<Entity>;+ rolePermissionConfig?: RolePermissionConfig;flatObjectMetadata: FlatObjectMetadata;flatFieldMetadataMaps: FlatEntityMaps<FlatFieldMetadata>;searchInput: string;@@ -239,6 +243,7 @@ export class SearchService {const fallbackResults = await this.buildIlikeFallbackQuery({entityManager,+ rolePermissionConfig,flatObjectMetadata,flatFieldMetadataMaps,searchInput,@@ -268,7 +273,9 @@ export class SearchService {filter: ObjectRecordFilterInput;after?: string;}) {- const queryBuilder = entityManager.createQueryBuilder();+ const queryBuilder = entityManager.createQueryBuilder(+ flatObjectMetadata.nameSingular,+ );const { flatObjectMetadataMaps } = entityManager.internalContext;@@ -298,7 +305,7 @@ export class SearchService {flatFieldMetadataMaps,),...imageIdentifierColumns,- ].map((field) => `"${field}"`);+ ];const tsRankCDExpr = `ts_rank_cd("${SEARCH_VECTOR_FIELD.name}", to_tsquery('simple', public.unaccent_immutable(:searchTerms)))`;@@ -311,8 +318,21 @@ export class SearchService {tsRankCDExpr,});+ const [firstField, ...remainingFields] = fieldsToSelect;++ queryBuilder.select(+ `"${flatObjectMetadata.nameSingular}"."${firstField}"`,+ firstField,+ );++ for (const field of remainingFields) {+ queryBuilder.addSelect(+ `"${flatObjectMetadata.nameSingular}"."${field}"`,+ field,+ );+ }+queryBuilder- .select(fieldsToSelect).addSelect(tsRankCDExpr, 'tsRankCD').addSelect(tsRankExpr, 'tsRank');@@ -352,6 +372,7 @@ export class SearchService {private async buildIlikeFallbackQuery<Entity extends ObjectLiteral>({entityManager,+ rolePermissionConfig,flatObjectMetadata,flatFieldMetadataMaps,searchInput,@@ -359,6 +380,7 @@ export class SearchService {filter,}: {entityManager: WorkspaceRepository<Entity>;+ rolePermissionConfig?: RolePermissionConfig;flatObjectMetadata: FlatObjectMetadata;flatFieldMetadataMaps: FlatEntityMaps<FlatFieldMetadata>;searchInput: string;@@ -369,30 +391,24 @@ export class SearchService {'SEARCH_ILIKE_FALLBACK_TIMEOUT_MS',);- // Must not run inside a caller transaction: SET LOCAL is transaction-scoped- // and would leak into the outer transaction.try {- return await entityManager.manager.transaction(- async (transactionManager) => {- const { queryRunner } = transactionManager;-- if (!isDefined(queryRunner)) {- throw new Error(- 'Expected queryRunner to be defined within transaction',- );- }-- await queryRunner.query(+ return await this.globalWorkspaceOrmManager.runInWorkspaceTransaction(+ async (transactionScope) => {+ await transactionScope.executeRawQuery(`SELECT set_config('statement_timeout', $1, true)`,[String(timeoutMs)],);- const queryBuilder = entityManager.createQueryBuilder(- undefined,- queryRunner,+ const repository = transactionScope.getRepository<Entity>(+ flatObjectMetadata.nameSingular,+ rolePermissionConfig,+ );++ const queryBuilder = repository.createQueryBuilder(+ flatObjectMetadata.nameSingular,);- const { flatObjectMetadataMaps } = entityManager.internalContext;+ const { flatObjectMetadataMaps } = repository.internalContext;const queryParser = new GraphqlQueryParser(flatObjectMetadata,@@ -420,9 +436,21 @@ export class SearchService {flatFieldMetadataMaps,),...imageIdentifierColumns,- ].map((field) => `"${field}"`);+ ];- queryBuilder.select(fieldsToSelect);+ const [firstField, ...remainingFields] = fieldsToSelect;++ queryBuilder.select(+ `"${flatObjectMetadata.nameSingular}"."${firstField}"`,+ firstField,+ );++ for (const field of remainingFields) {+ queryBuilder.addSelect(+ `"${flatObjectMetadata.nameSingular}"."${field}"`,+ field,+ );+ }const searchWords = searchInput.trim()@@ -439,7 +467,7 @@ export class SearchService {});const rawResults = await queryBuilder- .orderBy('"id"', 'ASC')+ .orderBy(`"${flatObjectMetadata.nameSingular}"."id"`, 'ASC').take(limit).getRawMany();diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-version-core-sync.service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-version-core-sync.service.tsindex f0d09f3955d..c8f06d85a82 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-version-core-sync.service.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-version-core-sync.service.ts@@ -12,8 +12,8 @@ import {WorkflowVersionStatus,} from 'src/engine/core-modules/workflow/entities/workflow-version.entity';import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';-import { type WorkspaceEntityManager } from 'src/engine/twenty-orm/entity-manager/workspace-entity-manager';import { GlobalWorkspaceOrmManager } from 'src/engine/twenty-orm/global-workspace-datasource/global-workspace-orm.manager';+import { type WorkspaceTransactionScope } from 'src/engine/twenty-orm/global-workspace-datasource/types/workspace-transaction-scope.type';import { WorkspaceRepository } from 'src/engine/twenty-orm/repository/workspace.repository';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';@@ -111,12 +111,12 @@ export class WorkflowVersionCoreSyncService {async mirrorWorkflowVersionWrite({workspaceId,- entityManager,+ transactionScope,workflowVersion,applicationId,}: {workspaceId: string;- entityManager: WorkspaceEntityManager;+ transactionScope: WorkspaceTransactionScope;workflowVersion: WorkflowVersionWorkspaceEntity;applicationId?: string;}): Promise<{ coreWorkflowVersionId: string } | null> {@@ -138,15 +138,7 @@ export class WorkflowVersionCoreSyncService {? workflowVersion.coreWorkflowVersionId: uuidv4();- const queryRunner = entityManager.queryRunner;-- if (!isDefined(queryRunner)) {- throw new Error(- 'Transactional core mirror requires a transaction-scoped entity manager',- );- }-- await queryRunner.query(+ await transactionScope.executeRawQuery(`INSERT INTO core."workflowVersion"("id", "workspaceId", "workflowId", "triggers", "steps", "status", "universalIdentifier", "applicationId")VALUES ($1, $2, $3, $4, $5, $6, $7, $8)@@ -171,11 +163,10 @@ export class WorkflowVersionCoreSyncService {);if (isNewLink) {- await this.writeBackCoreVersionIdOnManager(- workspaceId,+ await this.writeBackCoreVersionIdInTransaction(workflowVersion.id,coreWorkflowVersionId,- entityManager,+ transactionScope,);}@@ -184,11 +175,11 @@ export class WorkflowVersionCoreSyncService {async mirrorWorkflowVersionWrites({workspaceId,- entityManager,+ transactionScope,workflowVersions,}: {workspaceId: string;- entityManager: WorkspaceEntityManager;+ transactionScope: WorkspaceTransactionScope;workflowVersions: WorkflowVersionWorkspaceEntity[];}): Promise<Map<string, string>> {const coreIdByWorkspaceRecordId = new Map<string, string>();@@ -202,7 +193,7 @@ export class WorkflowVersionCoreSyncService {for (const workflowVersion of workflowVersions) {const result = await this.mirrorWorkflowVersionWrite({workspaceId,- entityManager,+ transactionScope,workflowVersion,applicationId,});@@ -222,53 +213,36 @@ export class WorkflowVersionCoreSyncService {workspaceId: string,write: (workflowVersionRepository: WorkspaceRepository<WorkflowVersionWorkspaceEntity>,- entityManager: WorkspaceEntityManager,+ transactionScope: WorkspaceTransactionScope,) => Promise<string>,): Promise<void> {await this.globalWorkspaceOrmManager.executeInWorkspaceContext(async () => {- const workflowVersionRepository =- await this.globalWorkspaceOrmManager.getV1Repository<WorkflowVersionWorkspaceEntity>(- workspaceId,- 'workflowVersion',- { shouldBypassPermissionChecks: true },- );-- const dataSource =- await this.globalWorkspaceOrmManager.getGlobalWorkspaceDataSourceWithEntityMetadatas();- const queryRunner = dataSource.createQueryRunner();-- await queryRunner.connect();- await queryRunner.startTransaction();-- try {- const workflowVersionId = await write(- workflowVersionRepository,- queryRunner.manager,- );+ await this.globalWorkspaceOrmManager.runInWorkspaceTransaction(+ async (transactionScope) => {+ const workflowVersionRepository =+ transactionScope.getRepository<WorkflowVersionWorkspaceEntity>(+ 'workflowVersion',+ { shouldBypassPermissionChecks: true },+ );- const workflowVersion = await workflowVersionRepository.findOne(- { where: { id: workflowVersionId } },- queryRunner.manager,- );+ const workflowVersionId = await write(+ workflowVersionRepository,+ transactionScope,+ );- if (isDefined(workflowVersion)) {- await this.mirrorWorkflowVersionWrite({- workspaceId,- entityManager: queryRunner.manager,- workflowVersion,+ const workflowVersion = await workflowVersionRepository.findOne({+ where: { id: workflowVersionId },});- }-- await queryRunner.commitTransaction();- } catch (error) {- if (queryRunner.isTransactionActive) {- await queryRunner.rollbackTransaction();- }- throw error;- } finally {- await queryRunner.release();- }+ if (isDefined(workflowVersion)) {+ await this.mirrorWorkflowVersionWrite({+ workspaceId,+ transactionScope,+ workflowVersion,+ });+ }+ },+ );}, buildSystemAuthContext(workspaceId));await this.invalidateAutomatedTriggerMaps(workspaceId);@@ -301,7 +275,7 @@ export class WorkflowVersionCoreSyncService {await this.globalWorkspaceOrmManager.executeInWorkspaceContext(async () => {const workflowVersionRepository =- await this.globalWorkspaceOrmManager.getV1Repository<WorkflowVersionWorkspaceEntity>(+ await this.globalWorkspaceOrmManager.getRepository<WorkflowVersionWorkspaceEntity>(workspaceId,'workflowVersion',{ shouldBypassPermissionChecks: true },@@ -328,7 +302,7 @@ export class WorkflowVersionCoreSyncService {): Promise<void> {await this.globalWorkspaceOrmManager.executeInWorkspaceContext(async () => {const workflowVersionRepository =- await this.globalWorkspaceOrmManager.getV1Repository<WorkflowVersionWorkspaceEntity>(+ await this.globalWorkspaceOrmManager.getRepository<WorkflowVersionWorkspaceEntity>(workspaceId,'workflowVersion',{ shouldBypassPermissionChecks: true },@@ -360,7 +334,7 @@ export class WorkflowVersionCoreSyncService {await this.globalWorkspaceOrmManager.executeInWorkspaceContext(async () => {const workspaceWorkflowVersionRepository =- await this.globalWorkspaceOrmManager.getV1Repository<WorkflowVersionWorkspaceEntity>(+ await this.globalWorkspaceOrmManager.getRepository<WorkflowVersionWorkspaceEntity>(workspaceId,'workflowVersion',{ shouldBypassPermissionChecks: true },@@ -377,15 +351,13 @@ export class WorkflowVersionCoreSyncService {}, buildSystemAuthContext(workspaceId));}- private async writeBackCoreVersionIdOnManager(- workspaceId: string,+ private async writeBackCoreVersionIdInTransaction(workflowVersionId: string,coreWorkflowVersionId: string,- entityManager: WorkspaceEntityManager,+ transactionScope: WorkspaceTransactionScope,): Promise<void> {const workspaceWorkflowVersionRepository =- await this.globalWorkspaceOrmManager.getV1Repository<WorkflowVersionWorkspaceEntity>(- workspaceId,+ transactionScope.getRepository<WorkflowVersionWorkspaceEntity>('workflowVersion',{ shouldBypassPermissionChecks: true },);@@ -393,8 +365,6 @@ export class WorkflowVersionCoreSyncService {await workspaceWorkflowVersionRepository.update({ id: workflowVersionId },{ coreWorkflowVersionId },- undefined,- entityManager,);}diff --git a/packages/twenty-server/src/engine/twenty-orm-v2/datasource/workspace-data-source-v2.ts b/packages/twenty-server/src/engine/twenty-orm-v2/datasource/workspace-data-source-v2.tsindex 5b84ddfb9ab..5794c3b8630 100644--- a/packages/twenty-server/src/engine/twenty-orm-v2/datasource/workspace-data-source-v2.ts+++ b/packages/twenty-server/src/engine/twenty-orm-v2/datasource/workspace-data-source-v2.ts@@ -30,6 +30,10 @@ export type WorkspaceTransactionScopeV2 = {nameSingular: string,rolePermissionConfig?: RolePermissionConfig,) => WorkspaceRepositoryV2;+ executeRawQuery: (+ sql: string,+ parameters?: unknown[],+ ) => Promise<Record<string, unknown>[]>;};export class WorkspaceDataSourceV2 {@@ -78,6 +82,8 @@ export class WorkspaceDataSourceV2 {executor,isTransactional: true,}),+ executeRawQuery: (sql, parameters = []) =>+ executor.execute({ text: sql, values: parameters }),}),);}diff --git a/packages/twenty-server/src/engine/twenty-orm-v2/query-builder/workspace-select-query-builder-v2.ts b/packages/twenty-server/src/engine/twenty-orm-v2/query-builder/workspace-select-query-builder-v2.tsindex d38c3bb286a..8f707c6e29a 100644--- a/packages/twenty-server/src/engine/twenty-orm-v2/query-builder/workspace-select-query-builder-v2.ts+++ b/packages/twenty-server/src/engine/twenty-orm-v2/query-builder/workspace-select-query-builder-v2.ts@@ -1,5 +1,5 @@import { type ObjectsPermissions } from 'twenty-shared/types';-import { isDefined } from 'twenty-shared/utils';+import { isDefined, pascalCase } from 'twenty-shared/utils';import { FindOperator } from 'typeorm';import { RelationType } from 'src/engine/metadata-modules/field-metadata/interfaces/relation-type.interface';@@ -611,20 +611,62 @@ export class WorkspaceSelectQueryBuilderV2 implements WhereExpressionLike {const parameters: Record<string, unknown> = {};for (const [columnName, value] of Object.entries(where)) {- if (!isDefined(this.tableShape.columnShapeByColumnName[columnName])) {- throw new TwentyOrmV2Exception(- `Column "${columnName}" does not exist on "${this.tableShape.nameSingular}"`,- TwentyOrmV2ExceptionCode.UNKNOWN_COLUMN,+ if (isDefined(this.tableShape.columnShapeByColumnName[columnName])) {+ conditions.push(+ this.buildValueCondition(+ quoteColumn(this.alias, columnName),+ columnName,+ value,+ parameters,+ ),);++ continue;}- conditions.push(- this.buildValueCondition(- quoteColumn(this.alias, columnName),- columnName,- value,- parameters,- ),+ const hasCompositeChildColumns = Object.values(+ this.tableShape.columnShapeByColumnName,+ ).some((shape) => shape.compositeParentFieldName === columnName);++ if (+ hasCompositeChildColumns &&+ isDefined(value) &&+ typeof value === 'object' &&+ !(value instanceof FindOperator) &&+ !Array.isArray(value)+ ) {+ for (const [subFieldName, subValue] of Object.entries(+ value as Record<string, unknown>,+ )) {+ const compositeColumnName = `${columnName}${pascalCase(subFieldName)}`;++ if (+ !isDefined(+ this.tableShape.columnShapeByColumnName[compositeColumnName],+ )+ ) {+ throw new TwentyOrmV2Exception(+ `Column "${compositeColumnName}" does not exist on "${this.tableShape.nameSingular}"`,+ TwentyOrmV2ExceptionCode.UNKNOWN_COLUMN,+ );+ }++ conditions.push(+ this.buildValueCondition(+ quoteColumn(this.alias, compositeColumnName),+ compositeColumnName,+ subValue,+ parameters,+ ),+ );+ }++ continue;+ }++ throw new TwentyOrmV2Exception(+ `Column "${columnName}" does not exist on "${this.tableShape.nameSingular}"`,+ TwentyOrmV2ExceptionCode.UNKNOWN_COLUMN,);}@@ -704,11 +746,19 @@ export class WorkspaceSelectQueryBuilderV2 implements WhereExpressionLike {.join(separator)})`;}case 'raw': {- const rawValue = value.value as- | string- | ((columnAlias: string) => string);- const rawSql =- typeof rawValue === 'function' ? rawValue(quotedColumn) : rawValue;+ const rawValue = value.value as unknown;++ let rawSql: string;++ if (typeof rawValue === 'function') {+ rawSql = (rawValue as (columnAlias: string) => string)(+ quotedColumn,+ );+ } else if (typeof rawValue === 'string') {+ rawSql = rawValue;+ } else {+ rawSql = value.getSql?.(quotedColumn) ?? '';+ }Object.assign(parameters, value.objectLiteralParameters ?? {});diff --git a/packages/twenty-server/src/engine/twenty-orm-v2/repository/workspace-repository-v2.ts b/packages/twenty-server/src/engine/twenty-orm-v2/repository/workspace-repository-v2.tsindex f3432cc3c3f..170336c9ca2 100644--- a/packages/twenty-server/src/engine/twenty-orm-v2/repository/workspace-repository-v2.ts+++ b/packages/twenty-server/src/engine/twenty-orm-v2/repository/workspace-repository-v2.ts@@ -159,6 +159,10 @@ export class WorkspaceRepositoryV2 {return this.options.internalContext;}+ get internalContext(): WorkspaceInternalContext {+ return this.options.internalContext;+ }+async find(options?: FindOptionsV2): Promise<ObjectRecord[]> {const records = await applyFindOptionsToQueryBuilder(this.createQueryBuilder(),@@ -486,7 +490,9 @@ export class WorkspaceRepositoryV2 {const { identifiers, generatedMaps, raw } = await this.runInsert({records,- columnsToReturn: ['id'],+ columnsToReturn: this.options.shouldBypassPermissionChecks+ ? Object.keys(this.options.tableShape.columnShapeByColumnName)+ : ['id'],});const insertResult = new InsertResult();diff --git a/packages/twenty-server/src/engine/twenty-orm/global-workspace-datasource/global-workspace-orm.manager.ts b/packages/twenty-server/src/engine/twenty-orm/global-workspace-datasource/global-workspace-orm.manager.tsindex d96d36078eb..b79abd86127 100644--- a/packages/twenty-server/src/engine/twenty-orm/global-workspace-datasource/global-workspace-orm.manager.ts+++ b/packages/twenty-server/src/engine/twenty-orm/global-workspace-datasource/global-workspace-orm.manager.ts@@ -1,6 +1,7 @@import { Injectable, type Type } from '@nestjs/common';import { FeatureFlagKey } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';import { type ObjectLiteral } from 'typeorm';import { getWorkspaceAuthContext } from 'src/engine/core-modules/auth/storage/workspace-auth-context.storage';@@ -9,6 +10,7 @@ import { buildObjectIdByNameMaps } from 'src/engine/metadata-modules/flat-objectimport { GlobalWorkspaceDataSource } from 'src/engine/twenty-orm/global-workspace-datasource/global-workspace-datasource';import { GlobalWorkspaceDataSourceService } from 'src/engine/twenty-orm/global-workspace-datasource/global-workspace-datasource.service';import { ExecuteInWorkspaceContextOptions } from 'src/engine/twenty-orm/global-workspace-datasource/types/execute-in-workspace-context-options.type';+import { type WorkspaceTransactionScope } from 'src/engine/twenty-orm/global-workspace-datasource/types/workspace-transaction-scope.type';import type { WorkspaceRepository } from 'src/engine/twenty-orm/repository/workspace.repository';import {getWorkspaceContext,@@ -49,11 +51,7 @@ export class GlobalWorkspaceOrmManager {workspaceEntityOrObjectMetadataName,);- if (- getWorkspaceContext().featureFlagsMap[- FeatureFlagKey.IS_ORM_V2_READ_PATH_ENABLED- ]- ) {+ if (await this.isOrmV2ReadPathEnabled()) {return this.workspaceDataSourceV2Service.getDataSource({ useReplica: false }).getRepository(@@ -106,47 +104,85 @@ export class GlobalWorkspaceOrmManager {);}- async getV1Repository<T extends ObjectLiteral>(- workspaceId: string,- workspaceEntity: Type<T>,- permissionOptions?: RolePermissionConfig,- ): Promise<WorkspaceRepository<T>>;+ private async isOrmV2ReadPathEnabled(): Promise<boolean> {+ const context = getWorkspaceContext();+ const contextFlag =+ context.featureFlagsMap[FeatureFlagKey.IS_ORM_V2_READ_PATH_ENABLED];- async getV1Repository<T extends ObjectLiteral>(- workspaceId: string,- objectMetadataName: string,- permissionOptions?: RolePermissionConfig,- ): Promise<WorkspaceRepository<T>>;+ if (isDefined(contextFlag)) {+ return contextFlag;+ }- async getV1Repository<T extends ObjectLiteral>(- _workspaceId: string,- workspaceEntityOrObjectMetadataName: Type<T> | string,- permissionOptions?: RolePermissionConfig,- ): Promise<WorkspaceRepository<T>> {- const objectMetadataName = this.resolveObjectMetadataName(- workspaceEntityOrObjectMetadataName,+ const { featureFlagsMap } = await this.workspaceCacheService.getOrRecompute(+ context.authContext.workspace.id,+ ['featureFlagsMap'],);- await this.ensureEntityMetadatasLoaded();-- const globalDataSource = await this.getGlobalWorkspaceDataSource();-- return globalDataSource.getRepository<T>(- objectMetadataName,- permissionOptions,- );+ return featureFlagsMap[FeatureFlagKey.IS_ORM_V2_READ_PATH_ENABLED] ?? false;}- async getGlobalWorkspaceDataSourceWithEntityMetadatas(): Promise<GlobalWorkspaceDataSource> {- await this.ensureEntityMetadatasLoaded();-- return this.getGlobalWorkspaceDataSource();- }+ async runInWorkspaceTransaction<T>(+ work: (transactionScope: WorkspaceTransactionScope) => Promise<T>,+ ): Promise<T> {+ if (await this.isOrmV2ReadPathEnabled()) {+ return this.workspaceDataSourceV2Service+ .getDataSource({ useReplica: false })+ .transaction((transactionScope) =>+ work({+ getRepository: <Entity extends ObjectLiteral>(+ objectMetadataName: string,+ rolePermissionConfig?: RolePermissionConfig,+ ): WorkspaceRepository<Entity> =>+ transactionScope.getRepository(+ objectMetadataName,+ rolePermissionConfig,+ ) as unknown as WorkspaceRepository<Entity>,+ executeRawQuery: (sql, parameters) =>+ transactionScope.executeRawQuery(sql, parameters),+ }),+ );+ }- async getGlobalWorkspaceDataSourceReplicaWithEntityMetadatas(): Promise<GlobalWorkspaceDataSource> {await this.ensureEntityMetadatasLoaded();- return this.getGlobalWorkspaceDataSourceReplica();+ const { authContext } = getWorkspaceContext();+ const globalDataSource = await this.getGlobalWorkspaceDataSource();+ const queryRunner = globalDataSource.createQueryRunner();++ try {+ await queryRunner.connect();+ await queryRunner.startTransaction();++ try {+ const result = await work({+ getRepository: <Entity extends ObjectLiteral>(+ objectMetadataName: string,+ rolePermissionConfig?: RolePermissionConfig,+ ): WorkspaceRepository<Entity> =>+ queryRunner.manager.getRepository<Entity>(+ objectMetadataName,+ rolePermissionConfig,+ authContext,+ ),+ executeRawQuery: (sql, parameters = []) =>+ queryRunner.query(sql, parameters) as Promise<+ Record<string, unknown>[]+ >,+ });++ await queryRunner.commitTransaction();++ return result;+ } catch (error) {+ if (queryRunner.isTransactionActive) {+ await queryRunner.rollbackTransaction();+ }++ throw error;+ }+ } finally {+ await queryRunner.release();+ }}async executeInWorkspaceContext<T>(@@ -223,15 +259,22 @@ export class GlobalWorkspaceOrmManager {): Promise<ORMWorkspaceContext> {const workspaceId = authContext.workspace.id;- const {- flatObjectMetadataMaps,- flatFieldMetadataMaps,- ORMEntityMetadatas: entityMetadatas,- } = await this.workspaceCacheService.getOrRecompute(workspaceId, [- 'flatObjectMetadataMaps',- 'flatFieldMetadataMaps',- 'ORMEntityMetadatas',- ]);+ const { flatObjectMetadataMaps, flatFieldMetadataMaps, featureFlagsMap } =+ await this.workspaceCacheService.getOrRecompute(workspaceId, [+ 'flatObjectMetadataMaps',+ 'flatFieldMetadataMaps',+ 'featureFlagsMap',+ ]);++ const entityMetadatas = featureFlagsMap[+ FeatureFlagKey.IS_ORM_V2_READ_PATH_ENABLED+ ]+ ? []+ : (+ await this.workspaceCacheService.getOrRecompute(workspaceId, [+ 'ORMEntityMetadatas',+ ])+ ).ORMEntityMetadatas;const { idByNameSingular: objectIdByNameSingular } =buildObjectIdByNameMaps(flatObjectMetadataMaps);diff --git a/packages/twenty-server/src/engine/twenty-orm/global-workspace-datasource/types/workspace-transaction-scope.type.ts b/packages/twenty-server/src/engine/twenty-orm/global-workspace-datasource/types/workspace-transaction-scope.type.tsnew file mode 100644index 00000000000..bad5a272b3a--- /dev/null+++ b/packages/twenty-server/src/engine/twenty-orm/global-workspace-datasource/types/workspace-transaction-scope.type.ts@@ -0,0 +1,15 @@+import { type ObjectLiteral } from 'typeorm';++import { type WorkspaceRepository } from 'src/engine/twenty-orm/repository/workspace.repository';+import { type RolePermissionConfig } from 'src/engine/twenty-orm/types/role-permission-config';++export type WorkspaceTransactionScope = {+ getRepository: <Entity extends ObjectLiteral>(+ objectMetadataName: string,+ rolePermissionConfig?: RolePermissionConfig,+ ) => WorkspaceRepository<Entity>;+ executeRawQuery: (+ sql: string,+ parameters?: unknown[],+ ) => Promise<Record<string, unknown>[]>;+};diff --git a/packages/twenty-server/src/modules/calendar/blocklist-manager/jobs/blocklist-item-delete-calendar-events.job.ts b/packages/twenty-server/src/modules/calendar/blocklist-manager/jobs/blocklist-item-delete-calendar-events.job.tsindex 7fb30dbbb42..c6441be3778 100644--- a/packages/twenty-server/src/modules/calendar/blocklist-manager/jobs/blocklist-item-delete-calendar-events.job.ts+++ b/packages/twenty-server/src/modules/calendar/blocklist-manager/jobs/blocklist-item-delete-calendar-events.job.ts@@ -1,21 +1,13 @@import { Scope } from '@nestjs/common';-import { InjectRepository } from '@nestjs/typeorm';import { type ObjectRecordCreateEvent } from 'twenty-shared/database-events';-import { isDefined } from 'twenty-shared/utils';-import { And, Any, ILike, In, Not, Or, type Repository } from 'typeorm';import { Process } from 'src/engine/core-modules/message-queue/decorators/process.decorator';import { Processor } from 'src/engine/core-modules/message-queue/decorators/processor.decorator';import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';-import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';-import { CalendarChannelEntity } from 'src/engine/metadata-modules/calendar-channel/entities/calendar-channel.entity';-import { GlobalWorkspaceOrmManager } from 'src/engine/twenty-orm/global-workspace-datasource/global-workspace-orm.manager';-import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';import { type WorkspaceEventBatch } from 'src/engine/workspace-event-emitter/types/workspace-event-batch.type';import { type BlocklistWorkspaceEntity } from 'src/modules/blocklist/standard-objects/blocklist.workspace-entity';import { CalendarEventCleanerService } from 'src/modules/calendar/calendar-event-cleaner/services/calendar-event-cleaner.service';-import { type CalendarChannelEventAssociationWorkspaceEntity } from 'src/modules/calendar/common/standard-objects/calendar-channel-event-association.workspace-entity';export type BlocklistItemDeleteCalendarEventsJobData = WorkspaceEventBatch<ObjectRecordCreateEvent<BlocklistWorkspaceEntity>@@ -27,163 +19,17 @@ export type BlocklistItemDeleteCalendarEventsJobData = WorkspaceEventBatch<})export class BlocklistItemDeleteCalendarEventsJob {constructor(- private readonly globalWorkspaceOrmManager: GlobalWorkspaceOrmManager,- @InjectRepository(CalendarChannelEntity)- private readonly calendarChannelRepository: Repository<CalendarChannelEntity>,- @InjectRepository(UserWorkspaceEntity)- private readonly userWorkspaceRepository: Repository<UserWorkspaceEntity>,private readonly calendarEventCleanerService: CalendarEventCleanerService,) {}@Process(BlocklistItemDeleteCalendarEventsJob.name)async handle(data: BlocklistItemDeleteCalendarEventsJobData): Promise<void> {- const workspaceId = data.workspaceId;-- const authContext = buildSystemAuthContext(workspaceId);-- await this.globalWorkspaceOrmManager.executeInWorkspaceContext(- async () => {- const blocklistItemIds = data.events.map(- (eventPayload) => eventPayload.recordId,- );-- const blocklistRepository =- await this.globalWorkspaceOrmManager.getRepository<BlocklistWorkspaceEntity>(- workspaceId,- 'blocklist',- );-- const blocklist = await blocklistRepository.find({- where: {- id: Any(blocklistItemIds),- },- });-- const handlesToDeleteByWorkspaceMemberIdMap = blocklist.reduce(- (acc, blocklistItem) => {- const { handle, workspaceMemberId } = blocklistItem;-- if (!acc.has(workspaceMemberId)) {- acc.set(workspaceMemberId, []);- }-- if (!isDefined(handle)) {- return acc;- }-- acc.get(workspaceMemberId)?.push(handle);-- return acc;- },- new Map<string, string[]>(),- );-- const calendarChannelEventAssociationRepository =- await this.globalWorkspaceOrmManager.getRepository<CalendarChannelEventAssociationWorkspaceEntity>(- workspaceId,- 'calendarChannelEventAssociation',- );-- const workspaceMemberRepository =- await this.globalWorkspaceOrmManager.getRepository(- workspaceId,- 'workspaceMember',- { shouldBypassPermissionChecks: true },- );-- for (const workspaceMemberId of handlesToDeleteByWorkspaceMemberIdMap.keys()) {- const handles =- handlesToDeleteByWorkspaceMemberIdMap.get(workspaceMemberId);-- if (!handles) {- continue;- }-- const workspaceMember = await workspaceMemberRepository.findOne({- where: { id: workspaceMemberId },- });-- if (!workspaceMember) {- continue;- }-- const userWorkspace = await this.userWorkspaceRepository.findOne({- where: { userId: workspaceMember.userId, workspaceId },- select: ['id'],- });-- if (!userWorkspace) {- continue;- }-- const calendarChannels = await this.calendarChannelRepository.find({- select: {- id: true,- handle: true,- connectedAccount: {- handleAliases: true,- },- },- where: {- connectedAccount: { userWorkspaceId: userWorkspace.id },- workspaceId,- },- relations: ['connectedAccount'],- });-- for (const calendarChannel of calendarChannels) {- const calendarChannelHandles = [calendarChannel.handle];-- if (calendarChannel.connectedAccount.handleAliases) {- const rawAliases = calendarChannel.connectedAccount- .handleAliases as string | string[];-- const aliasList = Array.isArray(rawAliases)- ? rawAliases- : rawAliases.split(',').map((alias: string) => alias.trim());-- calendarChannelHandles.push(...aliasList);- }-- const handleConditions = handles.map((handle) => {- const isHandleDomain = handle.startsWith('@');-- return isHandleDomain- ? {- handle: And(- Or(ILike(`%${handle}`), ILike(`%.${handle.slice(1)}`)),- Not(In(calendarChannelHandles)),- ),- }- : { handle };- });-- const calendarEventsAssociationsToDelete =- await calendarChannelEventAssociationRepository.find({- where: {- calendarChannelId: calendarChannel.id,- calendarEvent: {- calendarEventParticipants: handleConditions,- },- },- });-- if (calendarEventsAssociationsToDelete.length === 0) {- continue;- }-- await calendarChannelEventAssociationRepository.delete(- calendarEventsAssociationsToDelete.map(({ id }) => id),- );- }- }-- await this.calendarEventCleanerService.cleanWorkspaceCalendarEvents(- workspaceId,- );- },- authContext,- { lite: true },+ // Blocking a handle deletes their messages but deliberately leaves calendar+ // events alone: an event the blocked handle merely attended is still the+ // workspace's own meeting, so it is not swept up with them. We only clean up+ // events that were orphaned by other means.+ await this.calendarEventCleanerService.cleanWorkspaceCalendarEvents(+ data.workspaceId,);}}diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-cleaner/services/calendar-event-cleaner.service.ts b/packages/twenty-server/src/modules/calendar/calendar-event-cleaner/services/calendar-event-cleaner.service.tsindex a5bfd04a2d7..595487848fd 100644--- a/packages/twenty-server/src/modules/calendar/calendar-event-cleaner/services/calendar-event-cleaner.service.ts+++ b/packages/twenty-server/src/modules/calendar/calendar-event-cleaner/services/calendar-event-cleaner.service.ts@@ -1,11 +1,14 @@import { Injectable, Logger } from '@nestjs/common';-import { Any, IsNull } from 'typeorm';+import { isDefined } from 'twenty-shared/utils';+import { In, MoreThan } from 'typeorm';-import { type WorkspaceEntityManager } from 'src/engine/twenty-orm/entity-manager/workspace-entity-manager';import { GlobalWorkspaceOrmManager } from 'src/engine/twenty-orm/global-workspace-datasource/global-workspace-orm.manager';import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';-import { deleteUsingPagination } from 'src/modules/messaging/message-cleaner/utils/delete-using-pagination.util';+import { type CalendarChannelEventAssociationWorkspaceEntity } from 'src/modules/calendar/common/standard-objects/calendar-channel-event-association.workspace-entity';+import { type CalendarEventWorkspaceEntity } from 'src/modules/calendar/common/standard-objects/calendar-event.workspace-entity';++const CALENDAR_CLEANUP_PAGE_SIZE = 500;@Injectable()export class CalendarEventCleanerService {@@ -26,55 +29,35 @@ export class CalendarEventCleanerService {await this.globalWorkspaceOrmManager.executeInWorkspaceContext(async () => {- const calendarChannelEventAssociationRepository =- await this.globalWorkspaceOrmManager.getV1Repository(- workspaceId,- 'calendarChannelEventAssociation',- );-- const workspaceDataSource =- await this.globalWorkspaceOrmManager.getGlobalWorkspaceDataSourceWithEntityMetadatas();-- await workspaceDataSource.transaction(async (manager) => {- const transactionManager = manager as WorkspaceEntityManager;-- await deleteUsingPagination(- workspaceId,- 500,- async (- limit: number,- offset: number,- _workspaceId: string,- transactionManager?: WorkspaceEntityManager,- ) => {+ await this.globalWorkspaceOrmManager.runInWorkspaceTransaction(+ async (transactionScope) => {+ const calendarChannelEventAssociationRepository =+ transactionScope.getRepository<CalendarChannelEventAssociationWorkspaceEntity>(+ 'calendarChannelEventAssociation',+ );++ for (;;) {const associations =- await calendarChannelEventAssociationRepository.find(- {- where: { calendarChannelId },- take: limit,- skip: offset,- },- transactionManager,- );-- return associations.map(({ id }) => id);- },- async (- ids: string[],- workspaceId: string,- transactionManager?: WorkspaceEntityManager,- ) => {+ await calendarChannelEventAssociationRepository.find({+ where: { calendarChannelId },+ take: CALENDAR_CLEANUP_PAGE_SIZE,+ select: { id: true },+ });++ if (associations.length === 0) {+ break;+ }++ const ids = associations.map(({ id }) => id);+this.logger.log(`WorkspaceId: ${workspaceId} Deleting ${ids.length} calendar channel event associations for channel ${calendarChannelId}`,);- await calendarChannelEventAssociationRepository.delete(- ids,- transactionManager,- );- },- transactionManager,- );- });++ await calendarChannelEventAssociationRepository.delete(ids);+ }+ },+ );},authContext,{ lite: true },@@ -86,31 +69,53 @@ export class CalendarEventCleanerService {await this.globalWorkspaceOrmManager.executeInWorkspaceContext(async () => {- const calendarEventRepository =- await this.globalWorkspaceOrmManager.getV1Repository(- workspaceId,- 'calendarEvent',- );-- await deleteUsingPagination(- workspaceId,- 500,- async (limit, offset) => {- const nonAssociatedCalendarEvents =- await calendarEventRepository.find({- where: {- calendarChannelEventAssociations: {- id: IsNull(),- },- },- take: limit,- skip: offset,+ await this.globalWorkspaceOrmManager.runInWorkspaceTransaction(+ async (transactionScope) => {+ const calendarEventRepository =+ transactionScope.getRepository<CalendarEventWorkspaceEntity>(+ 'calendarEvent',+ );+ const calendarChannelEventAssociationRepository =+ transactionScope.getRepository<CalendarChannelEventAssociationWorkspaceEntity>(+ 'calendarChannelEventAssociation',+ );++ let cursor: string | undefined;++ for (;;) {+ const page = await calendarEventRepository.find({+ where: isDefined(cursor) ? { id: MoreThan(cursor) } : {},+ order: { id: 'ASC' },+ take: CALENDAR_CLEANUP_PAGE_SIZE,+ select: { id: true },});- return nonAssociatedCalendarEvents.map(({ id }) => id);- },- async (ids) => {- await calendarEventRepository.delete({ id: Any(ids) });+ if (page.length === 0) {+ break;+ }++ cursor = page[page.length - 1].id;++ const pageIds = page.map(({ id }) => id);++ const associations =+ await calendarChannelEventAssociationRepository.find({+ where: { calendarEventId: In(pageIds) },+ select: { calendarEventId: true },+ });++ const referencedEventIds = new Set(+ associations.map(({ calendarEventId }) => calendarEventId),+ );++ const orphanEventIds = pageIds.filter(+ (eventId) => !referencedEventIds.has(eventId),+ );++ if (orphanEventIds.length > 0) {+ await calendarEventRepository.delete(orphanEventIds);+ }+ }},);},diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/services/calendar-save-events.service.ts b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/services/calendar-save-events.service.tsindex 7f8d33fc040..0990797c582 100644--- a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/services/calendar-save-events.service.ts+++ b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/services/calendar-save-events.service.ts@@ -4,7 +4,6 @@ import { Any } from 'typeorm';import { v4 as uuid } from 'uuid';import { type CalendarChannelEntity } from 'src/engine/metadata-modules/calendar-channel/entities/calendar-channel.entity';-import { type WorkspaceEntityManager } from 'src/engine/twenty-orm/entity-manager/workspace-entity-manager';import { GlobalWorkspaceOrmManager } from 'src/engine/twenty-orm/global-workspace-datasource/global-workspace-orm.manager';import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';import { CalendarEventParticipantService } from 'src/modules/calendar/calendar-event-participant-manager/services/calendar-event-participant.service';@@ -36,35 +35,27 @@ export class CalendarSaveEventsService {await this.globalWorkspaceOrmManager.executeInWorkspaceContext(async () => {- const calendarEventRepository =- await this.globalWorkspaceOrmManager.getV1Repository<CalendarEventWorkspaceEntity>(- workspaceId,- 'calendarEvent',- );-- const calendarChannelEventAssociationRepository =- await this.globalWorkspaceOrmManager.getV1Repository<CalendarChannelEventAssociationWorkspaceEntity>(- workspaceId,- 'calendarChannelEventAssociation',- );-- const workspaceDataSource =- await this.globalWorkspaceOrmManager.getGlobalWorkspaceDataSourceWithEntityMetadatas();-- await workspaceDataSource.transaction(- async (transactionManager: WorkspaceEntityManager) => {+ await this.globalWorkspaceOrmManager.runInWorkspaceTransaction(+ async (transactionScope) => {+ const calendarEventRepository =+ transactionScope.getRepository<CalendarEventWorkspaceEntity>(+ 'calendarEvent',+ );++ const calendarChannelEventAssociationRepository =+ transactionScope.getRepository<CalendarChannelEventAssociationWorkspaceEntity>(+ 'calendarChannelEventAssociation',+ );+const existingAssociations =- await calendarChannelEventAssociationRepository.find(- {- where: {- eventExternalId: Any(- fetchedCalendarEvents.map((event) => event.id),- ),- calendarChannelId: calendarChannel.id,- },+ await calendarChannelEventAssociationRepository.find({+ where: {+ eventExternalId: Any(+ fetchedCalendarEvents.map((event) => event.id),+ ),+ calendarChannelId: calendarChannel.id,},- transactionManager,- );+ });const existingCalendarEventIdByExternalId = new Map(existingAssociations.map((association) => [@@ -134,10 +125,7 @@ export class CalendarSaveEventsService {});if (newCalendarEventsToInsert.length > 0) {- await calendarEventRepository.insert(- newCalendarEventsToInsert,- transactionManager,- );+ await calendarEventRepository.insert(newCalendarEventsToInsert);}const fetchedCalendarEventsWithDBEventsEnrichedWithSavedEvents: FetchedCalendarEventWithDBEvent[] =@@ -196,10 +184,7 @@ export class CalendarSaveEventsService {});if (existingEventsToUpdate.length > 0) {- await calendarEventRepository.updateMany(- existingEventsToUpdate,- transactionManager,- );+ await calendarEventRepository.updateMany(existingEventsToUpdate);}const calendarChannelEventAssociationsToSave: Pick<@@ -232,7 +217,6 @@ export class CalendarSaveEventsService {if (calendarChannelEventAssociationsToSave.length > 0) {await calendarChannelEventAssociationRepository.insert(calendarChannelEventAssociationsToSave,- transactionManager,);}@@ -254,7 +238,6 @@ export class CalendarSaveEventsService {if (existingAssociationsToUpdate.length > 0) {await calendarChannelEventAssociationRepository.updateMany(existingAssociationsToUpdate,- transactionManager,);}@@ -307,7 +290,7 @@ export class CalendarSaveEventsService {{participantsToCreate,participantsToUpdate,- transactionManager,+ transactionScope,calendarChannel,connectedAccount,workspaceId,diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/services/calendar-event-participant.service.ts b/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/services/calendar-event-participant.service.tsindex 581b388e73c..22bd2381e23 100644--- a/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/services/calendar-event-participant.service.ts+++ b/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/services/calendar-event-participant.service.ts@@ -4,13 +4,13 @@ import { isDefined } from 'class-validator';import chunk from 'lodash.chunk';import differenceWith from 'lodash.differencewith';import { FieldActorSource } from 'twenty-shared/types';-import { Any } from 'typeorm';+import { Any, In } from 'typeorm';import { type CalendarChannelEntity } from 'src/engine/metadata-modules/calendar-channel/entities/calendar-channel.entity';import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';-import { type WorkspaceEntityManager } from 'src/engine/twenty-orm/entity-manager/workspace-entity-manager';+import { type WorkspaceTransactionScope } from 'src/engine/twenty-orm/global-workspace-datasource/types/workspace-transaction-scope.type';import { GlobalWorkspaceOrmManager } from 'src/engine/twenty-orm/global-workspace-datasource/global-workspace-orm.manager';import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';import { type CalendarEventParticipantWorkspaceEntity } from 'src/modules/calendar/common/standard-objects/calendar-event-participant.workspace-entity';@@ -44,14 +44,14 @@ export class CalendarEventParticipantService {public async upsertAndDeleteCalendarEventParticipants({participantsToCreate,participantsToUpdate,- transactionManager,+ transactionScope,calendarChannel,connectedAccount,workspaceId,}: {participantsToCreate: FetchedCalendarEventParticipantWithCalendarEventId[];participantsToUpdate: FetchedCalendarEventParticipantWithCalendarEventId[];- transactionManager?: WorkspaceEntityManager;+ transactionScope: WorkspaceTransactionScope;calendarChannel: CalendarChannelEntity;connectedAccount: ConnectedAccountEntity;workspaceId: string;@@ -63,8 +63,7 @@ export class CalendarEventParticipantService {const chunkedParticipantsToUpdate = chunk(participantsToUpdate, 200);const calendarEventParticipantRepository =- await this.globalWorkspaceOrmManager.getV1Repository<CalendarEventParticipantWorkspaceEntity>(- workspaceId,+ transactionScope.getRepository<CalendarEventParticipantWorkspaceEntity>('calendarEventParticipant',);@@ -124,23 +123,19 @@ export class CalendarEventParticipantService {participantToUpdate.calendarEventId,);- await calendarEventParticipantRepository.delete(- {- id: Any(- calendarEventParticipantsToDelete.map(- (calendarEventParticipant) => calendarEventParticipant.id,- ),+ await calendarEventParticipantRepository.delete({+ id: Any(+ calendarEventParticipantsToDelete.map(+ (calendarEventParticipant) => calendarEventParticipant.id,),- },- transactionManager,- );+ ),+ });await calendarEventParticipantRepository.updateMany(calendarEventParticipantsToUpdate.map((participant) => ({criteria: participant.id,partialEntity: participant,})),- transactionManager,);participantsToCreate.push(...newCalendarEventParticipants);}@@ -149,13 +144,17 @@ export class CalendarEventParticipantService {const savedParticipants: CalendarEventParticipantWorkspaceEntity[] = [];for (const participantsToCreateChunk of chunkedParticipantsToCreate) {- const savedParticipantsChunk =+ const { identifiers } =await calendarEventParticipantRepository.insert(participantsToCreateChunk,- transactionManager,);- savedParticipants.push(...savedParticipantsChunk.raw);+ const insertedParticipants =+ await calendarEventParticipantRepository.find({+ where: { id: In(identifiers.map(({ id }) => id)) },+ });++ savedParticipants.push(...insertedParticipants);}if (calendarChannel.isContactAutoCreationEnabled) {@@ -177,7 +176,6 @@ export class CalendarEventParticipantService {await this.matchParticipantService.matchParticipants({participants: savedParticipants,objectMetadataName: 'calendarEventParticipant',- transactionManager,matchWith: 'workspaceMemberAndPerson',workspaceId,});diff --git a/packages/twenty-server/src/modules/emailing/services/message-campaign.service.ts b/packages/twenty-server/src/modules/emailing/services/message-campaign.service.tsindex 4b0d4b8755e..7dc59d09f62 100644--- a/packages/twenty-server/src/modules/emailing/services/message-campaign.service.ts+++ b/packages/twenty-server/src/modules/emailing/services/message-campaign.service.ts@@ -40,7 +40,6 @@ import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queuimport { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';import { MessageChannelMetadataService } from 'src/engine/metadata-modules/message-channel/message-channel-metadata.service';import { UserRoleService } from 'src/engine/metadata-modules/user-role/user-role.service';-import { type WorkspaceEntityManager } from 'src/engine/twenty-orm/entity-manager/workspace-entity-manager';import { GlobalWorkspaceOrmManager } from 'src/engine/twenty-orm/global-workspace-datasource/global-workspace-orm.manager';import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';@@ -136,7 +135,7 @@ export class MessageCampaignService {entity: Type<T>,roleId: string,) {- return this.globalWorkspaceOrmManager.getV1Repository(workspaceId, entity, {+ return this.globalWorkspaceOrmManager.getRepository(workspaceId, entity, {unionOf: [roleId],});}@@ -145,7 +144,7 @@ export class MessageCampaignService {workspaceId: string,entity: Type<T>,) {- return this.globalWorkspaceOrmManager.getV1Repository(workspaceId, entity, {+ return this.globalWorkspaceOrmManager.getRepository(workspaceId, entity, {shouldBypassPermissionChecks: true,});}@@ -358,7 +357,6 @@ export class MessageCampaignService {if (recipientsToCreate.length > 0) {await this.materializeCampaignMessages({- workspaceId,campaignId,messageChannelId,fromAddress: campaign.fromAddress?.primaryEmail ?? '',@@ -632,7 +630,6 @@ export class MessageCampaignService {}private async materializeCampaignMessages({- workspaceId,campaignId,messageChannelId,fromAddress,@@ -640,7 +637,6 @@ export class MessageCampaignService {bodyTemplate,recipients,}: {- workspaceId: string;campaignId: string;messageChannelId: string;fromAddress: string;@@ -662,37 +658,30 @@ export class MessageCampaignService {temporaryExternalId: v4(),}));- const messageThreadRepository = await this.getSystemRepository(- workspaceId,- MessageThreadWorkspaceEntity,- );- const messageRepository = await this.getSystemRepository(- workspaceId,- MessageWorkspaceEntity,- );- const associationRepository = await this.getSystemRepository(- workspaceId,- MessageChannelMessageAssociationWorkspaceEntity,- );- const participantRepository = await this.getSystemRepository(- workspaceId,- MessageParticipantWorkspaceEntity,- );-- const workspaceDataSource =- await this.globalWorkspaceOrmManager.getGlobalWorkspaceDataSourceWithEntityMetadatas();-- if (!workspaceDataSource) {- throw new Error(- `No workspace datasource available for workspace ${workspaceId}`,- );- }+ await this.globalWorkspaceOrmManager.runInWorkspaceTransaction(+ async (transactionScope) => {+ const messageThreadRepository =+ transactionScope.getRepository<MessageThreadWorkspaceEntity>(+ 'messageThread',+ { shouldBypassPermissionChecks: true },+ );+ const messageRepository =+ transactionScope.getRepository<MessageWorkspaceEntity>('message', {+ shouldBypassPermissionChecks: true,+ });+ const associationRepository =+ transactionScope.getRepository<MessageChannelMessageAssociationWorkspaceEntity>(+ 'messageChannelMessageAssociation',+ { shouldBypassPermissionChecks: true },+ );+ const participantRepository =+ transactionScope.getRepository<MessageParticipantWorkspaceEntity>(+ 'messageParticipant',+ { shouldBypassPermissionChecks: true },+ );- await workspaceDataSource.transaction(- async (transactionManager: WorkspaceEntityManager) => {await messageThreadRepository.insert(rows.map((row) => ({ id: row.threadId })),- transactionManager,);await messageRepository.insert(rows.map((row) => ({@@ -705,7 +694,6 @@ export class MessageCampaignService {messageCampaignId: campaignId,deliveryStatus: CAMPAIGN_MESSAGE_DELIVERY_STATUS.QUEUED,})),- transactionManager,);await associationRepository.insert(rows.map((row) => ({@@ -716,7 +704,6 @@ export class MessageCampaignService {messageThreadExternalId: row.temporaryExternalId,direction: MessageDirection.OUTGOING,})),- transactionManager,);await participantRepository.insert(rows.flatMap((row) => [@@ -737,7 +724,6 @@ export class MessageCampaignService {messageCampaignId: campaignId,},]),- transactionManager,);},);diff --git a/packages/twenty-server/src/modules/match-participant/match-participant.service.ts b/packages/twenty-server/src/modules/match-participant/match-participant.service.tsindex 56bd30dea7c..9b098b2cf01 100644--- a/packages/twenty-server/src/modules/match-participant/match-participant.service.ts+++ b/packages/twenty-server/src/modules/match-participant/match-participant.service.ts@@ -4,7 +4,6 @@ import chunk from 'lodash.chunk';import { isDefined } from 'twenty-shared/utils';import { Any, In } from 'typeorm';-import { type WorkspaceEntityManager } from 'src/engine/twenty-orm/entity-manager/workspace-entity-manager';import { GlobalWorkspaceOrmManager } from 'src/engine/twenty-orm/global-workspace-datasource/global-workspace-orm.manager';import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';import { WorkspaceEventEmitter } from 'src/engine/workspace-event-emitter/workspace-event-emitter';@@ -47,7 +46,6 @@ type MatchParticipantsArgs<> = {participants: ParticipantWorkspaceEntity[];objectMetadataName: ObjectMetadataName;- transactionManager?: WorkspaceEntityManager;matchWith: 'workspaceMemberOnly' | 'personOnly' | 'workspaceMemberAndPerson';workspaceId: string;};@@ -68,13 +66,13 @@ export class MatchParticipantService<objectMetadataName: 'messageParticipant' | 'calendarEventParticipant',) {if (objectMetadataName === 'messageParticipant') {- return await this.globalWorkspaceOrmManager.getV1Repository<MessageParticipantWorkspaceEntity>(+ return await this.globalWorkspaceOrmManager.getRepository<MessageParticipantWorkspaceEntity>(workspaceId,objectMetadataName,);}- return await this.globalWorkspaceOrmManager.getV1Repository<CalendarEventParticipantWorkspaceEntity>(+ return await this.globalWorkspaceOrmManager.getRepository<CalendarEventParticipantWorkspaceEntity>(workspaceId,objectMetadataName,);@@ -83,7 +81,6 @@ export class MatchParticipantService<public async matchParticipants({participants,objectMetadataName,- transactionManager,matchWith = 'workspaceMemberAndPerson',workspaceId,}: MatchParticipantsArgs<ParticipantWorkspaceEntity>) {@@ -92,7 +89,7 @@ export class MatchParticipantService<}const personRepository =- await this.globalWorkspaceOrmManager.getV1Repository<PersonWorkspaceEntity>(+ await this.globalWorkspaceOrmManager.getRepository<PersonWorkspaceEntity>(workspaceId,'person',{ shouldBypassPermissionChecks: true },@@ -104,7 +101,7 @@ export class MatchParticipantService<);const workspaceMemberRepository =- await this.globalWorkspaceOrmManager.getV1Repository<WorkspaceMemberWorkspaceEntity>(+ await this.globalWorkspaceOrmManager.getRepository<WorkspaceMemberWorkspaceEntity>(workspaceId,'workspaceMember',{ shouldBypassPermissionChecks: true },@@ -127,14 +124,11 @@ export class MatchParticipantService<.orderBy('person.createdAt', 'ASC').getMany();- const workspaceMembers = await workspaceMemberRepository.find(- {- where: {- userEmail: Any(uniqueParticipantsHandles),- },+ const workspaceMembers = await workspaceMemberRepository.find({+ where: {+ userEmail: Any(uniqueParticipantsHandles),},- transactionManager,- );+ });const partipantsToBeUpdated = participants.map((participant) => ({diff --git a/packages/twenty-server/src/modules/match-participant/utils/__tests__/__snapshots__/add-person-email-filters-to-query-builder.util.spec.ts.snap b/packages/twenty-server/src/modules/match-participant/utils/__tests__/__snapshots__/add-person-email-filters-to-query-builder.util.spec.ts.snapindex df7a4416281..1da9932881f 100644--- a/packages/twenty-server/src/modules/match-participant/utils/__tests__/__snapshots__/add-person-email-filters-to-query-builder.util.spec.ts.snap+++ b/packages/twenty-server/src/modules/match-participant/utils/__tests__/__snapshots__/add-person-email-filters-to-query-builder.util.spec.ts.snap@@ -1,21 +1,10 @@-// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing+// Jest Snapshot v1, https://goo.gl/fbAQLPexports[`addPersonEmailFiltersToQueryBuilder case-insensitive email normalization: should normalize emails to lowercase - query builder calls 1`] = `[{"args": [- [- "person.id",- "person.emailsPrimaryEmail",- "person.emailsAdditionalEmails",- "person.deletedAt",- ],- ],- "method": "select",- },- {- "args": [- "LOWER(person.emailsPrimaryEmail) IN (:...emails)",+ "LOWER("person"."emailsPrimaryEmail") IN (:...emails)",{"emails": [@@ -31,7 +20,7 @@ exports[`addPersonEmailFiltersToQueryBuilder case-insensitive email normalizatio},{"args": [- "person.emailsAdditionalEmails @> :email0::jsonb",+ ""person"."emailsAdditionalEmails" @> :email0::jsonb",{"email0": "["[email protected]"]",},@@ -40,7 +29,7 @@ exports[`addPersonEmailFiltersToQueryBuilder case-insensitive email normalizatio},{"args": [- "person.emailsAdditionalEmails @> :email1::jsonb",+ ""person"."emailsAdditionalEmails" @> :email1::jsonb",{"email1": "["[email protected]"]",},@@ -58,18 +47,7 @@ exports[`addPersonEmailFiltersToQueryBuilder emails with empty exclusion array:[{"args": [- [- "person.id",- "person.emailsPrimaryEmail",- "person.emailsAdditionalEmails",- "person.deletedAt",- ],- ],- "method": "select",- },- {- "args": [- "LOWER(person.emailsPrimaryEmail) IN (:...emails)",+ "LOWER("person"."emailsPrimaryEmail") IN (:...emails)",{"emails": [@@ -84,7 +62,7 @@ exports[`addPersonEmailFiltersToQueryBuilder emails with empty exclusion array:},{"args": [- "person.emailsAdditionalEmails @> :email0::jsonb",+ ""person"."emailsAdditionalEmails" @> :email0::jsonb",{"email0": "["[email protected]"]",},@@ -102,18 +80,7 @@ exports[`addPersonEmailFiltersToQueryBuilder empty emails array: should handle e[{"args": [- [- "person.id",- "person.emailsPrimaryEmail",- "person.emailsAdditionalEmails",- "person.deletedAt",- ],- ],- "method": "select",- },- {- "args": [- "LOWER(person.emailsPrimaryEmail) IN (:...emails)",+ "LOWER("person"."emailsPrimaryEmail") IN (:...emails)",{"emails": [],},@@ -135,18 +102,7 @@ exports[`addPersonEmailFiltersToQueryBuilder multiple emails with exclusions: sh[{"args": [- [- "person.id",- "person.emailsPrimaryEmail",- "person.emailsAdditionalEmails",- "person.deletedAt",- ],- ],- "method": "select",- },- {- "args": [- "LOWER(person.emailsPrimaryEmail) IN (:...emails)",+ "LOWER("person"."emailsPrimaryEmail") IN (:...emails)",{"emails": [@@ -162,7 +118,7 @@ exports[`addPersonEmailFiltersToQueryBuilder multiple emails with exclusions: sh},{"args": [- "person.id NOT IN (:...excludePersonIds)",+ ""person"."id" NOT IN (:...excludePersonIds)",{"excludePersonIds": ["person-1",@@ -173,7 +129,7 @@ exports[`addPersonEmailFiltersToQueryBuilder multiple emails with exclusions: sh},{"args": [- "person.id NOT IN (:...excludePersonIds) AND person.emailsAdditionalEmails @> :email0::jsonb",+ ""person"."id" NOT IN (:...excludePersonIds) AND "person"."emailsAdditionalEmails" @> :email0::jsonb",{"email0": "["[email protected]"]","excludePersonIds": [@@ -185,7 +141,7 @@ exports[`addPersonEmailFiltersToQueryBuilder multiple emails with exclusions: sh},{"args": [- "person.id NOT IN (:...excludePersonIds) AND person.emailsAdditionalEmails @> :email1::jsonb",+ ""person"."id" NOT IN (:...excludePersonIds) AND "person"."emailsAdditionalEmails" @> :email1::jsonb",{"email1": "["[email protected]"]","excludePersonIds": [@@ -206,18 +162,7 @@ exports[`addPersonEmailFiltersToQueryBuilder multiple emails without exclusions:[{"args": [- [- "person.id",- "person.emailsPrimaryEmail",- "person.emailsAdditionalEmails",- "person.deletedAt",- ],- ],- "method": "select",- },- {- "args": [- "LOWER(person.emailsPrimaryEmail) IN (:...emails)",+ "LOWER("person"."emailsPrimaryEmail") IN (:...emails)",{"emails": [@@ -233,7 +178,7 @@ exports[`addPersonEmailFiltersToQueryBuilder multiple emails without exclusions:},{"args": [- "person.emailsAdditionalEmails @> :email0::jsonb",+ ""person"."emailsAdditionalEmails" @> :email0::jsonb",{"email0": "["[email protected]"]",},@@ -242,7 +187,7 @@ exports[`addPersonEmailFiltersToQueryBuilder multiple emails without exclusions:},{"args": [- "person.emailsAdditionalEmails @> :email1::jsonb",+ ""person"."emailsAdditionalEmails" @> :email1::jsonb",{"email1": "["[email protected]"]",},@@ -260,18 +205,7 @@ exports[`addPersonEmailFiltersToQueryBuilder single email with person ID exclusi[{"args": [- [- "person.id",- "person.emailsPrimaryEmail",- "person.emailsAdditionalEmails",- "person.deletedAt",- ],- ],- "method": "select",- },- {- "args": [- "LOWER(person.emailsPrimaryEmail) IN (:...emails)",+ "LOWER("person"."emailsPrimaryEmail") IN (:...emails)",{"emails": [@@ -286,7 +220,7 @@ exports[`addPersonEmailFiltersToQueryBuilder single email with person ID exclusi},{"args": [- "person.id NOT IN (:...excludePersonIds)",+ ""person"."id" NOT IN (:...excludePersonIds)",{"excludePersonIds": ["person-1",@@ -298,7 +232,7 @@ exports[`addPersonEmailFiltersToQueryBuilder single email with person ID exclusi},{"args": [- "person.id NOT IN (:...excludePersonIds) AND person.emailsAdditionalEmails @> :email0::jsonb",+ ""person"."id" NOT IN (:...excludePersonIds) AND "person"."emailsAdditionalEmails" @> :email0::jsonb",{"email0": "["[email protected]"]","excludePersonIds": [@@ -320,18 +254,7 @@ exports[`addPersonEmailFiltersToQueryBuilder single email without exclusions: sh[{"args": [- [- "person.id",- "person.emailsPrimaryEmail",- "person.emailsAdditionalEmails",- "person.deletedAt",- ],- ],- "method": "select",- },- {- "args": [- "LOWER(person.emailsPrimaryEmail) IN (:...emails)",+ "LOWER("person"."emailsPrimaryEmail") IN (:...emails)",{"emails": [@@ -346,7 +269,7 @@ exports[`addPersonEmailFiltersToQueryBuilder single email without exclusions: sh},{"args": [- "person.emailsAdditionalEmails @> :email0::jsonb",+ ""person"."emailsAdditionalEmails" @> :email0::jsonb",{"email0": "["[email protected]"]",},@@ -364,18 +287,7 @@ exports[`addPersonEmailFiltersToQueryBuilder three emails with unique parameter[{"args": [- [- "person.id",- "person.emailsPrimaryEmail",- "person.emailsAdditionalEmails",- "person.deletedAt",- ],- ],- "method": "select",- },- {- "args": [- "LOWER(person.emailsPrimaryEmail) IN (:...emails)",+ "LOWER("person"."emailsPrimaryEmail") IN (:...emails)",{"emails": [@@ -392,7 +304,7 @@ exports[`addPersonEmailFiltersToQueryBuilder three emails with unique parameter},{"args": [- "person.emailsAdditionalEmails @> :email0::jsonb",+ ""person"."emailsAdditionalEmails" @> :email0::jsonb",{"email0": "["[email protected]"]",},@@ -401,7 +313,7 @@ exports[`addPersonEmailFiltersToQueryBuilder three emails with unique parameter},{"args": [- "person.emailsAdditionalEmails @> :email1::jsonb",+ ""person"."emailsAdditionalEmails" @> :email1::jsonb",{"email1": "["[email protected]"]",},@@ -410,7 +322,7 @@ exports[`addPersonEmailFiltersToQueryBuilder three emails with unique parameter},{"args": [- "person.emailsAdditionalEmails @> :email2::jsonb",+ ""person"."emailsAdditionalEmails" @> :email2::jsonb",{"email2": "["[email protected]"]",},diff --git a/packages/twenty-server/src/modules/match-participant/utils/add-person-email-filters-to-query-builder.ts b/packages/twenty-server/src/modules/match-participant/utils/add-person-email-filters-to-query-builder.tsindex 807a7b0fad9..a655c1d1501 100644--- a/packages/twenty-server/src/modules/match-participant/utils/add-person-email-filters-to-query-builder.ts+++ b/packages/twenty-server/src/modules/match-participant/utils/add-person-email-filters-to-query-builder.ts@@ -17,20 +17,14 @@ export function addPersonEmailFiltersToQueryBuilder({const normalizedEmails = emails.map((email) => email.toLowerCase());queryBuilder = queryBuilder- .select([- 'person.id',- 'person.emailsPrimaryEmail',- 'person.emailsAdditionalEmails',- 'person.deletedAt',- ])- .where('LOWER(person.emailsPrimaryEmail) IN (:...emails)', {+ .where('LOWER("person"."emailsPrimaryEmail") IN (:...emails)', {emails: normalizedEmails,}).withDeleted();if (excludePersonIds.length > 0) {queryBuilder = queryBuilder.andWhere(- 'person.id NOT IN (:...excludePersonIds)',+ '"person"."id" NOT IN (:...excludePersonIds)',{excludePersonIds,},@@ -41,8 +35,8 @@ export function addPersonEmailFiltersToQueryBuilder({const emailParamName = `email${index}`;const orWhereIsInAdditionalEmail =excludePersonIds.length > 0- ? `person.id NOT IN (:...excludePersonIds) AND person.emailsAdditionalEmails @> :${emailParamName}::jsonb`- : `person.emailsAdditionalEmails @> :${emailParamName}::jsonb`;+ ? `"person"."id" NOT IN (:...excludePersonIds) AND "person"."emailsAdditionalEmails" @> :${emailParamName}::jsonb`+ : `"person"."emailsAdditionalEmails" @> :${emailParamName}::jsonb`;queryBuilder = queryBuilder.orWhere(orWhereIsInAdditionalEmail, {...(excludePersonIds.length > 0 && { excludePersonIds }),diff --git a/packages/twenty-server/src/modules/messaging/blocklist-manager/jobs/messaging-blocklist-item-delete-messages.job.ts b/packages/twenty-server/src/modules/messaging/blocklist-manager/jobs/messaging-blocklist-item-delete-messages.job.tsindex 80524aa8507..1d99413c1c2 100644--- a/packages/twenty-server/src/modules/messaging/blocklist-manager/jobs/messaging-blocklist-item-delete-messages.job.ts+++ b/packages/twenty-server/src/modules/messaging/blocklist-manager/jobs/messaging-blocklist-item-delete-messages.job.ts@@ -17,6 +17,7 @@ import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-systemimport { type WorkspaceEventBatch } from 'src/engine/workspace-event-emitter/types/workspace-event-batch.type';import { type BlocklistWorkspaceEntity } from 'src/modules/blocklist/standard-objects/blocklist.workspace-entity';import { type MessageChannelMessageAssociationWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-channel-message-association.workspace-entity';+import { type MessageParticipantWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-participant.workspace-entity';import { MessagingMessageCleanerService } from 'src/modules/messaging/message-cleaner/services/messaging-message-cleaner.service';import { type WorkspaceMemberWorkspaceEntity } from 'src/modules/workspace-member/standard-objects/workspace-member.workspace-entity';@@ -96,6 +97,13 @@ export class BlocklistItemDeleteMessagesJob {{ shouldBypassPermissionChecks: true },);+ const messageParticipantRepository =+ await this.globalWorkspaceOrmManager.getRepository<MessageParticipantWorkspaceEntity>(+ workspaceId,+ 'messageParticipant',+ { shouldBypassPermissionChecks: true },+ );+for (const workspaceMemberId of handlesToDeleteByWorkspaceMemberIdMap.keys()) {const handles =handlesToDeleteByWorkspaceMemberIdMap.get(workspaceMemberId);@@ -178,13 +186,29 @@ export class BlocklistItemDeleteMessagesJob {: { handle, role: In(rolesToDelete) };});+ const matchingParticipants =+ await messageParticipantRepository.find({+ where: handleConditions,+ select: { messageId: true },+ });++ const messageIds = [+ ...new Set(+ matchingParticipants.map(+ (participant) => participant.messageId,+ ),+ ),+ ];++ if (messageIds.length === 0) {+ continue;+ }+const messageChannelMessageAssociationsToDelete =await messageChannelMessageAssociationRepository.find({where: {messageChannelId: messageChannel.id,- message: {- messageParticipants: handleConditions,- },+ messageId: In(messageIds),},});diff --git a/packages/twenty-server/src/modules/messaging/message-cleaner/services/messaging-message-cleaner.service.ts b/packages/twenty-server/src/modules/messaging/message-cleaner/services/messaging-message-cleaner.service.tsindex ce2856838ed..47757dc72a7 100644--- a/packages/twenty-server/src/modules/messaging/message-cleaner/services/messaging-message-cleaner.service.ts+++ b/packages/twenty-server/src/modules/messaging/message-cleaner/services/messaging-message-cleaner.service.ts@@ -1,15 +1,17 @@import { Injectable, Logger } from '@nestjs/common';import chunk from 'lodash.chunk';-import { In, IsNull } from 'typeorm';+import { isDefined } from 'twenty-shared/utils';+import { In, MoreThan } from 'typeorm';-import { type WorkspaceEntityManager } from 'src/engine/twenty-orm/entity-manager/workspace-entity-manager';import { GlobalWorkspaceOrmManager } from 'src/engine/twenty-orm/global-workspace-datasource/global-workspace-orm.manager';+import { type WorkspaceRepository } from 'src/engine/twenty-orm/repository/workspace.repository';import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';-import { MessageChannelMessageAssociationWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-channel-message-association.workspace-entity';+import { type MessageChannelMessageAssociationWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-channel-message-association.workspace-entity';import { type MessageThreadWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-thread.workspace-entity';import { type MessageWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message.workspace-entity';-import { deleteUsingPagination } from 'src/modules/messaging/message-cleaner/utils/delete-using-pagination.util';++const ORPHAN_CLEANUP_PAGE_SIZE = 500;@Injectable()export class MessagingMessageCleanerService {@@ -31,93 +33,90 @@ export class MessagingMessageCleanerService {await this.globalWorkspaceOrmManager.executeInWorkspaceContext(async () => {- const messageRepository =- await this.globalWorkspaceOrmManager.getV1Repository<MessageWorkspaceEntity>(- workspaceId,- 'message',- );-- const messageChannelMessageAssociationRepository =- await this.globalWorkspaceOrmManager.getV1Repository<MessageChannelMessageAssociationWorkspaceEntity>(- workspaceId,- 'messageChannelMessageAssociation',- );-- const messageThreadRepository =- await this.globalWorkspaceOrmManager.getV1Repository<MessageThreadWorkspaceEntity>(- workspaceId,- 'messageThread',- );-- const messageExternalIdsChunks = chunk(messageExternalIds, 500);-- for (const messageExternalIdsChunk of messageExternalIdsChunks) {- const messageChannelMessageAssociationsToDelete =- await messageChannelMessageAssociationRepository.find({- where: {- messageExternalId: In(messageExternalIdsChunk),- messageChannelId,- },- });+ await this.globalWorkspaceOrmManager.runInWorkspaceTransaction(+ async (transactionScope) => {+ const messageRepository =+ transactionScope.getRepository<MessageWorkspaceEntity>('message');+ const messageChannelMessageAssociationRepository =+ transactionScope.getRepository<MessageChannelMessageAssociationWorkspaceEntity>(+ 'messageChannelMessageAssociation',+ );+ const messageThreadRepository =+ transactionScope.getRepository<MessageThreadWorkspaceEntity>(+ 'messageThread',+ );- if (messageChannelMessageAssociationsToDelete.length <= 0) {- continue;- }+ for (const messageExternalIdsChunk of chunk(+ messageExternalIds,+ 500,+ )) {+ const associationsToDelete =+ await messageChannelMessageAssociationRepository.find({+ where: {+ messageExternalId: In(messageExternalIdsChunk),+ messageChannelId,+ },+ });- await messageChannelMessageAssociationRepository.delete(- messageChannelMessageAssociationsToDelete.map(({ id }) => id),- );+ if (associationsToDelete.length <= 0) {+ continue;+ }++ await messageChannelMessageAssociationRepository.delete(+ associationsToDelete.map(({ id }) => id),+ );- this.logger.log(- `WorkspaceId: ${workspaceId} Deleting ${messageChannelMessageAssociationsToDelete.length} message channel message associations`,- );+ this.logger.log(+ `WorkspaceId: ${workspaceId} Deleting ${associationsToDelete.length} message channel message associations`,+ );- const orphanMessages = await messageRepository.find({- where: {- id: In(- messageChannelMessageAssociationsToDelete.map(- ({ messageId }) => messageId,+ const candidateMessageIds = [+ ...new Set(+ associationsToDelete.map(({ messageId }) => messageId),),- ),- messageChannelMessageAssociations: {- id: IsNull(),- },- },- });-- if (orphanMessages.length <= 0) {- continue;- }-- this.logger.debug(- `WorkspaceId: ${workspaceId} Deleting ${orphanMessages.length} orphan messages`,- );-- await messageRepository.delete(orphanMessages.map(({ id }) => id));-- const orphanMessageThreads = await messageThreadRepository.find({- where: {- id: In(- orphanMessages.map(({ messageThreadId }) => messageThreadId),- ),- messages: {- id: IsNull(),- },- },- });+ ];++ const orphanMessageIds = await this.filterOrphans(+ candidateMessageIds,+ (messageIds) =>+ this.findReferencedMessageIds(+ messageChannelMessageAssociationRepository,+ messageIds,+ ),+ );- if (orphanMessageThreads.length <= 0) {- continue;- }+ if (orphanMessageIds.length <= 0) {+ continue;+ }- this.logger.debug(- `WorkspaceId: ${workspaceId} Deleting ${orphanMessageThreads.length} orphan message threads`,- );+ const orphanMessages = await messageRepository.find({+ where: { id: In(orphanMessageIds) },+ });- await messageThreadRepository.delete(- orphanMessageThreads.map(({ id }) => id),- );- }+ await messageRepository.delete(orphanMessageIds);++ const candidateThreadIds = [+ ...new Set(+ orphanMessages+ .map(({ messageThreadId }) => messageThreadId)+ .filter(isDefined),+ ),+ ];++ const orphanThreadIds = await this.filterOrphans(+ candidateThreadIds,+ (threadIds) =>+ this.findReferencedThreadIds(messageRepository, threadIds),+ );++ if (orphanThreadIds.length <= 0) {+ continue;+ }++ await messageThreadRepository.delete(orphanThreadIds);+ }+ },+ );},authContext,{ lite: true },@@ -135,55 +134,35 @@ export class MessagingMessageCleanerService {await this.globalWorkspaceOrmManager.executeInWorkspaceContext(async () => {- const messageChannelMessageAssociationRepository =- await this.globalWorkspaceOrmManager.getV1Repository<MessageChannelMessageAssociationWorkspaceEntity>(- workspaceId,- 'messageChannelMessageAssociation',- );-- const workspaceDataSource =- await this.globalWorkspaceOrmManager.getGlobalWorkspaceDataSourceWithEntityMetadatas();-- await workspaceDataSource.transaction(async (manager) => {- const transactionManager = manager as WorkspaceEntityManager;-- await deleteUsingPagination(- workspaceId,- 500,- async (- limit: number,- offset: number,- _workspaceId: string,- transactionManager?: WorkspaceEntityManager,- ) => {+ await this.globalWorkspaceOrmManager.runInWorkspaceTransaction(+ async (transactionScope) => {+ const messageChannelMessageAssociationRepository =+ transactionScope.getRepository<MessageChannelMessageAssociationWorkspaceEntity>(+ 'messageChannelMessageAssociation',+ );++ for (;;) {const associations =- await messageChannelMessageAssociationRepository.find(- {- where: { messageChannelId },- take: limit,- skip: offset,- },- transactionManager,- );-- return associations.map(({ id }) => id);- },- async (- ids: string[],- workspaceId: string,- transactionManager?: WorkspaceEntityManager,- ) => {+ await messageChannelMessageAssociationRepository.find({+ where: { messageChannelId },+ take: ORPHAN_CLEANUP_PAGE_SIZE,+ select: { id: true },+ });++ if (associations.length === 0) {+ break;+ }++ const ids = associations.map(({ id }) => id);+this.logger.log(`WorkspaceId: ${workspaceId} Deleting ${ids.length} message channel message associations for channel ${messageChannelId}`,);- await messageChannelMessageAssociationRepository.delete(- ids,- transactionManager,- );- },- transactionManager,- );- });++ await messageChannelMessageAssociationRepository.delete(ids);+ }+ },+ );},authContext,{ lite: true },@@ -195,93 +174,56 @@ export class MessagingMessageCleanerService {await this.globalWorkspaceOrmManager.executeInWorkspaceContext(async () => {- const messageThreadRepository =- await this.globalWorkspaceOrmManager.getV1Repository<MessageThreadWorkspaceEntity>(- workspaceId,- 'messageThread',- );-- const messageRepository =- await this.globalWorkspaceOrmManager.getV1Repository<MessageWorkspaceEntity>(- workspaceId,- 'message',- );-- const workspaceDataSource =- await this.globalWorkspaceOrmManager.getGlobalWorkspaceDataSourceWithEntityMetadatas();-- await workspaceDataSource.transaction(- async (transactionManager: WorkspaceEntityManager) => {- await deleteUsingPagination(- workspaceId,- 500,- async (- limit: number,- offset: number,- _workspaceId: string,- transactionManager: WorkspaceEntityManager,- ) => {- const nonAssociatedMessages = await messageRepository.find(- {- where: {- messageChannelMessageAssociations: {- id: IsNull(),- },- },- take: limit,- skip: offset,- relations: ['messageChannelMessageAssociations'],- },- transactionManager,- );+ await this.globalWorkspaceOrmManager.runInWorkspaceTransaction(+ async (transactionScope) => {+ const messageThreadRepository =+ transactionScope.getRepository<MessageThreadWorkspaceEntity>(+ 'messageThread',+ );+ const messageRepository =+ transactionScope.getRepository<MessageWorkspaceEntity>('message');+ const messageChannelMessageAssociationRepository =+ transactionScope.getRepository<MessageChannelMessageAssociationWorkspaceEntity>(+ 'messageChannelMessageAssociation',+ );- return nonAssociatedMessages.map(({ id }) => id);- },- async (- ids: string[],- workspaceId: string,- transactionManager?: WorkspaceEntityManager,- ) => {- this.logger.debug(- `WorkspaceId: ${workspaceId} Deleting ${ids.length} messages from message cleaner`,- );- await messageRepository.delete(ids, transactionManager);+ await this.deleteOrphansByKeyset(+ async (cursor) => {+ const page = await messageRepository.find({+ where: isDefined(cursor) ? { id: MoreThan(cursor) } : {},+ order: { id: 'ASC' },+ take: ORPHAN_CLEANUP_PAGE_SIZE,+ select: { id: true },+ });++ return page.map(({ id }) => id);},- transactionManager,+ (ids) => messageRepository.delete(ids),+ (pageIds) =>+ this.filterOrphans(pageIds, (ids) =>+ this.findReferencedMessageIds(+ messageChannelMessageAssociationRepository,+ ids,+ ),+ ),);- await deleteUsingPagination(- workspaceId,- 500,- async (- limit: number,- offset: number,- _workspaceId: string,- transactionManager?: WorkspaceEntityManager,- ) => {- const orphanThreads = await messageThreadRepository.find(- {- where: {- messages: {- id: IsNull(),- },- },- take: limit,- skip: offset,- },- transactionManager,- );+ await this.deleteOrphansByKeyset(+ async (cursor) => {+ const page = await messageThreadRepository.find({+ where: isDefined(cursor) ? { id: MoreThan(cursor) } : {},+ order: { id: 'ASC' },+ take: ORPHAN_CLEANUP_PAGE_SIZE,+ select: { id: true },+ });- return orphanThreads.map(({ id }) => id);- },- async (- ids: string[],- _workspaceId: string,- transactionManager?: WorkspaceEntityManager,- ) => {- await messageThreadRepository.delete(ids, transactionManager);+ return page.map(({ id }) => id);},- transactionManager,+ (ids) => messageThreadRepository.delete(ids),+ (pageIds) =>+ this.filterOrphans(pageIds, (ids) =>+ this.findReferencedThreadIds(messageRepository, ids),+ ),);},);@@ -290,4 +232,69 @@ export class MessagingMessageCleanerService {{ lite: true },);}++ private async findReferencedMessageIds(+ messageChannelMessageAssociationRepository: WorkspaceRepository<MessageChannelMessageAssociationWorkspaceEntity>,+ messageIds: string[],+ ): Promise<string[]> {+ const associations = await messageChannelMessageAssociationRepository.find({+ where: { messageId: In(messageIds) },+ select: { messageId: true },+ });++ return associations.map(({ messageId }) => messageId);+ }++ private async findReferencedThreadIds(+ messageRepository: WorkspaceRepository<MessageWorkspaceEntity>,+ threadIds: string[],+ ): Promise<string[]> {+ const messages = await messageRepository.find({+ where: { messageThreadId: In(threadIds) },+ select: { messageThreadId: true },+ });++ return messages+ .map(({ messageThreadId }) => messageThreadId)+ .filter(isDefined);+ }++ private async filterOrphans(+ parentIds: string[],+ findReferencedParentIds: (parentIds: string[]) => Promise<string[]>,+ ): Promise<string[]> {+ if (parentIds.length === 0) {+ return [];+ }++ const referencedParentIds = new Set(+ await findReferencedParentIds(parentIds),+ );++ return parentIds.filter((parentId) => !referencedParentIds.has(parentId));+ }++ private async deleteOrphansByKeyset(+ fetchPageIds: (cursor: string | undefined) => Promise<string[]>,+ deleteByIds: (ids: string[]) => Promise<unknown>,+ findOrphanIds: (pageIds: string[]) => Promise<string[]>,+ ): Promise<void> {+ let cursor: string | undefined;++ for (;;) {+ const pageIds = await fetchPageIds(cursor);++ if (pageIds.length === 0) {+ break;+ }++ cursor = pageIds[pageIds.length - 1];++ const orphanIds = await findOrphanIds(pageIds);++ if (orphanIds.length > 0) {+ await deleteByIds(orphanIds);+ }+ }+ }}diff --git a/packages/twenty-server/src/modules/messaging/message-cleaner/utils/__tests__/delete-using-pagination.util.spec.ts b/packages/twenty-server/src/modules/messaging/message-cleaner/utils/__tests__/delete-using-pagination.util.spec.tsdeleted file mode 100644index 27255327805..00000000000--- a/packages/twenty-server/src/modules/messaging/message-cleaner/utils/__tests__/delete-using-pagination.util.spec.ts+++ /dev/null@@ -1,44 +0,0 @@-import { deleteUsingPagination } from 'src/modules/messaging/message-cleaner/utils/delete-using-pagination.util';--describe('deleteUsingPagination', () => {- it('should delete items using pagination', async () => {- const workspaceId = 'workspace123';- const batchSize = 10;- const getterPaginated = jest- .fn()- .mockResolvedValueOnce(['id1', 'id2'])- .mockResolvedValueOnce([]);- const deleter = jest.fn();- const transactionManager = undefined;-- await deleteUsingPagination(- workspaceId,- batchSize,- getterPaginated,- deleter,- transactionManager,- );-- expect(getterPaginated).toHaveBeenNthCalledWith(- 1,- batchSize,- 0,- workspaceId,- transactionManager,- );- expect(getterPaginated).toHaveBeenNthCalledWith(- 2,- batchSize,- 0,- workspaceId,- transactionManager,- );- expect(deleter).toHaveBeenNthCalledWith(- 1,- ['id1', 'id2'],- workspaceId,- transactionManager,- );- expect(deleter).toHaveBeenCalledTimes(1);- });-});diff --git a/packages/twenty-server/src/modules/messaging/message-cleaner/utils/delete-using-pagination.util.ts b/packages/twenty-server/src/modules/messaging/message-cleaner/utils/delete-using-pagination.util.tsdeleted file mode 100644index bb33b8df7cf..00000000000--- a/packages/twenty-server/src/modules/messaging/message-cleaner/utils/delete-using-pagination.util.ts+++ /dev/null@@ -1,35 +0,0 @@-import { type WorkspaceEntityManager } from 'src/engine/twenty-orm/entity-manager/workspace-entity-manager';--export const deleteUsingPagination = async (- workspaceId: string,- batchSize: number,- getterPaginated: (- limit: number,- offset: number,- workspaceId: string,- transactionManager?: WorkspaceEntityManager,- ) => Promise<string[]>,- deleter: (- ids: string[],- workspaceId: string,- transactionManager?: WorkspaceEntityManager,- ) => Promise<void>,- transactionManager?: WorkspaceEntityManager,-) => {- let hasMoreData = true;-- while (hasMoreData) {- const idsToDelete = await getterPaginated(- batchSize,- 0,- workspaceId,- transactionManager,- );-- if (idsToDelete.length > 0) {- await deleter(idsToDelete, workspaceId, transactionManager);- } else {- hasMoreData = false;- }- }-};diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-message-folder-association.service.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-message-folder-association.service.tsindex 27b4839b10c..88b599f05cd 100644--- a/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-message-folder-association.service.ts+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-message-folder-association.service.ts@@ -2,8 +2,8 @@ import { Injectable } from '@nestjs/common';import { In } from 'typeorm';-import { type WorkspaceEntityManager } from 'src/engine/twenty-orm/entity-manager/workspace-entity-manager';import { GlobalWorkspaceOrmManager } from 'src/engine/twenty-orm/global-workspace-datasource/global-workspace-orm.manager';+import { type WorkspaceTransactionScope } from 'src/engine/twenty-orm/global-workspace-datasource/types/workspace-transaction-scope.type';import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';import { type MessageChannelMessageAssociationMessageFolderWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-channel-message-association-message-folder.workspace-entity';import { type MessageChannelMessageAssociationFolderAssociation } from 'src/modules/messaging/message-import-manager/types/message-channel-message-association-folder-association.type';@@ -18,7 +18,7 @@ export class MessagingMessageFolderAssociationService {async saveMessageFolderAssociations(associations: MessageChannelMessageAssociationFolderAssociation[],workspaceId: string,- transactionManager?: WorkspaceEntityManager,+ transactionScope: WorkspaceTransactionScope,): Promise<void> {const associationIds = [...new Set(@@ -37,19 +37,15 @@ export class MessagingMessageFolderAssociationService {await this.globalWorkspaceOrmManager.executeInWorkspaceContext(async () => {const repository =- await this.globalWorkspaceOrmManager.getV1Repository<MessageChannelMessageAssociationMessageFolderWorkspaceEntity>(- workspaceId,+ transactionScope.getRepository<MessageChannelMessageAssociationMessageFolderWorkspaceEntity>('messageChannelMessageAssociationMessageFolder',);- const existingRecords = await repository.find(- {- where: {- messageChannelMessageAssociationId: In(associationIds),- },+ const existingRecords = await repository.find({+ where: {+ messageChannelMessageAssociationId: In(associationIds),},- transactionManager,- );+ });const recordsToInsert = buildMessageFolderAssociationsToInsert({associations,@@ -57,7 +53,7 @@ export class MessagingMessageFolderAssociationService {});if (recordsToInsert.length > 0) {- await repository.insert(recordsToInsert, transactionManager);+ await repository.insert(recordsToInsert);}},authContext,diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-message.service.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-message.service.tsindex 74d02cfb457..531f1597e4e 100644--- a/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-message.service.ts+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-message.service.ts@@ -4,8 +4,8 @@ import { isDefined } from 'twenty-shared/utils';import { In } from 'typeorm';import { v4 } from 'uuid';-import { type WorkspaceEntityManager } from 'src/engine/twenty-orm/entity-manager/workspace-entity-manager';import { GlobalWorkspaceOrmManager } from 'src/engine/twenty-orm/global-workspace-datasource/global-workspace-orm.manager';+import { type WorkspaceTransactionScope } from 'src/engine/twenty-orm/global-workspace-datasource/types/workspace-transaction-scope.type';import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';import { type MessageChannelMessageAssociationWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-channel-message-association.workspace-entity';import { type MessageThreadWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-thread.workspace-entity';@@ -48,7 +48,7 @@ export class MessagingMessageService {public async saveMessagesWithinTransaction(messages: MessageWithParticipants[],messageChannelId: string,- transactionManager: WorkspaceEntityManager,+ transactionScope: WorkspaceTransactionScope,workspaceId: string,): Promise<{createdMessages: Partial<MessageWorkspaceEntity>[];@@ -64,20 +64,15 @@ export class MessagingMessageService {return this.globalWorkspaceOrmManager.executeInWorkspaceContext(async () => {const messageChannelMessageAssociationRepository =- await this.globalWorkspaceOrmManager.getV1Repository<MessageChannelMessageAssociationWorkspaceEntity>(- workspaceId,+ transactionScope.getRepository<MessageChannelMessageAssociationWorkspaceEntity>('messageChannelMessageAssociation',);const messageRepository =- await this.globalWorkspaceOrmManager.getV1Repository<MessageWorkspaceEntity>(- workspaceId,- 'message',- );+ transactionScope.getRepository<MessageWorkspaceEntity>('message');const messageThreadRepository =- await this.globalWorkspaceOrmManager.getV1Repository<MessageThreadWorkspaceEntity>(- workspaceId,+ transactionScope.getRepository<MessageThreadWorkspaceEntity>('messageThread',);@@ -92,18 +87,15 @@ export class MessagingMessageService {});const messageChannelMessageAssociationsReferencingMessageThread =- await messageChannelMessageAssociationRepository.find(- {- where: {- messageThreadExternalId: In(- messages.map((message) => message.messageThreadExternalId),- ),- messageChannelId,- },- relations: ['message'],+ await messageChannelMessageAssociationRepository.find({+ where: {+ messageThreadExternalId: In(+ messages.map((message) => message.messageThreadExternalId),+ ),+ messageChannelId,},- transactionManager,- );+ relations: { message: true },+ });const existingMessageChannelMessageAssociations =await messageChannelMessageAssociationRepository.find({@@ -252,10 +244,7 @@ export class MessagingMessageService {}if (messageThreadsToCreate.length > 0) {- await messageThreadRepository.insert(- messageThreadsToCreate,- transactionManager,- );+ await messageThreadRepository.insert(messageThreadsToCreate);}if (threadSubjectUpdates.size > 0) {@@ -264,7 +253,6 @@ export class MessagingMessageService {([id, { subject }]) => ({ id, subject }),),['id'],- transactionManager,);}@@ -272,7 +260,7 @@ export class MessagingMessageService {.map((accumulator) => accumulator.messageToCreate).filter(isDefined);- await messageRepository.insert(messagesToCreate, transactionManager);+ await messageRepository.insert(messagesToCreate);const messageChannelMessageAssociationsToCreate = Array.from(associationToCreateByMessageId.values(),@@ -280,7 +268,6 @@ export class MessagingMessageService {await messageChannelMessageAssociationRepository.insert(messageChannelMessageAssociationsToCreate,- transactionManager,);const messageExternalIdsAndIdsMap = new Map<string, string>();diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-save-messages-and-enqueue-contact-creation.service.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-save-messages-and-enqueue-contact-creation.service.tsindex b5386189cfd..73784f812eb 100644--- a/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-save-messages-and-enqueue-contact-creation.service.ts+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-save-messages-and-enqueue-contact-creation.service.ts@@ -11,7 +11,6 @@ import { type MessageChannelEntity } from 'src/engine/metadata-modules/message-cimport { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';-import { type WorkspaceEntityManager } from 'src/engine/twenty-orm/entity-manager/workspace-entity-manager';import { GlobalWorkspaceOrmManager } from 'src/engine/twenty-orm/global-workspace-datasource/global-workspace-orm.manager';import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';import { type ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';@@ -60,11 +59,8 @@ export class MessagingSaveMessagesAndEnqueueContactCreationService {const savedMessagesResult =await this.globalWorkspaceOrmManager.executeInWorkspaceContext(async () => {- const workspaceDataSource =- await this.globalWorkspaceOrmManager.getGlobalWorkspaceDataSourceWithEntityMetadatas();-- return workspaceDataSource?.transaction(- async (transactionManager: WorkspaceEntityManager) => {+ return this.globalWorkspaceOrmManager.runInWorkspaceTransaction(+ async (transactionScope) => {const {messageExternalIdsAndIdsMap,messageExternalIdToMessageChannelMessageAssociationIdMap,@@ -72,7 +68,7 @@ export class MessagingSaveMessagesAndEnqueueContactCreationService {} = await this.messageService.saveMessagesWithinTransaction(messagesToSave,messageChannel.id,- transactionManager,+ transactionScope,workspaceId,);@@ -132,7 +128,7 @@ export class MessagingSaveMessagesAndEnqueueContactCreationService {await this.messageParticipantService.saveMessageParticipants(participantsWithMessageId,workspaceId,- transactionManager,+ transactionScope,);const folderAssociations: MessageChannelMessageAssociationFolderAssociation[] =@@ -163,7 +159,7 @@ export class MessagingSaveMessagesAndEnqueueContactCreationService {await this.messageFolderAssociationService.saveMessageFolderAssociations(folderAssociations,workspaceId,- transactionManager,+ transactionScope,);return {diff --git a/packages/twenty-server/src/modules/messaging/message-outbound-manager/services/messaging-draft-send.service.ts b/packages/twenty-server/src/modules/messaging/message-outbound-manager/services/messaging-draft-send.service.tsindex 2904809bf30..11359067dc5 100644--- a/packages/twenty-server/src/modules/messaging/message-outbound-manager/services/messaging-draft-send.service.ts+++ b/packages/twenty-server/src/modules/messaging/message-outbound-manager/services/messaging-draft-send.service.ts@@ -75,7 +75,7 @@ export class MessagingDraftSendService {const association =await messageChannelMessageAssociationRepository.findOne({where: { messageExternalId },- relations: ['message'],+ relations: { message: true },});return association?.message?.messageThreadId ?? undefined;diff --git a/packages/twenty-server/src/modules/messaging/message-participant-manager/services/messaging-message-participant.service.ts b/packages/twenty-server/src/modules/messaging/message-participant-manager/services/messaging-message-participant.service.tsindex 642b5d6d2ac..57dbf2d2f3e 100644--- a/packages/twenty-server/src/modules/messaging/message-participant-manager/services/messaging-message-participant.service.ts+++ b/packages/twenty-server/src/modules/messaging/message-participant-manager/services/messaging-message-participant.service.ts@@ -2,8 +2,8 @@ import { Injectable } from '@nestjs/common';import { In } from 'typeorm';-import { type WorkspaceEntityManager } from 'src/engine/twenty-orm/entity-manager/workspace-entity-manager';import { GlobalWorkspaceOrmManager } from 'src/engine/twenty-orm/global-workspace-datasource/global-workspace-orm.manager';+import { type WorkspaceTransactionScope } from 'src/engine/twenty-orm/global-workspace-datasource/types/workspace-transaction-scope.type';import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';import { MatchParticipantService } from 'src/modules/match-participant/match-participant.service';import { type MessageParticipantWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-participant.workspace-entity';@@ -19,15 +19,14 @@ export class MessagingMessageParticipantService {public async saveMessageParticipants(participants: ParticipantWithMessageId[],workspaceId: string,- transactionManager?: WorkspaceEntityManager,+ transactionScope: WorkspaceTransactionScope,): Promise<void> {const authContext = buildSystemAuthContext(workspaceId);await this.globalWorkspaceOrmManager.executeInWorkspaceContext(async () => {const messageParticipantRepository =- await this.globalWorkspaceOrmManager.getV1Repository<MessageParticipantWorkspaceEntity>(- workspaceId,+ transactionScope.getRepository<MessageParticipantWorkspaceEntity>('messageParticipant',);@@ -63,15 +62,16 @@ export class MessagingMessageParticipantService {};});- const createdParticipants = await messageParticipantRepository.insert(- participantsToCreate,- transactionManager,- );+ const { identifiers } =+ await messageParticipantRepository.insert(participantsToCreate);++ const createdParticipants = await messageParticipantRepository.find({+ where: { id: In(identifiers.map(({ id }) => id)) },+ });await this.matchParticipantService.matchParticipants({- participants: createdParticipants.raw ?? [],+ participants: createdParticipants,objectMetadataName: 'messageParticipant',- transactionManager,matchWith: 'workspaceMemberAndPerson',workspaceId,});diff --git a/packages/twenty-server/src/modules/workflow/common/query-hooks/workflow-create-many.post-query.hook.ts b/packages/twenty-server/src/modules/workflow/common/query-hooks/workflow-create-many.post-query.hook.tsindex 39c159b1239..15517ec68d0 100644--- a/packages/twenty-server/src/modules/workflow/common/query-hooks/workflow-create-many.post-query.hook.ts+++ b/packages/twenty-server/src/modules/workflow/common/query-hooks/workflow-create-many.post-query.hook.ts@@ -52,16 +52,13 @@ export class WorkflowCreateManyPostQueryHook implements WorkspacePostQueryHookInfor (const workflow of payload) {await this.workflowVersionCoreSyncService.writeWorkflowVersionAndMirror(workspace.id,- async (workflowVersionRepository, entityManager) => {- const insertResult = await workflowVersionRepository.insert(- {- workflowId: workflow.id,- status: WorkflowVersionStatus.DRAFT,- name: 'v1',- position,- },- entityManager,- );+ async (workflowVersionRepository) => {+ const insertResult = await workflowVersionRepository.insert({+ workflowId: workflow.id,+ status: WorkflowVersionStatus.DRAFT,+ name: 'v1',+ position,+ });return (insertResult.generatedMaps[0] as WorkflowVersionWorkspaceEntitydiff --git a/packages/twenty-server/src/modules/workflow/common/query-hooks/workflow-create-one.post-query.hook.ts b/packages/twenty-server/src/modules/workflow/common/query-hooks/workflow-create-one.post-query.hook.tsindex ae9495f132d..db668501b82 100644--- a/packages/twenty-server/src/modules/workflow/common/query-hooks/workflow-create-one.post-query.hook.ts+++ b/packages/twenty-server/src/modules/workflow/common/query-hooks/workflow-create-one.post-query.hook.ts@@ -37,7 +37,7 @@ export class WorkflowCreateOnePostQueryHook implements WorkspacePostQueryHookInsawait this.workflowVersionCoreSyncService.writeWorkflowVersionAndMirror(workspace.id,- async (workflowVersionRepository, entityManager) => {+ async (workflowVersionRepository) => {const position = await this.recordPositionService.buildRecordPosition({value: 'first',objectMetadata: {@@ -47,15 +47,12 @@ export class WorkflowCreateOnePostQueryHook implements WorkspacePostQueryHookInsworkspaceId: workspace.id,});- const insertResult = await workflowVersionRepository.insert(- {- workflowId: workflow.id,- status: WorkflowVersionStatus.DRAFT,- name: 'v1',- position,- },- entityManager,- );+ const insertResult = await workflowVersionRepository.insert({+ workflowId: workflow.id,+ status: WorkflowVersionStatus.DRAFT,+ name: 'v1',+ position,+ });return (insertResult.generatedMaps[0] as WorkflowVersionWorkspaceEntity).id;diff --git a/packages/twenty-server/src/modules/workflow/common/workspace-services/workflow-common.workspace-service.ts b/packages/twenty-server/src/modules/workflow/common/workspace-services/workflow-common.workspace-service.tsindex 4e355c995d5..25e17fb550c 100644--- a/packages/twenty-server/src/modules/workflow/common/workspace-services/workflow-common.workspace-service.ts+++ b/packages/twenty-server/src/modules/workflow/common/workspace-services/workflow-common.workspace-service.ts@@ -82,7 +82,7 @@ export class WorkflowCommonWorkspaceService {return this.globalWorkspaceOrmManager.executeInWorkspaceContext(async () => {const workflowVersionRepository =- await this.globalWorkspaceOrmManager.getV1Repository<WorkflowVersionWorkspaceEntity>(+ await this.globalWorkspaceOrmManager.getRepository<WorkflowVersionWorkspaceEntity>(workspaceId,'workflowVersion',{ shouldBypassPermissionChecks: true },@@ -167,7 +167,7 @@ export class WorkflowCommonWorkspaceService {await this.globalWorkspaceOrmManager.executeInWorkspaceContext(async () => {const workflowRepository =- await this.globalWorkspaceOrmManager.getV1Repository<WorkflowWorkspaceEntity>(+ await this.globalWorkspaceOrmManager.getRepository<WorkflowWorkspaceEntity>(workspaceId,'workflow',{ shouldBypassPermissionChecks: true },@@ -320,21 +320,21 @@ export class WorkflowCommonWorkspaceService {await this.globalWorkspaceOrmManager.executeInWorkspaceContext(async () => {const workflowVersionRepository =- await this.globalWorkspaceOrmManager.getV1Repository<WorkflowVersionWorkspaceEntity>(+ await this.globalWorkspaceOrmManager.getRepository<WorkflowVersionWorkspaceEntity>(workspaceId,'workflowVersion',{ shouldBypassPermissionChecks: true },);const workflowRunRepository =- await this.globalWorkspaceOrmManager.getV1Repository<WorkflowRunWorkspaceEntity>(+ await this.globalWorkspaceOrmManager.getRepository<WorkflowRunWorkspaceEntity>(workspaceId,'workflowRun',{ shouldBypassPermissionChecks: true },);const workflowAutomatedTriggerRepository =- await this.globalWorkspaceOrmManager.getV1Repository<WorkflowAutomatedTriggerWorkspaceEntity>(+ await this.globalWorkspaceOrmManager.getRepository<WorkflowAutomatedTriggerWorkspaceEntity>(workspaceId,'workflowAutomatedTrigger',{ shouldBypassPermissionChecks: true },@@ -414,72 +414,50 @@ export class WorkflowCommonWorkspaceService {return;}- const workflowRepository =- await this.globalWorkspaceOrmManager.getV1Repository<WorkflowWorkspaceEntity>(- workspaceId,- 'workflow',- { shouldBypassPermissionChecks: true },- );-const workflowVersions = await workflowVersionRepository.find({where: { workflowId },withDeleted: true,});- const workspaceDataSource =- await this.globalWorkspaceOrmManager.getGlobalWorkspaceDataSourceWithEntityMetadatas();-- const queryRunner = workspaceDataSource.createQueryRunner();-- await queryRunner.connect();- await queryRunner.startTransaction();+ await this.globalWorkspaceOrmManager.runInWorkspaceTransaction(+ async ({ getRepository }) => {+ const workflowRepository = getRepository<WorkflowWorkspaceEntity>(+ 'workflow',+ { shouldBypassPermissionChecks: true },+ );+ const transactionalWorkflowVersionRepository =+ getRepository<WorkflowVersionWorkspaceEntity>('workflowVersion', {+ shouldBypassPermissionChecks: true,+ });- try {- const workflow = await workflowRepository.findOne(- {+ const workflow = await workflowRepository.findOne({where: { id: workflowId },withDeleted: true,- },- queryRunner.manager,- );+ });- if (workflow?.statuses?.includes(WorkflowStatus.ACTIVE)) {- const newStatuses = [- ...workflow.statuses.filter(- (status) => status !== WorkflowStatus.ACTIVE,- ),- WorkflowStatus.DEACTIVATED,- ];+ if (workflow?.statuses?.includes(WorkflowStatus.ACTIVE)) {+ const newStatuses = [+ ...workflow.statuses.filter(+ (status) => status !== WorkflowStatus.ACTIVE,+ ),+ WorkflowStatus.DEACTIVATED,+ ];- await workflowRepository.update(- workflowId,- { statuses: newStatuses },- undefined,- queryRunner.manager,- );- }-- for (const workflowVersion of workflowVersions) {- if (workflowVersion.status === WorkflowVersionStatus.ACTIVE) {- await workflowVersionRepository.update(- workflowVersion.id,- { status: WorkflowVersionStatus.DEACTIVATED },- undefined,- queryRunner.manager,- );+ await workflowRepository.update(workflowId, {+ statuses: newStatuses,+ });}- }-- await queryRunner.commitTransaction();- } catch (error) {- if (queryRunner.isTransactionActive) {- await queryRunner.rollbackTransaction();- }- throw error;- } finally {- await queryRunner.release();- }+ for (const workflowVersion of workflowVersions) {+ if (workflowVersion.status === WorkflowVersionStatus.ACTIVE) {+ await transactionalWorkflowVersionRepository.update(+ workflowVersion.id,+ { status: WorkflowVersionStatus.DEACTIVATED },+ );+ }+ }+ },+ );for (const workflowVersion of workflowVersions) {if (workflowVersion.status === WorkflowVersionStatus.ACTIVE) {diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-edge/workflow-version-edge.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-edge/workflow-version-edge.workspace-service.tsindex cdf4c25fe17..4f2b86fefac 100644--- a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-edge/workflow-version-edge.workspace-service.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-edge/workflow-version-edge.workspace-service.ts@@ -187,13 +187,10 @@ export class WorkflowVersionEdgeWorkspaceService {await this.workflowVersionCoreSyncService.writeWorkflowVersionAndMirror(workspaceId,- async (workflowVersionRepository, entityManager) => {- await workflowVersionRepository.update(- workflowVersion.id,- { trigger: updatedTrigger },- undefined,- entityManager,- );+ async (workflowVersionRepository) => {+ await workflowVersionRepository.update(workflowVersion.id, {+ trigger: updatedTrigger,+ });return workflowVersion.id;},@@ -263,13 +260,10 @@ export class WorkflowVersionEdgeWorkspaceService {if (shouldPersist) {await this.workflowVersionCoreSyncService.writeWorkflowVersionAndMirror(workspaceId,- async (workflowVersionRepository, entityManager) => {- await workflowVersionRepository.update(- workflowVersion.id,- { steps: updatedSteps },- undefined,- entityManager,- );+ async (workflowVersionRepository) => {+ await workflowVersionRepository.update(workflowVersion.id, {+ steps: updatedSteps,+ });return workflowVersion.id;},@@ -410,13 +404,10 @@ export class WorkflowVersionEdgeWorkspaceService {await this.workflowVersionCoreSyncService.writeWorkflowVersionAndMirror(workspaceId,- async (workflowVersionRepository, entityManager) => {- await workflowVersionRepository.update(- workflowVersion.id,- { trigger: updatedTrigger },- undefined,- entityManager,- );+ async (workflowVersionRepository) => {+ await workflowVersionRepository.update(workflowVersion.id, {+ trigger: updatedTrigger,+ });return workflowVersion.id;},@@ -500,13 +491,10 @@ export class WorkflowVersionEdgeWorkspaceService {await this.workflowVersionCoreSyncService.writeWorkflowVersionAndMirror(workspaceId,- async (workflowVersionRepository, entityManager) => {- await workflowVersionRepository.update(- workflowVersion.id,- { steps: updatedSteps },- undefined,- entityManager,- );+ async (workflowVersionRepository) => {+ await workflowVersionRepository.update(workflowVersion.id, {+ steps: updatedSteps,+ });return workflowVersion.id;},diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-helpers.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-helpers.workspace-service.tsindex 77576f4edac..94cb7cd89a3 100644--- a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-helpers.workspace-service.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-helpers.workspace-service.ts@@ -58,13 +58,8 @@ export class WorkflowVersionStepHelpersWorkspaceService {await this.workflowVersionCoreSyncService.writeWorkflowVersionAndMirror(workspaceId,- async (workflowVersionRepository, entityManager) => {- await workflowVersionRepository.update(- workflowVersionId,- updateData,- undefined,- entityManager,- );+ async (workflowVersionRepository) => {+ await workflowVersionRepository.update(workflowVersionId, updateData);return workflowVersionId;},diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service.tsindex bb754012025..c324f32df0c 100644--- a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service.ts@@ -973,13 +973,10 @@ export class WorkflowVersionStepOperationsWorkspaceService {await this.workflowVersionCoreSyncService.writeWorkflowVersionAndMirror(workspaceId,- async (scopedRepository, entityManager) => {- await scopedRepository.update(- workflowVersion.id,- { steps: [...existingSteps, emptyNodeStep] },- undefined,- entityManager,- );+ async (scopedRepository) => {+ await scopedRepository.update(workflowVersion.id, {+ steps: [...existingSteps, emptyNodeStep],+ });return workflowVersion.id;},@@ -1065,13 +1062,10 @@ export class WorkflowVersionStepOperationsWorkspaceService {await this.workflowVersionCoreSyncService.writeWorkflowVersionAndMirror(workspaceId,- async (scopedRepository, entityManager) => {- await scopedRepository.update(- workflowVersion.id,- { steps: [...existingSteps, ifEmptyNode, elseEmptyNode] },- undefined,- entityManager,- );+ async (scopedRepository) => {+ await scopedRepository.update(workflowVersion.id, {+ steps: [...existingSteps, ifEmptyNode, elseEmptyNode],+ });return workflowVersion.id;},diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version/workflow-version.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version/workflow-version.workspace-service.tsindex 90ef0d36f85..7d2b5faf49e 100644--- a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version/workflow-version.workspace-service.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version/workflow-version.workspace-service.ts@@ -109,16 +109,11 @@ export class WorkflowVersionWorkspaceService {await this.workflowVersionCoreSyncService.writeWorkflowVersionAndMirror(workspaceId,- async (scopedRepository, entityManager) => {- await scopedRepository.update(- existingDraftVersion.id,- {- steps: newWorkflowVersionSteps,- trigger: newWorkflowVersionTrigger,- },- undefined,- entityManager,- );+ async (scopedRepository) => {+ await scopedRepository.update(existingDraftVersion.id, {+ steps: newWorkflowVersionSteps,+ trigger: newWorkflowVersionTrigger,+ });return existingDraftVersion.id;},@@ -151,18 +146,15 @@ export class WorkflowVersionWorkspaceService {await this.workflowVersionCoreSyncService.writeWorkflowVersionAndMirror(workspaceId,- async (scopedRepository, entityManager) => {- const insertResult = await scopedRepository.insert(- {- workflowId,- name: `v${workflowVersionsCount + 1}`,- status: WorkflowVersionStatus.DRAFT,- steps: newWorkflowVersionSteps,- trigger: newWorkflowVersionTrigger,- position,- },- entityManager,- );+ async (scopedRepository) => {+ const insertResult = await scopedRepository.insert({+ workflowId,+ name: `v${workflowVersionsCount + 1}`,+ status: WorkflowVersionStatus.DRAFT,+ steps: newWorkflowVersionSteps,+ trigger: newWorkflowVersionTrigger,+ position,+ });draftWorkflowVersion = insertResult.generatedMaps[0] as WorkflowVersionWorkspaceEntity;@@ -339,18 +331,15 @@ export class WorkflowVersionWorkspaceService {await this.workflowVersionCoreSyncService.writeWorkflowVersionAndMirror(workspaceId,- async (scopedRepository, entityManager) => {- const insertVersionResult = await scopedRepository.insert(- {- workflowId: newWorkflowId,- name: 'v1',- status: WorkflowVersionStatus.DRAFT,- position: versionPosition,- steps: remappedSteps,- trigger: remappedTrigger,- },- entityManager,- );+ async (scopedRepository) => {+ const insertVersionResult = await scopedRepository.insert({+ workflowId: newWorkflowId,+ name: 'v1',+ status: WorkflowVersionStatus.DRAFT,+ position: versionPosition,+ steps: remappedSteps,+ trigger: remappedTrigger,+ });newDraftVersion = insertVersionResult.generatedMaps[0] as WorkflowVersionWorkspaceEntity;@@ -438,13 +427,8 @@ export class WorkflowVersionWorkspaceService {await this.workflowVersionCoreSyncService.writeWorkflowVersionAndMirror(workspaceId,- async (scopedRepository, entityManager) => {- await scopedRepository.update(- workflowVersionId,- updatePayload,- undefined,- entityManager,- );+ async (scopedRepository) => {+ await scopedRepository.update(workflowVersionId, updatePayload);return workflowVersionId;},diff --git a/packages/twenty-server/src/modules/workflow/workflow-tools/tools/create-complete-workflow.tool.ts b/packages/twenty-server/src/modules/workflow/workflow-tools/tools/create-complete-workflow.tool.tsindex 9753cb1fa0d..854e29c9ede 100644--- a/packages/twenty-server/src/modules/workflow/workflow-tools/tools/create-complete-workflow.tool.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-tools/tools/create-complete-workflow.tool.ts@@ -269,7 +269,7 @@ const createWorkflowVersion = async ({await deps.workflowVersionCoreSyncService.writeWorkflowVersionAndMirror(context.workspaceId,- async (workflowVersionRepository, entityManager) => {+ async (workflowVersionRepository) => {const versionPosition =await deps.recordPositionService.buildRecordPosition({value: 'first',@@ -280,18 +280,15 @@ const createWorkflowVersion = async ({workspaceId: context.workspaceId,});- await workflowVersionRepository.insert(- {- id: workflowVersionId,- workflowId,- name: 'v1',- status: WorkflowVersionStatus.DRAFT,- trigger,- steps,- position: versionPosition,- },- entityManager,- );+ await workflowVersionRepository.insert({+ id: workflowVersionId,+ workflowId,+ name: 'v1',+ status: WorkflowVersionStatus.DRAFT,+ trigger,+ steps,+ position: versionPosition,+ });return workflowVersionId;},diff --git a/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/automated-trigger.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/automated-trigger.workspace-service.tsindex 451f8dcc52e..91b7b0074f5 100644--- a/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/automated-trigger.workspace-service.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/automated-trigger.workspace-service.ts@@ -1,8 +1,8 @@import { Injectable } from '@nestjs/common';import { isDefined } from 'twenty-shared/utils';-import { type WorkspaceEntityManager } from 'src/engine/twenty-orm/entity-manager/workspace-entity-manager';import { GlobalWorkspaceOrmManager } from 'src/engine/twenty-orm/global-workspace-datasource/global-workspace-orm.manager';+import { type WorkspaceTransactionScope } from 'src/engine/twenty-orm/global-workspace-datasource/types/workspace-transaction-scope.type';import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';import {type AutomatedTriggerType,@@ -21,25 +21,20 @@ export class AutomatedTriggerWorkspaceService {type,settings,workspaceId,- entityManager,+ transactionScope,}: {workflowId: string;type: AutomatedTriggerType;settings: AutomatedTriggerSettings;workspaceId: string;- entityManager?: WorkspaceEntityManager;+ transactionScope?: WorkspaceTransactionScope;}) {- const workflowAutomatedTriggerRepository =- await this.globalWorkspaceOrmManager.getRepository<WorkflowAutomatedTriggerWorkspaceEntity>(- workspaceId,- 'workflowAutomatedTrigger',- );-- if (isDefined(entityManager)) {- await workflowAutomatedTriggerRepository.insert(- { type, settings, workflowId },- entityManager,- );+ if (isDefined(transactionScope)) {+ await transactionScope+ .getRepository<WorkflowAutomatedTriggerWorkspaceEntity>(+ 'workflowAutomatedTrigger',+ )+ .insert({ type, settings, workflowId });return;}@@ -47,6 +42,12 @@ export class AutomatedTriggerWorkspaceService {const authContext = buildSystemAuthContext(workspaceId);await this.globalWorkspaceOrmManager.executeInWorkspaceContext(async () => {+ const workflowAutomatedTriggerRepository =+ await this.globalWorkspaceOrmManager.getRepository<WorkflowAutomatedTriggerWorkspaceEntity>(+ workspaceId,+ 'workflowAutomatedTrigger',+ );+await workflowAutomatedTriggerRepository.insert({type,settings,@@ -58,23 +59,18 @@ export class AutomatedTriggerWorkspaceService {async deleteAutomatedTrigger({workflowId,workspaceId,- entityManager,+ transactionScope,}: {workflowId: string;workspaceId: string;- entityManager?: WorkspaceEntityManager;+ transactionScope?: WorkspaceTransactionScope;}) {- const workflowAutomatedTriggerRepository =- await this.globalWorkspaceOrmManager.getRepository<WorkflowAutomatedTriggerWorkspaceEntity>(- workspaceId,- 'workflowAutomatedTrigger',- );-- if (isDefined(entityManager)) {- await workflowAutomatedTriggerRepository.delete(- { workflowId },- entityManager,- );+ if (isDefined(transactionScope)) {+ await transactionScope+ .getRepository<WorkflowAutomatedTriggerWorkspaceEntity>(+ 'workflowAutomatedTrigger',+ )+ .delete({ workflowId });return;}@@ -82,6 +78,12 @@ export class AutomatedTriggerWorkspaceService {const authContext = buildSystemAuthContext(workspaceId);await this.globalWorkspaceOrmManager.executeInWorkspaceContext(async () => {+ const workflowAutomatedTriggerRepository =+ await this.globalWorkspaceOrmManager.getRepository<WorkflowAutomatedTriggerWorkspaceEntity>(+ workspaceId,+ 'workflowAutomatedTrigger',+ );+await workflowAutomatedTriggerRepository.delete({ workflowId });}, authContext);}diff --git a/packages/twenty-server/src/modules/workflow/workflow-trigger/workspace-services/workflow-trigger.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-trigger/workspace-services/workflow-trigger.workspace-service.tsindex f55030154a6..05146cd1a39 100644--- a/packages/twenty-server/src/modules/workflow/workflow-trigger/workspace-services/workflow-trigger.workspace-service.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-trigger/workspace-services/workflow-trigger.workspace-service.ts@@ -11,7 +11,7 @@ import { WorkflowVersionCoreSyncService } from 'src/engine/core-modules/workflowimport { CommandMenuItemService } from 'src/engine/metadata-modules/command-menu-item/command-menu-item.service';import { CommandMenuItemAvailabilityType } from 'src/engine/metadata-modules/command-menu-item/enums/command-menu-item-availability-type.enum';import { EngineComponentKey } from 'src/engine/metadata-modules/command-menu-item/enums/engine-component-key.enum';-import { type WorkspaceEntityManager } from 'src/engine/twenty-orm/entity-manager/workspace-entity-manager';+import { type WorkspaceTransactionScope } from 'src/engine/twenty-orm/global-workspace-datasource/types/workspace-transaction-scope.type';import { GlobalWorkspaceOrmManager } from 'src/engine/twenty-orm/global-workspace-datasource/global-workspace-orm.manager';import { type WorkspaceRepository } from 'src/engine/twenty-orm/repository/workspace.repository';import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';@@ -103,7 +103,7 @@ export class WorkflowTriggerWorkspaceService {return this.globalWorkspaceOrmManager.executeInWorkspaceContext(async () => {const workflowVersionRepository =- await this.globalWorkspaceOrmManager.getV1Repository<WorkflowVersionWorkspaceEntity>(+ await this.globalWorkspaceOrmManager.getRepository<WorkflowVersionWorkspaceEntity>(workspaceId,'workflowVersion',{ shouldBypassPermissionChecks: true },@@ -121,7 +121,7 @@ export class WorkflowTriggerWorkspaceService {);const workflowRepository =- await this.globalWorkspaceOrmManager.getV1Repository<WorkflowWorkspaceEntity>(+ await this.globalWorkspaceOrmManager.getRepository<WorkflowWorkspaceEntity>(workspaceId,'workflow',{ shouldBypassPermissionChecks: true },@@ -158,7 +158,6 @@ export class WorkflowTriggerWorkspaceService {await this.performActivationSteps(workflow,workflowVersion,- workflowRepository,workflowVersionRepository,workspaceId,);@@ -213,7 +212,7 @@ export class WorkflowTriggerWorkspaceService {return this.globalWorkspaceOrmManager.executeInWorkspaceContext(async () => {const workflowVersionRepository =- await this.globalWorkspaceOrmManager.getV1Repository<WorkflowVersionWorkspaceEntity>(+ await this.globalWorkspaceOrmManager.getRepository<WorkflowVersionWorkspaceEntity>(workspaceId,'workflowVersion',{ shouldBypassPermissionChecks: true },@@ -248,13 +247,13 @@ export class WorkflowTriggerWorkspaceService {private async mirrorVersionStatusChangeInTransaction(workflowVersionId: string,workspaceId: string,- workflowVersionRepository: WorkspaceRepository<WorkflowVersionWorkspaceEntity>,- entityManager: WorkspaceEntityManager,+ transactionScope: WorkspaceTransactionScope,): Promise<void> {- const workflowVersion = await workflowVersionRepository.findOne(- { where: { id: workflowVersionId } },- entityManager,- );+ const workflowVersion = await transactionScope+ .getRepository<WorkflowVersionWorkspaceEntity>('workflowVersion', {+ shouldBypassPermissionChecks: true,+ })+ .findOne({ where: { id: workflowVersionId } });if (!isDefined(workflowVersion)) {return;@@ -262,7 +261,7 @@ export class WorkflowTriggerWorkspaceService {await this.workflowVersionCoreSyncService.mirrorWorkflowVersionWrite({workspaceId,- entityManager,+ transactionScope,workflowVersion,});}@@ -270,7 +269,6 @@ export class WorkflowTriggerWorkspaceService {private async performActivationSteps(workflow: WorkflowWorkspaceEntity,workflowVersion: WorkflowVersionWorkspaceEntity,- workflowRepository: WorkspaceRepository<WorkflowWorkspaceEntity>,workflowVersionRepository: WorkspaceRepository<WorkflowVersionWorkspaceEntity>,workspaceId: string,) {@@ -293,88 +291,72 @@ export class WorkflowTriggerWorkspaceService {workspaceId,);- const workspaceDataSource =- await this.globalWorkspaceOrmManager.getGlobalWorkspaceDataSourceWithEntityMetadatas();+ await this.globalWorkspaceOrmManager.runInWorkspaceTransaction(+ async (transactionScope) => {+ const transactionalWorkflowRepository =+ transactionScope.getRepository<WorkflowWorkspaceEntity>('workflow', {+ shouldBypassPermissionChecks: true,+ });+ const transactionalWorkflowVersionRepository =+ transactionScope.getRepository<WorkflowVersionWorkspaceEntity>(+ 'workflowVersion',+ { shouldBypassPermissionChecks: true },+ );- const queryRunner = workspaceDataSource.createQueryRunner();+ if (workflow.lastPublishedVersionId !== workflowVersion.id) {+ if (workflow.lastPublishedVersionId) {+ await transactionalWorkflowVersionRepository.update(+ { id: workflow.lastPublishedVersionId },+ { status: WorkflowVersionStatus.ARCHIVED },+ );- await queryRunner.connect();- await queryRunner.startTransaction();+ await this.mirrorVersionStatusChangeInTransaction(+ workflow.lastPublishedVersionId,+ workspaceId,+ transactionScope,+ );+ }- try {- if (workflow.lastPublishedVersionId !== workflowVersion.id) {- if (workflow.lastPublishedVersionId) {- await workflowVersionRepository.update(- { id: workflow.lastPublishedVersionId },- { status: WorkflowVersionStatus.ARCHIVED },- undefined,- queryRunner.manager,+ await transactionalWorkflowRepository.update(+ { id: workflow.id },+ { lastPublishedVersionId: workflowVersion.id },);+ }- await this.mirrorVersionStatusChangeInTransaction(- workflow.lastPublishedVersionId,- workspaceId,- workflowVersionRepository,- queryRunner.manager,+ const activeWorkflowVersions =+ await transactionalWorkflowVersionRepository.find({+ where: {+ workflowId: workflowVersion.workflowId,+ status: WorkflowVersionStatus.ACTIVE,+ },+ });++ if (activeWorkflowVersions.length > 0) {+ throw new WorkflowTriggerException(+ 'Cannot have more than one active workflow version',+ WorkflowTriggerExceptionCode.FORBIDDEN,+ {+ userFriendlyMessage: msg`Cannot have more than one active workflow version`,+ },);}- await workflowRepository.update(- { id: workflow.id },- { lastPublishedVersionId: workflowVersion.id },- undefined,- queryRunner.manager,+ await transactionalWorkflowVersionRepository.update(+ { id: workflowVersion.id },+ { status: WorkflowVersionStatus.ACTIVE },);- }- const activeWorkflowVersions = await workflowVersionRepository.find(- {- where: {- workflowId: workflowVersion.workflowId,- status: WorkflowVersionStatus.ACTIVE,- },- },- queryRunner.manager,- );-- if (activeWorkflowVersions.length > 0) {- throw new WorkflowTriggerException(- 'Cannot have more than one active workflow version',- WorkflowTriggerExceptionCode.FORBIDDEN,- {- userFriendlyMessage: msg`Cannot have more than one active workflow version`,- },+ await this.mirrorVersionStatusChangeInTransaction(+ workflowVersion.id,+ workspaceId,+ transactionScope,);- }-- await workflowVersionRepository.update(- { id: workflowVersion.id },- { status: WorkflowVersionStatus.ACTIVE },- undefined,- queryRunner.manager,- );-- await this.mirrorVersionStatusChangeInTransaction(- workflowVersion.id,- workspaceId,- workflowVersionRepository,- queryRunner.manager,- );-- await this.enableAutomatedTrigger(workflowVersion, workspaceId, {- entityManager: queryRunner.manager,- });- await queryRunner.commitTransaction();- } catch (error) {- if (queryRunner.isTransactionActive) {- await queryRunner.rollbackTransaction();- }-- throw error;- } finally {- await queryRunner.release();- }+ await this.enableAutomatedTrigger(workflowVersion, workspaceId, {+ transactionScope,+ });+ },+ );await this.workflowVersionCoreSyncService.invalidateAutomatedTriggerMaps(workspaceId,@@ -407,43 +389,28 @@ export class WorkflowTriggerWorkspaceService {await this.deleteCommandMenuItem(workflowVersion, workspaceId);- const workspaceDataSource =- await this.globalWorkspaceOrmManager.getGlobalWorkspaceDataSourceWithEntityMetadatas();-- const queryRunner = workspaceDataSource.createQueryRunner();-- await queryRunner.connect();- await queryRunner.startTransaction();-- try {- await workflowVersionRepository.update(- { id: workflowVersion.id },- { status: WorkflowVersionStatus.DEACTIVATED },- undefined,- queryRunner.manager,- );-- await this.mirrorVersionStatusChangeInTransaction(- workflowVersion.id,- workspaceId,- workflowVersionRepository,- queryRunner.manager,- );-- await this.disableAutomatedTrigger(workflowVersion, workspaceId, {- entityManager: queryRunner.manager,- });+ await this.globalWorkspaceOrmManager.runInWorkspaceTransaction(+ async (transactionScope) => {+ await transactionScope+ .getRepository<WorkflowVersionWorkspaceEntity>('workflowVersion', {+ shouldBypassPermissionChecks: true,+ })+ .update(+ { id: workflowVersion.id },+ { status: WorkflowVersionStatus.DEACTIVATED },+ );- await queryRunner.commitTransaction();- } catch (error) {- if (queryRunner.isTransactionActive) {- await queryRunner.rollbackTransaction();- }+ await this.mirrorVersionStatusChangeInTransaction(+ workflowVersion.id,+ workspaceId,+ transactionScope,+ );- throw error;- } finally {- await queryRunner.release();- }+ await this.disableAutomatedTrigger(workflowVersion, workspaceId, {+ transactionScope,+ });+ },+ );await this.workflowVersionCoreSyncService.invalidateAutomatedTriggerMaps(workspaceId,@@ -583,7 +550,7 @@ export class WorkflowTriggerWorkspaceService {workflowVersion: WorkflowVersionWorkspaceEntity,workspaceId: string,transactionContext?: {- entityManager: WorkspaceEntityManager;+ transactionScope: WorkspaceTransactionScope;},) {assertWorkflowVersionTriggerIsDefined(workflowVersion);@@ -601,7 +568,7 @@ export class WorkflowTriggerWorkspaceService {type: AutomatedTriggerType.DATABASE_EVENT,settings,workspaceId,- entityManager: transactionContext?.entityManager,+ transactionScope: transactionContext?.transactionScope,});return;@@ -614,7 +581,7 @@ export class WorkflowTriggerWorkspaceService {type: AutomatedTriggerType.CRON,settings: { pattern },workspaceId,- entityManager: transactionContext?.entityManager,+ transactionScope: transactionContext?.transactionScope,});const cachedTrigger: CachedCronTrigger = {@@ -640,7 +607,7 @@ export class WorkflowTriggerWorkspaceService {workflowVersion: WorkflowVersionWorkspaceEntity,workspaceId: string,transactionContext?: {- entityManager: WorkspaceEntityManager;+ transactionScope: WorkspaceTransactionScope;},) {assertWorkflowVersionTriggerIsDefined(workflowVersion);@@ -650,7 +617,7 @@ export class WorkflowTriggerWorkspaceService {await this.automatedTriggerWorkspaceService.deleteAutomatedTrigger({workflowId: workflowVersion.workflowId,workspaceId,- entityManager: transactionContext?.entityManager,+ transactionScope: transactionContext?.transactionScope,});return;@@ -658,7 +625,7 @@ export class WorkflowTriggerWorkspaceService {await this.automatedTriggerWorkspaceService.deleteAutomatedTrigger({workflowId: workflowVersion.workflowId,workspaceId,- entityManager: transactionContext?.entityManager,+ transactionScope: transactionContext?.transactionScope,});await this.cacheStorageService.hashDelete({