Rename serverlessFunction to logicFunction (#17494)
## Summary Rename "Serverless Function" to "Logic Function" across the codebase for clearer naming. ### Environment Variable Changes | Old | New | |-----|-----| | `SERVERLESS_TYPE` | `LOGIC_FUNCTION_TYPE` | | `SERVERLESS_LAMBDA_REGION` | `LOGIC_FUNCTION_LAMBDA_REGION` | | `SERVERLESS_LAMBDA_ROLE` | `LOGIC_FUNCTION_LAMBDA_ROLE` | | `SERVERLESS_LAMBDA_SUBHOSTING_URL` | `LOGIC_FUNCTION_LAMBDA_SUBHOSTING_URL` | | `SERVERLESS_LAMBDA_ACCESS_KEY_ID` | `LOGIC_FUNCTION_LAMBDA_ACCESS_KEY_ID` | | `SERVERLESS_LAMBDA_SECRET_ACCESS_KEY` | `LOGIC_FUNCTION_LAMBDA_SECRET_ACCESS_KEY` | ### Breaking Changes - Environment variables must be updated in production deployments - Database migration renames `serverlessFunction` → `logicFunction` tables
This commit is contained in:
+9
@@ -0,0 +1,9 @@
|
||||
// Default tool input schema matching the seed-project template
|
||||
// Template params: { a: string; b: number; }
|
||||
export const DEFAULT_TOOL_INPUT_SCHEMA = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
a: { type: 'string' },
|
||||
b: { type: 'number' },
|
||||
},
|
||||
};
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
import { type FlatLogicFunction } from 'src/engine/metadata-modules/logic-function/types/flat-logic-function.type';
|
||||
|
||||
export const FLAT_LOGIC_FUNCTION_EDITABLE_PROPERTIES = [
|
||||
'name',
|
||||
'description',
|
||||
'timeoutSeconds',
|
||||
'checksum',
|
||||
'code',
|
||||
'sourceHandlerPath',
|
||||
'handlerName',
|
||||
'toolInputSchema',
|
||||
'isTool',
|
||||
] as const satisfies (keyof FlatLogicFunction)[];
|
||||
+1
@@ -0,0 +1 @@
|
||||
export const LOGIC_FUNCTION_PUBLISHED = 'logic_function_published';
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
import { ID, InputType } from '@nestjs/graphql';
|
||||
|
||||
import { IDField } from '@ptc-org/nestjs-query-graphql';
|
||||
|
||||
@InputType()
|
||||
export class BuildDraftLogicFunctionInput {
|
||||
@IDField(() => ID, { description: 'The id of the function.' })
|
||||
id!: string;
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
import { Field, HideField, InputType } from '@nestjs/graphql';
|
||||
|
||||
import {
|
||||
IsBoolean,
|
||||
IsNotEmpty,
|
||||
IsNumber,
|
||||
IsObject,
|
||||
IsOptional,
|
||||
IsString,
|
||||
Max,
|
||||
Min,
|
||||
} from 'class-validator';
|
||||
import graphqlTypeJson from 'graphql-type-json';
|
||||
import { Sources } from 'twenty-shared/types';
|
||||
|
||||
@InputType()
|
||||
export class CreateLogicFunctionInput {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@Field()
|
||||
name: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
@Field({ nullable: true })
|
||||
description?: string;
|
||||
|
||||
@IsNumber()
|
||||
@Field({ nullable: true })
|
||||
@Min(1)
|
||||
@Max(900)
|
||||
@IsOptional()
|
||||
timeoutSeconds?: number;
|
||||
|
||||
@HideField()
|
||||
applicationId?: string;
|
||||
|
||||
@HideField()
|
||||
universalIdentifier?: string;
|
||||
|
||||
@HideField()
|
||||
logicFunctionLayerId?: string;
|
||||
|
||||
@Field(() => graphqlTypeJson, { nullable: true })
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
code?: Sources;
|
||||
|
||||
@IsString()
|
||||
@Field({ nullable: true })
|
||||
@IsOptional()
|
||||
handlerName?: string;
|
||||
|
||||
@IsString()
|
||||
@Field({ nullable: true })
|
||||
@IsOptional()
|
||||
sourceHandlerPath?: string;
|
||||
|
||||
@IsString()
|
||||
@Field({ nullable: true })
|
||||
@IsOptional()
|
||||
builtHandlerPath?: string;
|
||||
|
||||
@Field(() => graphqlTypeJson, { nullable: true })
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
toolInputSchema?: object;
|
||||
|
||||
@IsBoolean()
|
||||
@Field({ nullable: true })
|
||||
@IsOptional()
|
||||
isTool?: boolean;
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
import { Field, InputType } from '@nestjs/graphql';
|
||||
|
||||
import { IsNotEmpty, IsObject, IsUUID } from 'class-validator';
|
||||
import graphqlTypeJson from 'graphql-type-json';
|
||||
|
||||
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
|
||||
|
||||
@InputType()
|
||||
export class ExecuteLogicFunctionInput {
|
||||
@Field(() => UUIDScalarType, {
|
||||
description: 'Id of the logic function to execute',
|
||||
})
|
||||
@IsNotEmpty()
|
||||
@IsUUID()
|
||||
id: string;
|
||||
|
||||
@Field(() => graphqlTypeJson, {
|
||||
description: 'Payload in JSON format',
|
||||
})
|
||||
@IsObject()
|
||||
payload: JSON;
|
||||
|
||||
@Field(() => String, {
|
||||
nullable: false,
|
||||
description: 'Version of the logic function to execute',
|
||||
defaultValue: 'latest',
|
||||
})
|
||||
version: string;
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
import { Field, ID, InputType } from '@nestjs/graphql';
|
||||
|
||||
import { IDField } from '@ptc-org/nestjs-query-graphql';
|
||||
|
||||
@InputType()
|
||||
export class GetLogicFunctionSourceCodeInput {
|
||||
@IDField(() => ID, { description: 'The id of the function.' })
|
||||
id!: string;
|
||||
|
||||
@Field(() => String, {
|
||||
nullable: false,
|
||||
description: 'The version of the function',
|
||||
defaultValue: 'draft',
|
||||
})
|
||||
version: string;
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
import { Field, ObjectType, registerEnumType } from '@nestjs/graphql';
|
||||
|
||||
import { IsObject, IsOptional } from 'class-validator';
|
||||
import graphqlTypeJson from 'graphql-type-json';
|
||||
|
||||
export enum LogicFunctionExecutionStatus {
|
||||
IDLE = 'IDLE',
|
||||
SUCCESS = 'SUCCESS',
|
||||
ERROR = 'ERROR',
|
||||
}
|
||||
|
||||
registerEnumType(LogicFunctionExecutionStatus, {
|
||||
name: 'LogicFunctionExecutionStatus',
|
||||
description: 'Status of the logic function execution',
|
||||
});
|
||||
|
||||
@ObjectType('LogicFunctionExecutionResult')
|
||||
export class LogicFunctionExecutionResultDTO {
|
||||
@IsObject()
|
||||
@Field(() => graphqlTypeJson, {
|
||||
description: 'Execution result in JSON format',
|
||||
nullable: true,
|
||||
})
|
||||
data?: JSON;
|
||||
|
||||
@Field({ description: 'Execution Logs' })
|
||||
logs: string;
|
||||
|
||||
@Field({ description: 'Execution duration in milliseconds' })
|
||||
duration: number;
|
||||
|
||||
@Field(() => LogicFunctionExecutionStatus, {
|
||||
description: 'Execution status',
|
||||
})
|
||||
status: LogicFunctionExecutionStatus;
|
||||
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
@Field(() => graphqlTypeJson, {
|
||||
description: 'Execution error in JSON format',
|
||||
nullable: true,
|
||||
})
|
||||
error?: {
|
||||
errorType: string;
|
||||
errorMessage: string;
|
||||
stackTrace: string;
|
||||
};
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
import { ID, InputType } from '@nestjs/graphql';
|
||||
|
||||
import { IDField } from '@ptc-org/nestjs-query-graphql';
|
||||
|
||||
@InputType()
|
||||
export class LogicFunctionIdInput {
|
||||
@IDField(() => ID, { description: 'The id of the function.' })
|
||||
id!: string;
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
import { Field, HideField, ObjectType } from '@nestjs/graphql';
|
||||
|
||||
@ObjectType('LogicFunctionLogs')
|
||||
export class LogicFunctionLogsDTO {
|
||||
@Field({ description: 'Execution Logs' })
|
||||
logs: string;
|
||||
|
||||
@HideField()
|
||||
applicationUniversalIdentifier?: string;
|
||||
|
||||
@HideField()
|
||||
applicationId?: string;
|
||||
|
||||
@HideField()
|
||||
name?: string;
|
||||
|
||||
@HideField()
|
||||
id?: string;
|
||||
|
||||
@HideField()
|
||||
universalIdentifier?: string;
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
import { Field, InputType } from '@nestjs/graphql';
|
||||
|
||||
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
|
||||
|
||||
@InputType('LogicFunctionLogsInput')
|
||||
export class LogicFunctionLogsInput {
|
||||
@Field(() => UUIDScalarType, { nullable: true })
|
||||
applicationId?: string;
|
||||
|
||||
@Field(() => UUIDScalarType, { nullable: true })
|
||||
applicationUniversalIdentifier?: string;
|
||||
|
||||
@Field(() => String, { nullable: true })
|
||||
name?: string;
|
||||
|
||||
@Field(() => UUIDScalarType, { nullable: true })
|
||||
id?: string;
|
||||
|
||||
@Field(() => UUIDScalarType, { nullable: true })
|
||||
universalIdentifier?: string;
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
import { Field, HideField, ObjectType } from '@nestjs/graphql';
|
||||
|
||||
import {
|
||||
Authorize,
|
||||
IDField,
|
||||
QueryOptions,
|
||||
} from '@ptc-org/nestjs-query-graphql';
|
||||
import {
|
||||
IsArray,
|
||||
IsBoolean,
|
||||
IsDateString,
|
||||
IsNotEmpty,
|
||||
IsNumber,
|
||||
IsObject,
|
||||
IsOptional,
|
||||
IsString,
|
||||
IsUUID,
|
||||
} from 'class-validator';
|
||||
import graphqlTypeJson from 'graphql-type-json';
|
||||
|
||||
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
|
||||
import {
|
||||
CronTriggerSettings,
|
||||
DatabaseEventTriggerSettings,
|
||||
HttpRouteTriggerSettings,
|
||||
} from 'src/engine/metadata-modules/logic-function/logic-function.entity';
|
||||
|
||||
@ObjectType('LogicFunction')
|
||||
@Authorize({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authorize: (context: any) => ({
|
||||
workspaceId: { eq: context?.req?.workspace?.id },
|
||||
}),
|
||||
})
|
||||
@QueryOptions({
|
||||
defaultResultSize: 10,
|
||||
maxResultsSize: 1000,
|
||||
})
|
||||
export class LogicFunctionDTO {
|
||||
@IsUUID()
|
||||
@IsNotEmpty()
|
||||
@IDField(() => UUIDScalarType)
|
||||
id: string;
|
||||
|
||||
@IsString()
|
||||
@Field()
|
||||
name: string;
|
||||
|
||||
@IsString()
|
||||
@Field({ nullable: true })
|
||||
description?: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@Field()
|
||||
runtime: string;
|
||||
|
||||
@IsNumber()
|
||||
@Field()
|
||||
timeoutSeconds: number;
|
||||
|
||||
@IsString()
|
||||
@Field({ nullable: true })
|
||||
latestVersion?: string;
|
||||
|
||||
@IsString()
|
||||
@Field()
|
||||
sourceHandlerPath: string;
|
||||
|
||||
@IsString()
|
||||
@Field()
|
||||
builtHandlerPath: string;
|
||||
|
||||
@IsString()
|
||||
@Field()
|
||||
handlerName: string;
|
||||
|
||||
@IsArray()
|
||||
@Field(() => [String], { nullable: false })
|
||||
publishedVersions: string[];
|
||||
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
@Field(() => graphqlTypeJson, { nullable: true })
|
||||
toolInputSchema?: object;
|
||||
|
||||
@IsBoolean()
|
||||
@Field()
|
||||
isTool: boolean;
|
||||
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
@Field(() => graphqlTypeJson, { nullable: true })
|
||||
cronTriggerSettings?: CronTriggerSettings;
|
||||
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
@Field(() => graphqlTypeJson, { nullable: true })
|
||||
databaseEventTriggerSettings?: DatabaseEventTriggerSettings;
|
||||
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
@Field(() => graphqlTypeJson, { nullable: true })
|
||||
httpRouteTriggerSettings?: HttpRouteTriggerSettings;
|
||||
|
||||
@IsUUID()
|
||||
@IsOptional()
|
||||
@Field(() => UUIDScalarType, { nullable: true })
|
||||
applicationId?: string;
|
||||
|
||||
@IsUUID()
|
||||
@IsOptional()
|
||||
@Field(() => UUIDScalarType, { nullable: true })
|
||||
universalIdentifier?: string;
|
||||
|
||||
@HideField()
|
||||
workspaceId: string;
|
||||
|
||||
@IsDateString()
|
||||
@Field()
|
||||
createdAt: Date;
|
||||
|
||||
@IsDateString()
|
||||
@Field()
|
||||
updatedAt: Date;
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
import { ID, InputType } from '@nestjs/graphql';
|
||||
|
||||
import { IDField } from '@ptc-org/nestjs-query-graphql';
|
||||
|
||||
@InputType()
|
||||
export class PublishLogicFunctionInput {
|
||||
@IDField(() => ID, { description: 'The id of the function.' })
|
||||
id!: string;
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
import { Field, InputType } from '@nestjs/graphql';
|
||||
|
||||
import { Type } from 'class-transformer';
|
||||
import {
|
||||
IsBoolean,
|
||||
IsNotEmpty,
|
||||
IsNumber,
|
||||
IsObject,
|
||||
IsOptional,
|
||||
IsString,
|
||||
IsUUID,
|
||||
Max,
|
||||
Min,
|
||||
ValidateNested,
|
||||
} from 'class-validator';
|
||||
import graphqlTypeJson from 'graphql-type-json';
|
||||
|
||||
import type { Sources } from 'twenty-shared/types';
|
||||
|
||||
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
|
||||
|
||||
@InputType()
|
||||
class UpdateLogicFunctionInputUpdates {
|
||||
@IsString()
|
||||
@Field()
|
||||
@IsOptional()
|
||||
name?: string;
|
||||
|
||||
@IsString()
|
||||
@Field({ nullable: true })
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
|
||||
@IsNumber()
|
||||
@Field({ nullable: true })
|
||||
@Min(1)
|
||||
@Max(900)
|
||||
@IsOptional()
|
||||
timeoutSeconds?: number;
|
||||
|
||||
@Field(() => graphqlTypeJson)
|
||||
@IsObject()
|
||||
code: Sources;
|
||||
|
||||
@IsString()
|
||||
@Field({ nullable: true })
|
||||
@IsOptional()
|
||||
handlerName?: string;
|
||||
|
||||
@IsString()
|
||||
@Field({ nullable: true })
|
||||
@IsOptional()
|
||||
sourceHandlerPath?: string;
|
||||
|
||||
@Field(() => graphqlTypeJson, { nullable: true })
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
toolInputSchema?: object;
|
||||
|
||||
@IsBoolean()
|
||||
@Field({ nullable: true })
|
||||
@IsOptional()
|
||||
isTool?: boolean;
|
||||
}
|
||||
|
||||
@InputType()
|
||||
export class UpdateLogicFunctionInput {
|
||||
@Field(() => UUIDScalarType, {
|
||||
description: 'Id of the logic function to update',
|
||||
})
|
||||
@IsNotEmpty()
|
||||
@IsUUID()
|
||||
id: string;
|
||||
|
||||
@Type(() => UpdateLogicFunctionInputUpdates)
|
||||
@ValidateNested()
|
||||
@Field(() => UpdateLogicFunctionInputUpdates, {
|
||||
description: 'The logic function updates',
|
||||
})
|
||||
update: UpdateLogicFunctionInputUpdates;
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
import { Scope } from '@nestjs/common';
|
||||
|
||||
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 { LogicFunctionService } from 'src/engine/metadata-modules/logic-function/logic-function.service';
|
||||
|
||||
export type LogicFunctionTriggerJobData = {
|
||||
logicFunctionId: string;
|
||||
workspaceId: string;
|
||||
payload?: object;
|
||||
};
|
||||
|
||||
@Processor({
|
||||
queueName: MessageQueue.logicFunctionQueue,
|
||||
scope: Scope.REQUEST,
|
||||
})
|
||||
export class LogicFunctionTriggerJob {
|
||||
constructor(private readonly logicFunctionService: LogicFunctionService) {}
|
||||
|
||||
@Process(LogicFunctionTriggerJob.name)
|
||||
async handle(logicFunctionPayloads: LogicFunctionTriggerJobData[]) {
|
||||
await Promise.all(
|
||||
logicFunctionPayloads.map(
|
||||
async (logicFunctionPayload) =>
|
||||
await this.logicFunctionService.executeOneLogicFunction({
|
||||
id: logicFunctionPayload.logicFunctionId,
|
||||
workspaceId: logicFunctionPayload.workspaceId,
|
||||
payload: logicFunctionPayload.payload || {},
|
||||
version: 'draft',
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
import { HTTPMethod } from 'twenty-shared/types';
|
||||
import {
|
||||
Check,
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
DeleteDateColumn,
|
||||
Entity,
|
||||
Index,
|
||||
JoinColumn,
|
||||
ManyToOne,
|
||||
PrimaryGeneratedColumn,
|
||||
Relation,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
|
||||
import { type JsonbProperty } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/jsonb-property.type';
|
||||
import { LogicFunctionLayerEntity } from 'src/engine/metadata-modules/logic-function-layer/logic-function-layer.entity';
|
||||
import { SyncableEntity } from 'src/engine/workspace-manager/types/syncable-entity.interface';
|
||||
|
||||
export type CronTriggerSettings = {
|
||||
pattern: string;
|
||||
};
|
||||
|
||||
export type DatabaseEventTriggerSettings = {
|
||||
eventName: string;
|
||||
updatedFields?: string[];
|
||||
};
|
||||
|
||||
export type HttpRouteTriggerSettings = {
|
||||
path: string;
|
||||
httpMethod: HTTPMethod;
|
||||
isAuthRequired: boolean;
|
||||
forwardedRequestHeaders?: string[];
|
||||
};
|
||||
|
||||
const DEFAULT_LOGIC_FUNCTION_TIMEOUT_SECONDS = 300; // 5 minutes
|
||||
|
||||
export enum LogicFunctionRuntime {
|
||||
NODE18 = 'nodejs18.x',
|
||||
NODE22 = 'nodejs22.x',
|
||||
}
|
||||
|
||||
export const DEFAULT_SOURCE_HANDLER_PATH = 'src/index.ts';
|
||||
export const DEFAULT_BUILT_HANDLER_PATH = 'index.mjs';
|
||||
export const DEFAULT_HANDLER_NAME = 'main';
|
||||
|
||||
@Entity('logicFunction')
|
||||
@Index('IDX_LOGIC_FUNCTION_ID_DELETED_AT', ['id', 'deletedAt'])
|
||||
@Index('IDX_LOGIC_FUNCTION_LAYER_ID', ['logicFunctionLayerId'])
|
||||
export class LogicFunctionEntity
|
||||
extends SyncableEntity
|
||||
implements Required<LogicFunctionEntity>
|
||||
{
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@Column({ nullable: false })
|
||||
name: string;
|
||||
|
||||
@Column({ nullable: false, default: DEFAULT_SOURCE_HANDLER_PATH })
|
||||
sourceHandlerPath: string;
|
||||
|
||||
@Column({ nullable: false, default: DEFAULT_BUILT_HANDLER_PATH })
|
||||
builtHandlerPath: string;
|
||||
|
||||
@Column({ nullable: false, default: DEFAULT_HANDLER_NAME })
|
||||
handlerName: string;
|
||||
|
||||
@Column({ nullable: true, type: 'varchar' })
|
||||
description: string | null;
|
||||
|
||||
@Column({ nullable: true, type: 'varchar' })
|
||||
latestVersion: string | null;
|
||||
|
||||
@Column({ nullable: false, type: 'jsonb', default: [] })
|
||||
publishedVersions: JsonbProperty<string[]>;
|
||||
|
||||
@Column({ nullable: false, default: LogicFunctionRuntime.NODE22 })
|
||||
runtime: LogicFunctionRuntime;
|
||||
|
||||
@Column({ nullable: false, default: DEFAULT_LOGIC_FUNCTION_TIMEOUT_SECONDS })
|
||||
@Check(`"timeoutSeconds" >= 1 AND "timeoutSeconds" <= 900`)
|
||||
timeoutSeconds: number;
|
||||
|
||||
@Column({ nullable: true, type: 'text' })
|
||||
checksum: string | null;
|
||||
|
||||
@Column({ nullable: true, type: 'jsonb' })
|
||||
toolInputSchema: JsonbProperty<object> | null;
|
||||
|
||||
@Column({ nullable: false, default: false })
|
||||
isTool: boolean;
|
||||
|
||||
@Column({ nullable: false, type: 'uuid' })
|
||||
logicFunctionLayerId: string;
|
||||
|
||||
@ManyToOne(
|
||||
() => LogicFunctionLayerEntity,
|
||||
(logicFunctionLayer) => logicFunctionLayer.logicFunctions,
|
||||
{ nullable: false },
|
||||
)
|
||||
@JoinColumn({ name: 'logicFunctionLayerId' })
|
||||
logicFunctionLayer: Relation<LogicFunctionLayerEntity>;
|
||||
|
||||
@Column({ nullable: true, type: 'jsonb' })
|
||||
cronTriggerSettings: JsonbProperty<CronTriggerSettings> | null;
|
||||
|
||||
@Column({ nullable: true, type: 'jsonb' })
|
||||
databaseEventTriggerSettings: JsonbProperty<DatabaseEventTriggerSettings> | null;
|
||||
|
||||
@Column({ nullable: true, type: 'jsonb' })
|
||||
httpRouteTriggerSettings: JsonbProperty<HttpRouteTriggerSettings> | null;
|
||||
|
||||
@CreateDateColumn({ type: 'timestamptz' })
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn({ type: 'timestamptz' })
|
||||
updatedAt: Date;
|
||||
|
||||
@DeleteDateColumn({ type: 'timestamptz' })
|
||||
deletedAt: Date | null;
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
import { type MessageDescriptor } from '@lingui/core';
|
||||
import { msg } from '@lingui/core/macro';
|
||||
import { assertUnreachable } from 'twenty-shared/utils';
|
||||
|
||||
import { CustomException } from 'src/utils/custom-exception';
|
||||
|
||||
export enum LogicFunctionExceptionCode {
|
||||
LOGIC_FUNCTION_NOT_FOUND = 'LOGIC_FUNCTION_NOT_FOUND',
|
||||
LOGIC_FUNCTION_VERSION_NOT_FOUND = 'LOGIC_FUNCTION_VERSION_NOT_FOUND',
|
||||
LOGIC_FUNCTION_ALREADY_EXIST = 'LOGIC_FUNCTION_ALREADY_EXIST',
|
||||
LOGIC_FUNCTION_NOT_READY = 'LOGIC_FUNCTION_NOT_READY',
|
||||
LOGIC_FUNCTION_BUILDING = 'LOGIC_FUNCTION_BUILDING',
|
||||
LOGIC_FUNCTION_CODE_UNCHANGED = 'LOGIC_FUNCTION_CODE_UNCHANGED',
|
||||
LOGIC_FUNCTION_EXECUTION_LIMIT_REACHED = 'LOGIC_FUNCTION_EXECUTION_LIMIT_REACHED',
|
||||
LOGIC_FUNCTION_CREATE_FAILED = 'LOGIC_FUNCTION_CREATE_FAILED',
|
||||
LOGIC_FUNCTION_EXECUTION_TIMEOUT = 'LOGIC_FUNCTION_EXECUTION_TIMEOUT',
|
||||
LOGIC_FUNCTION_DISABLED = 'LOGIC_FUNCTION_DISABLED',
|
||||
}
|
||||
|
||||
const getLogicFunctionExceptionUserFriendlyMessage = (
|
||||
code: LogicFunctionExceptionCode,
|
||||
) => {
|
||||
switch (code) {
|
||||
case LogicFunctionExceptionCode.LOGIC_FUNCTION_NOT_FOUND:
|
||||
return msg`Function not found.`;
|
||||
case LogicFunctionExceptionCode.LOGIC_FUNCTION_VERSION_NOT_FOUND:
|
||||
return msg`Function version not found.`;
|
||||
case LogicFunctionExceptionCode.LOGIC_FUNCTION_ALREADY_EXIST:
|
||||
return msg`A function with this name already exists.`;
|
||||
case LogicFunctionExceptionCode.LOGIC_FUNCTION_NOT_READY:
|
||||
return msg`Function is not ready.`;
|
||||
case LogicFunctionExceptionCode.LOGIC_FUNCTION_BUILDING:
|
||||
return msg`Function is currently building.`;
|
||||
case LogicFunctionExceptionCode.LOGIC_FUNCTION_CODE_UNCHANGED:
|
||||
return msg`Function code is unchanged.`;
|
||||
case LogicFunctionExceptionCode.LOGIC_FUNCTION_EXECUTION_LIMIT_REACHED:
|
||||
return msg`Function execution limit reached.`;
|
||||
case LogicFunctionExceptionCode.LOGIC_FUNCTION_CREATE_FAILED:
|
||||
return msg`Failed to create function.`;
|
||||
case LogicFunctionExceptionCode.LOGIC_FUNCTION_EXECUTION_TIMEOUT:
|
||||
return msg`Function execution timed out.`;
|
||||
case LogicFunctionExceptionCode.LOGIC_FUNCTION_DISABLED:
|
||||
return msg`Logic function execution is disabled.`;
|
||||
default:
|
||||
assertUnreachable(code);
|
||||
}
|
||||
};
|
||||
|
||||
export class LogicFunctionException extends CustomException<LogicFunctionExceptionCode> {
|
||||
constructor(
|
||||
message: string,
|
||||
code: LogicFunctionExceptionCode,
|
||||
{ userFriendlyMessage }: { userFriendlyMessage?: MessageDescriptor } = {},
|
||||
) {
|
||||
super(message, code, {
|
||||
userFriendlyMessage:
|
||||
userFriendlyMessage ??
|
||||
getLogicFunctionExceptionUserFriendlyMessage(code),
|
||||
});
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
|
||||
import { NestjsQueryTypeOrmModule } from '@ptc-org/nestjs-query-typeorm';
|
||||
|
||||
import { ApplicationModule } from 'src/engine/core-modules/application/application.module';
|
||||
import { AuditModule } from 'src/engine/core-modules/audit/audit.module';
|
||||
import { TokenModule } from 'src/engine/core-modules/auth/token/token.module';
|
||||
import { FeatureFlagEntity } from 'src/engine/core-modules/feature-flag/feature-flag.entity';
|
||||
import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';
|
||||
import { FileUploadModule } from 'src/engine/core-modules/file/file-upload/file-upload.module';
|
||||
import { FileModule } from 'src/engine/core-modules/file/file.module';
|
||||
import { SecretEncryptionModule } from 'src/engine/core-modules/secret-encryption/secret-encryption.module';
|
||||
import { ThrottlerModule } from 'src/engine/core-modules/throttler/throttler.module';
|
||||
import { WorkspaceManyOrAllFlatEntityMapsCacheModule } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.module';
|
||||
import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permissions.module';
|
||||
import { LogicFunctionLayerModule } from 'src/engine/metadata-modules/logic-function-layer/logic-function-layer.module';
|
||||
import { LogicFunctionTriggerJob } from 'src/engine/metadata-modules/logic-function/jobs/logic-function-trigger.job';
|
||||
import { LogicFunctionEntity } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
|
||||
import { LogicFunctionResolver } from 'src/engine/metadata-modules/logic-function/logic-function.resolver';
|
||||
import { LogicFunctionService } from 'src/engine/metadata-modules/logic-function/logic-function.service';
|
||||
import { LogicFunctionV2Service } from 'src/engine/metadata-modules/logic-function/services/logic-function-v2.service';
|
||||
import { WorkspaceFlatLogicFunctionMapCacheService } from 'src/engine/metadata-modules/logic-function/services/workspace-flat-logic-function-map-cache.service';
|
||||
import { SubscriptionsModule } from 'src/engine/subscriptions/subscriptions.module';
|
||||
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
|
||||
import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspace-migration/workspace-migration.module';
|
||||
import { FunctionBuildModule } from 'src/engine/metadata-modules/function-build/function-build.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
FileUploadModule,
|
||||
NestjsQueryTypeOrmModule.forFeature([LogicFunctionEntity]),
|
||||
TypeOrmModule.forFeature([FeatureFlagEntity]),
|
||||
FileModule,
|
||||
ThrottlerModule,
|
||||
ApplicationModule,
|
||||
AuditModule,
|
||||
FeatureFlagModule,
|
||||
PermissionsModule,
|
||||
WorkspaceManyOrAllFlatEntityMapsCacheModule,
|
||||
WorkspaceMigrationModule,
|
||||
FunctionBuildModule,
|
||||
LogicFunctionLayerModule,
|
||||
SubscriptionsModule,
|
||||
WorkspaceCacheModule,
|
||||
TokenModule,
|
||||
SecretEncryptionModule,
|
||||
],
|
||||
providers: [
|
||||
LogicFunctionService,
|
||||
LogicFunctionV2Service,
|
||||
LogicFunctionTriggerJob,
|
||||
LogicFunctionResolver,
|
||||
WorkspaceFlatLogicFunctionMapCacheService,
|
||||
],
|
||||
exports: [LogicFunctionService, LogicFunctionV2Service],
|
||||
})
|
||||
export class LogicFunctionModule {}
|
||||
+281
@@ -0,0 +1,281 @@
|
||||
import { UseFilters, UseGuards, UsePipes } from '@nestjs/common';
|
||||
import { Args, Mutation, Query, Resolver, Subscription } from '@nestjs/graphql';
|
||||
|
||||
import graphqlTypeJson from 'graphql-type-json';
|
||||
import { PermissionFlagType } from 'twenty-shared/constants';
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
|
||||
import { PreventNestToAutoLogGraphqlErrorsFilter } from 'src/engine/core-modules/graphql/filters/prevent-nest-to-auto-log-graphql-errors.filter';
|
||||
import { ResolverValidationPipe } from 'src/engine/core-modules/graphql/pipes/resolver-validation.pipe';
|
||||
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
|
||||
import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
|
||||
import { FeatureFlagGuard } from 'src/engine/guards/feature-flag.guard';
|
||||
import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';
|
||||
import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
|
||||
import { WorkspaceManyOrAllFlatEntityMapsCacheService } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.service';
|
||||
import { CreateLogicFunctionInput } from 'src/engine/metadata-modules/logic-function/dtos/create-logic-function.input';
|
||||
import { ExecuteLogicFunctionInput } from 'src/engine/metadata-modules/logic-function/dtos/execute-logic-function.input';
|
||||
import { GetLogicFunctionSourceCodeInput } from 'src/engine/metadata-modules/logic-function/dtos/get-logic-function-source-code.input';
|
||||
import { PublishLogicFunctionInput } from 'src/engine/metadata-modules/logic-function/dtos/publish-logic-function.input';
|
||||
import { LogicFunctionExecutionResultDTO } from 'src/engine/metadata-modules/logic-function/dtos/logic-function-execution-result.dto';
|
||||
import { LogicFunctionIdInput } from 'src/engine/metadata-modules/logic-function/dtos/logic-function-id.input';
|
||||
import { LogicFunctionLogsDTO } from 'src/engine/metadata-modules/logic-function/dtos/logic-function-logs.dto';
|
||||
import { LogicFunctionLogsInput } from 'src/engine/metadata-modules/logic-function/dtos/logic-function-logs.input';
|
||||
import { LogicFunctionDTO } from 'src/engine/metadata-modules/logic-function/dtos/logic-function.dto';
|
||||
import { UpdateLogicFunctionInput } from 'src/engine/metadata-modules/logic-function/dtos/update-logic-function.input';
|
||||
import { LogicFunctionService } from 'src/engine/metadata-modules/logic-function/logic-function.service';
|
||||
import { FlatLogicFunction } from 'src/engine/metadata-modules/logic-function/types/flat-logic-function.type';
|
||||
import { findFlatLogicFunctionOrThrow } from 'src/engine/metadata-modules/logic-function/utils/find-flat-logic-function-or-throw.util';
|
||||
import { fromFlatLogicFunctionToLogicFunctionDto } from 'src/engine/metadata-modules/logic-function/utils/from-flat-logic-function-to-logic-function-dto.util';
|
||||
import { logicFunctionGraphQLApiExceptionHandler } from 'src/engine/metadata-modules/logic-function/utils/logic-function-graphql-api-exception-handler.utils';
|
||||
import { SubscriptionChannel } from 'src/engine/subscriptions/enums/subscription-channel.enum';
|
||||
import { SubscriptionService } from 'src/engine/subscriptions/subscription.service';
|
||||
|
||||
@UseGuards(
|
||||
WorkspaceAuthGuard,
|
||||
FeatureFlagGuard,
|
||||
SettingsPermissionGuard(PermissionFlagType.WORKFLOWS),
|
||||
)
|
||||
@Resolver()
|
||||
@UsePipes(ResolverValidationPipe)
|
||||
@UseFilters(PreventNestToAutoLogGraphqlErrorsFilter)
|
||||
export class LogicFunctionResolver {
|
||||
constructor(
|
||||
private readonly logicFunctionService: LogicFunctionService,
|
||||
private readonly subscriptionService: SubscriptionService,
|
||||
private readonly flatEntityMapsCacheService: WorkspaceManyOrAllFlatEntityMapsCacheService,
|
||||
) {}
|
||||
|
||||
@Query(() => LogicFunctionDTO)
|
||||
async findOneLogicFunction(
|
||||
@Args('input') { id }: LogicFunctionIdInput,
|
||||
@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
|
||||
): Promise<LogicFunctionDTO> {
|
||||
try {
|
||||
const { flatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const flatLogicFunction = findFlatLogicFunctionOrThrow({
|
||||
id,
|
||||
flatLogicFunctionMaps,
|
||||
});
|
||||
|
||||
return fromFlatLogicFunctionToLogicFunctionDto({
|
||||
flatLogicFunction,
|
||||
});
|
||||
} catch (error) {
|
||||
return logicFunctionGraphQLApiExceptionHandler(error);
|
||||
}
|
||||
}
|
||||
|
||||
@Query(() => [LogicFunctionDTO])
|
||||
async findManyLogicFunctions(
|
||||
@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
|
||||
): Promise<LogicFunctionDTO[]> {
|
||||
try {
|
||||
const { flatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
return Object.values(flatLogicFunctionMaps.byId)
|
||||
.filter(
|
||||
(flatLogicFunction): flatLogicFunction is FlatLogicFunction =>
|
||||
isDefined(flatLogicFunction) &&
|
||||
!isDefined(flatLogicFunction.deletedAt),
|
||||
)
|
||||
.map((flatLogicFunction) =>
|
||||
fromFlatLogicFunctionToLogicFunctionDto({
|
||||
flatLogicFunction,
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
return logicFunctionGraphQLApiExceptionHandler(error);
|
||||
}
|
||||
}
|
||||
|
||||
@Query(() => graphqlTypeJson)
|
||||
async getAvailablePackages(@Args('input') { id }: LogicFunctionIdInput) {
|
||||
try {
|
||||
return await this.logicFunctionService.getAvailablePackages(id);
|
||||
} catch (error) {
|
||||
return logicFunctionGraphQLApiExceptionHandler(error);
|
||||
}
|
||||
}
|
||||
|
||||
@Query(() => graphqlTypeJson, { nullable: true })
|
||||
async getLogicFunctionSourceCode(
|
||||
@Args('input') input: GetLogicFunctionSourceCodeInput,
|
||||
@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
|
||||
) {
|
||||
try {
|
||||
return await this.logicFunctionService.getLogicFunctionSourceCode(
|
||||
workspaceId,
|
||||
input.id,
|
||||
input.version,
|
||||
);
|
||||
} catch (error) {
|
||||
return logicFunctionGraphQLApiExceptionHandler(error);
|
||||
}
|
||||
}
|
||||
|
||||
@Mutation(() => LogicFunctionDTO)
|
||||
@UseGuards(SettingsPermissionGuard(PermissionFlagType.WORKFLOWS))
|
||||
async deleteOneLogicFunction(
|
||||
@Args('input') input: LogicFunctionIdInput,
|
||||
@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
|
||||
): Promise<LogicFunctionDTO> {
|
||||
try {
|
||||
const flatLogicFunction =
|
||||
await this.logicFunctionService.deleteOneLogicFunction({
|
||||
id: input.id,
|
||||
workspaceId,
|
||||
});
|
||||
|
||||
return fromFlatLogicFunctionToLogicFunctionDto({
|
||||
flatLogicFunction,
|
||||
});
|
||||
} catch (error) {
|
||||
return logicFunctionGraphQLApiExceptionHandler(error);
|
||||
}
|
||||
}
|
||||
|
||||
@Mutation(() => LogicFunctionDTO)
|
||||
@UseGuards(SettingsPermissionGuard(PermissionFlagType.WORKFLOWS))
|
||||
async updateOneLogicFunction(
|
||||
@Args('input')
|
||||
input: UpdateLogicFunctionInput,
|
||||
@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
|
||||
): Promise<LogicFunctionDTO> {
|
||||
try {
|
||||
const flatLogicFunction =
|
||||
await this.logicFunctionService.updateOneLogicFunction(
|
||||
input,
|
||||
workspaceId,
|
||||
);
|
||||
|
||||
return fromFlatLogicFunctionToLogicFunctionDto({
|
||||
flatLogicFunction,
|
||||
});
|
||||
} catch (error) {
|
||||
return logicFunctionGraphQLApiExceptionHandler(error);
|
||||
}
|
||||
}
|
||||
|
||||
@Mutation(() => LogicFunctionDTO)
|
||||
@UseGuards(SettingsPermissionGuard(PermissionFlagType.WORKFLOWS))
|
||||
async createOneLogicFunction(
|
||||
@Args('input')
|
||||
input: CreateLogicFunctionInput,
|
||||
@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
|
||||
): Promise<LogicFunctionDTO> {
|
||||
try {
|
||||
const flatLogicFunction =
|
||||
await this.logicFunctionService.createOneLogicFunction(
|
||||
input,
|
||||
workspaceId,
|
||||
);
|
||||
|
||||
return fromFlatLogicFunctionToLogicFunctionDto({
|
||||
flatLogicFunction,
|
||||
});
|
||||
} catch (error) {
|
||||
return logicFunctionGraphQLApiExceptionHandler(error);
|
||||
}
|
||||
}
|
||||
|
||||
@Mutation(() => LogicFunctionExecutionResultDTO)
|
||||
@UseGuards(SettingsPermissionGuard(PermissionFlagType.WORKFLOWS))
|
||||
async executeOneLogicFunction(
|
||||
@Args('input') input: ExecuteLogicFunctionInput,
|
||||
@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
|
||||
) {
|
||||
try {
|
||||
const { id, payload, version } = input;
|
||||
|
||||
return await this.logicFunctionService.executeOneLogicFunction({
|
||||
id,
|
||||
workspaceId,
|
||||
payload,
|
||||
version,
|
||||
});
|
||||
} catch (error) {
|
||||
return logicFunctionGraphQLApiExceptionHandler(error);
|
||||
}
|
||||
}
|
||||
|
||||
@Mutation(() => LogicFunctionDTO)
|
||||
@UseGuards(SettingsPermissionGuard(PermissionFlagType.WORKFLOWS))
|
||||
async publishLogicFunction(
|
||||
@Args('input') input: PublishLogicFunctionInput,
|
||||
@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
|
||||
): Promise<LogicFunctionDTO> {
|
||||
try {
|
||||
const { id } = input;
|
||||
|
||||
const flatLogicFunction =
|
||||
await this.logicFunctionService.publishOneLogicFunctionOrFail(
|
||||
id,
|
||||
workspaceId,
|
||||
);
|
||||
|
||||
return fromFlatLogicFunctionToLogicFunctionDto({
|
||||
flatLogicFunction,
|
||||
});
|
||||
} catch (error) {
|
||||
return logicFunctionGraphQLApiExceptionHandler(error);
|
||||
}
|
||||
}
|
||||
|
||||
@Subscription(() => LogicFunctionLogsDTO, {
|
||||
filter: (
|
||||
payload: { logicFunctionLogs: LogicFunctionLogsDTO },
|
||||
variables: { input: LogicFunctionLogsInput },
|
||||
) => {
|
||||
const { logicFunctionLogs } = payload;
|
||||
const {
|
||||
id,
|
||||
universalIdentifier,
|
||||
applicationId,
|
||||
applicationUniversalIdentifier,
|
||||
name,
|
||||
} = logicFunctionLogs;
|
||||
const {
|
||||
id: inputId,
|
||||
universalIdentifier: inputUniversalIdentifier,
|
||||
name: inputName,
|
||||
applicationId: inputApplicationId,
|
||||
applicationUniversalIdentifier: inputApplicationUniversalIdentifier,
|
||||
} = variables.input;
|
||||
|
||||
return (
|
||||
(!isDefined(inputId) || inputId === id) &&
|
||||
(!isDefined(inputUniversalIdentifier) ||
|
||||
inputUniversalIdentifier === universalIdentifier) &&
|
||||
(!isDefined(inputName) || inputName === name) &&
|
||||
(!isDefined(inputApplicationId) ||
|
||||
inputApplicationId === applicationId) &&
|
||||
(!isDefined(inputApplicationUniversalIdentifier) ||
|
||||
inputApplicationUniversalIdentifier ===
|
||||
applicationUniversalIdentifier)
|
||||
);
|
||||
},
|
||||
})
|
||||
logicFunctionLogs(
|
||||
@Args('input') _: LogicFunctionLogsInput,
|
||||
@AuthWorkspace() workspace: WorkspaceEntity,
|
||||
) {
|
||||
return this.subscriptionService.subscribe({
|
||||
channel: SubscriptionChannel.LOGIC_FUNCTION_LOGS_CHANNEL,
|
||||
workspaceId: workspace.id,
|
||||
});
|
||||
}
|
||||
}
|
||||
+838
@@ -0,0 +1,838 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
|
||||
import deepEqual from 'deep-equal';
|
||||
import {
|
||||
DEFAULT_API_KEY_NAME,
|
||||
DEFAULT_API_URL_NAME,
|
||||
} from 'twenty-shared/application';
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
import { Repository } from 'typeorm';
|
||||
import { FileFolder } from 'twenty-shared/types';
|
||||
|
||||
import { FileStorageExceptionCode } from 'src/engine/core-modules/file-storage/interfaces/file-storage-exception';
|
||||
import { type LogicFunctionExecuteResult } from 'src/engine/core-modules/logic-function-executor/drivers/interfaces/logic-function-executor-driver.interface';
|
||||
|
||||
import { ApplicationService } from 'src/engine/core-modules/application/application.service';
|
||||
import { AuditService } from 'src/engine/core-modules/audit/services/audit.service';
|
||||
import { LOGIC_FUNCTION_EXECUTED_EVENT } from 'src/engine/core-modules/audit/utils/events/workspace-event/logic-function/logic-function-executed';
|
||||
import { ApplicationTokenService } from 'src/engine/core-modules/auth/token/services/application-token.service';
|
||||
import { FileStorageService } from 'src/engine/core-modules/file-storage/file-storage.service';
|
||||
import { SecretEncryptionService } from 'src/engine/core-modules/secret-encryption/secret-encryption.service';
|
||||
import { buildEnvVar } from 'src/engine/core-modules/logic-function-executor/drivers/utils/build-env-var';
|
||||
import { LogicFunctionExecutorService } from 'src/engine/core-modules/logic-function-executor/logic-function-executor.service';
|
||||
import { getLogicFunctionFolderOrThrow } from 'src/engine/core-modules/logic-function-executor/utils/get-logic-function-folder-or-throw.utils';
|
||||
import { ThrottlerService } from 'src/engine/core-modules/throttler/throttler.service';
|
||||
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
|
||||
import { WorkspaceManyOrAllFlatEntityMapsCacheService } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.service';
|
||||
import { findFlatEntityByIdInFlatEntityMapsOrThrow } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps-or-throw.util';
|
||||
import { findFlatEntityByIdInFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps.util';
|
||||
import { LogicFunctionLayerService } from 'src/engine/metadata-modules/logic-function-layer/logic-function-layer.service';
|
||||
import { CreateLogicFunctionInput } from 'src/engine/metadata-modules/logic-function/dtos/create-logic-function.input';
|
||||
import { type UpdateLogicFunctionInput } from 'src/engine/metadata-modules/logic-function/dtos/update-logic-function.input';
|
||||
import { LogicFunctionEntity } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
|
||||
import {
|
||||
LogicFunctionException,
|
||||
LogicFunctionExceptionCode,
|
||||
} from 'src/engine/metadata-modules/logic-function/logic-function.exception';
|
||||
import { type FlatLogicFunction } from 'src/engine/metadata-modules/logic-function/types/flat-logic-function.type';
|
||||
import { findFlatLogicFunctionOrThrow } from 'src/engine/metadata-modules/logic-function/utils/find-flat-logic-function-or-throw.util';
|
||||
import { fromCreateLogicFunctionInputToFlatLogicFunction } from 'src/engine/metadata-modules/logic-function/utils/from-create-logic-function-input-to-flat-logic-function.util';
|
||||
import { fromUpdateLogicFunctionInputToFlatLogicFunctionToUpdateOrThrow } from 'src/engine/metadata-modules/logic-function/utils/from-update-logic-function-input-to-flat-logic-function-to-update-or-throw.util';
|
||||
import { SubscriptionChannel } from 'src/engine/subscriptions/enums/subscription-channel.enum';
|
||||
import { SubscriptionService } from 'src/engine/subscriptions/subscription.service';
|
||||
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
|
||||
import { WorkspaceMigrationBuilderException } from 'src/engine/workspace-manager/workspace-migration/exceptions/workspace-migration-builder-exception';
|
||||
import { WorkspaceMigrationValidateBuildAndRunService } from 'src/engine/workspace-manager/workspace-migration/services/workspace-migration-validate-build-and-run-service';
|
||||
import {
|
||||
WorkflowVersionStepException,
|
||||
WorkflowVersionStepExceptionCode,
|
||||
} from 'src/modules/workflow/common/exceptions/workflow-version-step.exception';
|
||||
import { cleanServerUrl } from 'src/utils/clean-server-url';
|
||||
import { FunctionBuildService } from 'src/engine/metadata-modules/function-build/function-build.service';
|
||||
|
||||
const MIN_TOKEN_EXPIRATION_IN_SECONDS = 5;
|
||||
|
||||
@Injectable()
|
||||
export class LogicFunctionService {
|
||||
constructor(
|
||||
private readonly fileStorageService: FileStorageService,
|
||||
private readonly logicFunctionExecutorService: LogicFunctionExecutorService,
|
||||
private readonly functionBuildService: FunctionBuildService,
|
||||
private readonly logicFunctionLayerService: LogicFunctionLayerService,
|
||||
@InjectRepository(LogicFunctionEntity)
|
||||
private readonly logicFunctionRepository: Repository<LogicFunctionEntity>,
|
||||
private readonly throttlerService: ThrottlerService,
|
||||
private readonly twentyConfigService: TwentyConfigService,
|
||||
private readonly auditService: AuditService,
|
||||
private readonly applicationTokenService: ApplicationTokenService,
|
||||
private readonly subscriptionService: SubscriptionService,
|
||||
private readonly flatEntityMapsCacheService: WorkspaceManyOrAllFlatEntityMapsCacheService,
|
||||
private readonly workspaceMigrationValidateBuildAndRunService: WorkspaceMigrationValidateBuildAndRunService,
|
||||
private readonly applicationService: ApplicationService,
|
||||
private readonly workspaceCacheService: WorkspaceCacheService,
|
||||
private readonly secretEncryptionService: SecretEncryptionService,
|
||||
) {}
|
||||
|
||||
async hasLogicFunctionPublishedVersion(
|
||||
logicFunctionId: string,
|
||||
workspaceId: string,
|
||||
) {
|
||||
const { flatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const flatLogicFunction = findFlatEntityByIdInFlatEntityMaps({
|
||||
flatEntityId: logicFunctionId,
|
||||
flatEntityMaps: flatLogicFunctionMaps,
|
||||
});
|
||||
|
||||
return (
|
||||
isDefined(flatLogicFunction) &&
|
||||
!isDefined(flatLogicFunction.deletedAt) &&
|
||||
isDefined(flatLogicFunction.latestVersion)
|
||||
);
|
||||
}
|
||||
|
||||
async getLogicFunctionSourceCode(
|
||||
workspaceId: string,
|
||||
id: string,
|
||||
version: string,
|
||||
) {
|
||||
const { flatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const flatLogicFunction = findFlatLogicFunctionOrThrow({
|
||||
id,
|
||||
flatLogicFunctionMaps,
|
||||
});
|
||||
|
||||
try {
|
||||
const folderPath = getLogicFunctionFolderOrThrow({
|
||||
flatLogicFunction,
|
||||
version,
|
||||
});
|
||||
|
||||
return await this.fileStorageService.readFolder(folderPath);
|
||||
} catch (error) {
|
||||
if (error.code === FileStorageExceptionCode.FILE_NOT_FOUND) {
|
||||
return;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async executeOneLogicFunction({
|
||||
id,
|
||||
workspaceId,
|
||||
payload,
|
||||
version = 'latest',
|
||||
}: {
|
||||
id: string;
|
||||
workspaceId: string;
|
||||
payload: object;
|
||||
version?: string;
|
||||
}): Promise<LogicFunctionExecuteResult> {
|
||||
await this.throttleExecution(workspaceId);
|
||||
|
||||
const {
|
||||
flatLogicFunctionMaps,
|
||||
flatApplicationMaps,
|
||||
applicationVariableMaps,
|
||||
logicFunctionLayerMaps,
|
||||
} = await this.workspaceCacheService.getOrRecompute(workspaceId, [
|
||||
'flatLogicFunctionMaps',
|
||||
'flatApplicationMaps',
|
||||
'applicationVariableMaps',
|
||||
'logicFunctionLayerMaps',
|
||||
]);
|
||||
|
||||
const flatLogicFunction = findFlatLogicFunctionOrThrow({
|
||||
id,
|
||||
flatLogicFunctionMaps,
|
||||
});
|
||||
|
||||
const flatLogicFunctionLayer =
|
||||
logicFunctionLayerMaps.byId[flatLogicFunction.logicFunctionLayerId];
|
||||
|
||||
if (!isDefined(flatLogicFunctionLayer)) {
|
||||
throw new LogicFunctionException(
|
||||
`Logic function layer with id ${flatLogicFunction.logicFunctionLayerId} not found`,
|
||||
LogicFunctionExceptionCode.LOGIC_FUNCTION_NOT_FOUND,
|
||||
);
|
||||
}
|
||||
|
||||
const applicationAccessToken = isDefined(flatLogicFunction.applicationId)
|
||||
? await this.applicationTokenService.generateApplicationToken({
|
||||
workspaceId,
|
||||
applicationId: flatLogicFunction.applicationId,
|
||||
expiresInSeconds: Math.max(
|
||||
flatLogicFunction.timeoutSeconds,
|
||||
MIN_TOKEN_EXPIRATION_IN_SECONDS,
|
||||
),
|
||||
})
|
||||
: undefined;
|
||||
|
||||
const baseUrl = cleanServerUrl(this.twentyConfigService.get('SERVER_URL'));
|
||||
|
||||
const flatApplicationVariables = isDefined(flatLogicFunction.applicationId)
|
||||
? (applicationVariableMaps.byApplicationId[
|
||||
flatLogicFunction.applicationId
|
||||
] ?? [])
|
||||
: [];
|
||||
|
||||
const envVariables = {
|
||||
...(isDefined(baseUrl)
|
||||
? {
|
||||
[DEFAULT_API_URL_NAME]: baseUrl,
|
||||
}
|
||||
: {}),
|
||||
...(isDefined(applicationAccessToken)
|
||||
? {
|
||||
[DEFAULT_API_KEY_NAME]: applicationAccessToken.token,
|
||||
}
|
||||
: {}),
|
||||
...buildEnvVar(flatApplicationVariables, this.secretEncryptionService),
|
||||
};
|
||||
|
||||
// We keep that check to build functions
|
||||
if (
|
||||
!(await this.functionBuildService.isBuilt({
|
||||
flatLogicFunction,
|
||||
version,
|
||||
}))
|
||||
) {
|
||||
await this.functionBuildService.buildAndUpload({
|
||||
flatLogicFunction,
|
||||
version,
|
||||
});
|
||||
}
|
||||
|
||||
const resultLogicFunction = await this.callWithTimeout({
|
||||
callback: () =>
|
||||
this.logicFunctionExecutorService.execute({
|
||||
flatLogicFunction,
|
||||
flatLogicFunctionLayer,
|
||||
payload,
|
||||
version,
|
||||
env: envVariables,
|
||||
}),
|
||||
timeoutMs: flatLogicFunction.timeoutSeconds * 1000,
|
||||
});
|
||||
|
||||
if (this.twentyConfigService.get('LOGIC_FUNCTION_LOGS_ENABLED')) {
|
||||
/* eslint-disable no-console */
|
||||
console.log(resultLogicFunction.logs);
|
||||
}
|
||||
|
||||
const applicationUniversalIdentifier = isDefined(
|
||||
flatLogicFunction.applicationId,
|
||||
)
|
||||
? flatApplicationMaps.byId[flatLogicFunction.applicationId]
|
||||
?.universalIdentifier
|
||||
: undefined;
|
||||
|
||||
await this.subscriptionService.publish({
|
||||
channel: SubscriptionChannel.LOGIC_FUNCTION_LOGS_CHANNEL,
|
||||
workspaceId,
|
||||
payload: {
|
||||
logicFunctionLogs: {
|
||||
logs: resultLogicFunction.logs,
|
||||
id: flatLogicFunction.id,
|
||||
name: flatLogicFunction.name,
|
||||
universalIdentifier: flatLogicFunction.universalIdentifier,
|
||||
applicationId: flatLogicFunction.applicationId,
|
||||
applicationUniversalIdentifier,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
this.auditService
|
||||
.createContext({
|
||||
workspaceId,
|
||||
})
|
||||
.insertWorkspaceEvent(LOGIC_FUNCTION_EXECUTED_EVENT, {
|
||||
duration: resultLogicFunction.duration,
|
||||
status: resultLogicFunction.status,
|
||||
...(resultLogicFunction.error && {
|
||||
errorType: resultLogicFunction.error.errorType,
|
||||
}),
|
||||
functionId: flatLogicFunction.id,
|
||||
functionName: flatLogicFunction.name,
|
||||
});
|
||||
|
||||
return resultLogicFunction;
|
||||
}
|
||||
|
||||
async publishOneLogicFunctionOrFail(
|
||||
id: string,
|
||||
workspaceId: string,
|
||||
): Promise<FlatLogicFunction> {
|
||||
const { flatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const existingFlatLogicFunction = findFlatLogicFunctionOrThrow({
|
||||
id,
|
||||
flatLogicFunctionMaps,
|
||||
});
|
||||
|
||||
if (isDefined(existingFlatLogicFunction.latestVersion)) {
|
||||
const latestCode = await this.getLogicFunctionSourceCode(
|
||||
workspaceId,
|
||||
id,
|
||||
'latest',
|
||||
);
|
||||
const draftCode = await this.getLogicFunctionSourceCode(
|
||||
workspaceId,
|
||||
id,
|
||||
'draft',
|
||||
);
|
||||
|
||||
if (deepEqual(latestCode, draftCode)) {
|
||||
return existingFlatLogicFunction;
|
||||
}
|
||||
}
|
||||
|
||||
const newVersion = existingFlatLogicFunction.latestVersion
|
||||
? `${parseInt(existingFlatLogicFunction.latestVersion, 10) + 1}`
|
||||
: '1';
|
||||
|
||||
const draftSourceFolderPath = getLogicFunctionFolderOrThrow({
|
||||
flatLogicFunction: existingFlatLogicFunction,
|
||||
version: 'draft',
|
||||
fileFolder: FileFolder.LogicFunction,
|
||||
});
|
||||
|
||||
const newSourceFolderPath = getLogicFunctionFolderOrThrow({
|
||||
flatLogicFunction: existingFlatLogicFunction,
|
||||
version: newVersion,
|
||||
fileFolder: FileFolder.LogicFunction,
|
||||
});
|
||||
|
||||
await this.fileStorageService.copy({
|
||||
from: { folderPath: draftSourceFolderPath },
|
||||
to: { folderPath: newSourceFolderPath },
|
||||
});
|
||||
|
||||
const draftBuiltFolderPath = getLogicFunctionFolderOrThrow({
|
||||
flatLogicFunction: existingFlatLogicFunction,
|
||||
version: 'draft',
|
||||
fileFolder: FileFolder.BuiltFunction,
|
||||
});
|
||||
|
||||
const newBuiltFolderPath = getLogicFunctionFolderOrThrow({
|
||||
flatLogicFunction: existingFlatLogicFunction,
|
||||
version: newVersion,
|
||||
fileFolder: FileFolder.BuiltFunction,
|
||||
});
|
||||
|
||||
await this.fileStorageService.copy({
|
||||
from: { folderPath: draftBuiltFolderPath },
|
||||
to: { folderPath: newBuiltFolderPath },
|
||||
});
|
||||
|
||||
const newPublishedVersions = [
|
||||
...existingFlatLogicFunction.publishedVersions,
|
||||
newVersion,
|
||||
];
|
||||
|
||||
const updatedFlatLogicFunction: FlatLogicFunction = {
|
||||
...existingFlatLogicFunction,
|
||||
latestVersion: newVersion,
|
||||
publishedVersions: newPublishedVersions,
|
||||
};
|
||||
|
||||
const validateAndBuildResult =
|
||||
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
|
||||
{
|
||||
allFlatEntityOperationByMetadataName: {
|
||||
logicFunction: {
|
||||
flatEntityToCreate: [],
|
||||
flatEntityToDelete: [],
|
||||
flatEntityToUpdate: [updatedFlatLogicFunction],
|
||||
},
|
||||
},
|
||||
workspaceId,
|
||||
isSystemBuild: false,
|
||||
},
|
||||
);
|
||||
|
||||
if (isDefined(validateAndBuildResult)) {
|
||||
throw new WorkspaceMigrationBuilderException(
|
||||
validateAndBuildResult,
|
||||
'Multiple validation errors occurred while publishing logic function',
|
||||
);
|
||||
}
|
||||
|
||||
const { flatLogicFunctionMaps: recomputedFlatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const publishedFlatLogicFunction =
|
||||
findFlatEntityByIdInFlatEntityMapsOrThrow({
|
||||
flatEntityId: id,
|
||||
flatEntityMaps: recomputedFlatLogicFunctionMaps,
|
||||
});
|
||||
|
||||
if (!isDefined(publishedFlatLogicFunction.latestVersion)) {
|
||||
throw new WorkflowVersionStepException(
|
||||
`Fail to publish logicFunction ${publishedFlatLogicFunction.id}.Received latest version ${publishedFlatLogicFunction.latestVersion}`,
|
||||
WorkflowVersionStepExceptionCode.CODE_STEP_FAILURE,
|
||||
);
|
||||
}
|
||||
|
||||
return publishedFlatLogicFunction;
|
||||
}
|
||||
|
||||
async deleteOneLogicFunction({
|
||||
id,
|
||||
workspaceId,
|
||||
softDelete = false,
|
||||
}: {
|
||||
id: string;
|
||||
workspaceId: string;
|
||||
softDelete?: boolean;
|
||||
}): Promise<FlatLogicFunction> {
|
||||
const { flatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const existingFlatLogicFunction = flatLogicFunctionMaps.byId[id];
|
||||
|
||||
if (!isDefined(existingFlatLogicFunction)) {
|
||||
throw new LogicFunctionException(
|
||||
'Logic function to delete not found',
|
||||
LogicFunctionExceptionCode.LOGIC_FUNCTION_NOT_FOUND,
|
||||
);
|
||||
}
|
||||
|
||||
if (softDelete) {
|
||||
const updatedFlatLogicFunctionWithDeletedAt: FlatLogicFunction = {
|
||||
...existingFlatLogicFunction,
|
||||
deletedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
const validateAndBuildResult =
|
||||
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
|
||||
{
|
||||
allFlatEntityOperationByMetadataName: {
|
||||
logicFunction: {
|
||||
flatEntityToCreate: [],
|
||||
flatEntityToDelete: [],
|
||||
flatEntityToUpdate: [updatedFlatLogicFunctionWithDeletedAt],
|
||||
},
|
||||
},
|
||||
workspaceId,
|
||||
isSystemBuild: false,
|
||||
},
|
||||
);
|
||||
|
||||
if (isDefined(validateAndBuildResult)) {
|
||||
throw new WorkspaceMigrationBuilderException(
|
||||
validateAndBuildResult,
|
||||
'Multiple validation errors occurred while deleting logic function',
|
||||
);
|
||||
}
|
||||
|
||||
return updatedFlatLogicFunctionWithDeletedAt;
|
||||
} else {
|
||||
const validateAndBuildResult =
|
||||
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
|
||||
{
|
||||
allFlatEntityOperationByMetadataName: {
|
||||
logicFunction: {
|
||||
flatEntityToCreate: [],
|
||||
flatEntityToDelete: [existingFlatLogicFunction],
|
||||
flatEntityToUpdate: [],
|
||||
},
|
||||
},
|
||||
workspaceId,
|
||||
isSystemBuild: false,
|
||||
},
|
||||
);
|
||||
|
||||
if (isDefined(validateAndBuildResult)) {
|
||||
throw new WorkspaceMigrationBuilderException(
|
||||
validateAndBuildResult,
|
||||
'Multiple validation errors occurred while destroying logic function',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return existingFlatLogicFunction;
|
||||
}
|
||||
|
||||
async restoreOneLogicFunction(
|
||||
id: string,
|
||||
workspaceId: string,
|
||||
): Promise<FlatLogicFunction> {
|
||||
const { flatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const existingFlatLogicFunction = flatLogicFunctionMaps.byId[id];
|
||||
|
||||
if (!isDefined(existingFlatLogicFunction)) {
|
||||
throw new LogicFunctionException(
|
||||
'Logic function to restore not found',
|
||||
LogicFunctionExceptionCode.LOGIC_FUNCTION_NOT_FOUND,
|
||||
);
|
||||
}
|
||||
|
||||
const restoredFlatLogicFunction: FlatLogicFunction = {
|
||||
...existingFlatLogicFunction,
|
||||
deletedAt: null,
|
||||
};
|
||||
|
||||
const validateAndBuildResult =
|
||||
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
|
||||
{
|
||||
allFlatEntityOperationByMetadataName: {
|
||||
logicFunction: {
|
||||
flatEntityToCreate: [],
|
||||
flatEntityToDelete: [],
|
||||
flatEntityToUpdate: [restoredFlatLogicFunction],
|
||||
},
|
||||
},
|
||||
workspaceId,
|
||||
isSystemBuild: false,
|
||||
},
|
||||
);
|
||||
|
||||
if (isDefined(validateAndBuildResult)) {
|
||||
throw new WorkspaceMigrationBuilderException(
|
||||
validateAndBuildResult,
|
||||
'Multiple validation errors occurred while restoring logic function',
|
||||
);
|
||||
}
|
||||
|
||||
const { flatLogicFunctionMaps: recomputedFlatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
return findFlatEntityByIdInFlatEntityMapsOrThrow({
|
||||
flatEntityId: id,
|
||||
flatEntityMaps: recomputedFlatLogicFunctionMaps,
|
||||
});
|
||||
}
|
||||
|
||||
async updateOneLogicFunction(
|
||||
logicFunctionInput: UpdateLogicFunctionInput,
|
||||
workspaceId: string,
|
||||
): Promise<FlatLogicFunction> {
|
||||
const { flatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const updatedFlatLogicFunction =
|
||||
fromUpdateLogicFunctionInputToFlatLogicFunctionToUpdateOrThrow({
|
||||
flatLogicFunctionMaps,
|
||||
updateLogicFunctionInput: logicFunctionInput,
|
||||
});
|
||||
|
||||
const validateAndBuildResult =
|
||||
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
|
||||
{
|
||||
allFlatEntityOperationByMetadataName: {
|
||||
logicFunction: {
|
||||
flatEntityToCreate: [],
|
||||
flatEntityToDelete: [],
|
||||
flatEntityToUpdate: [updatedFlatLogicFunction],
|
||||
},
|
||||
},
|
||||
workspaceId,
|
||||
isSystemBuild: false,
|
||||
},
|
||||
);
|
||||
|
||||
if (isDefined(validateAndBuildResult)) {
|
||||
throw new WorkspaceMigrationBuilderException(
|
||||
validateAndBuildResult,
|
||||
'Multiple validation errors occurred while updating logic function',
|
||||
);
|
||||
}
|
||||
|
||||
const { flatLogicFunctionMaps: recomputedFlatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
return findFlatEntityByIdInFlatEntityMapsOrThrow({
|
||||
flatEntityId: updatedFlatLogicFunction.id,
|
||||
flatEntityMaps: recomputedFlatLogicFunctionMaps,
|
||||
});
|
||||
}
|
||||
|
||||
async getAvailablePackages(logicFunctionId: string) {
|
||||
const logicFunction = await this.logicFunctionRepository.findOneOrFail({
|
||||
where: { id: logicFunctionId },
|
||||
relations: ['logicFunctionLayer'],
|
||||
});
|
||||
|
||||
const packageJson = logicFunction.logicFunctionLayer.packageJson;
|
||||
|
||||
const yarnLock = logicFunction.logicFunctionLayer.yarnLock;
|
||||
|
||||
const packageVersionRegex = /^"([^@]+)@.*?":\n\s+version: (.+)$/gm;
|
||||
|
||||
const versions: Record<string, string> = {};
|
||||
|
||||
let match: RegExpExecArray | null;
|
||||
|
||||
while ((match = packageVersionRegex.exec(yarnLock)) !== null) {
|
||||
const packageName = match[1].split('@', 1)[0];
|
||||
const version = match[2];
|
||||
|
||||
// @ts-expect-error legacy noImplicitAny
|
||||
if (packageJson.dependencies?.[packageName]) {
|
||||
versions[packageName] = version;
|
||||
}
|
||||
}
|
||||
|
||||
return versions;
|
||||
}
|
||||
|
||||
async createOneLogicFunction(
|
||||
logicFunctionInput: CreateLogicFunctionInput & {
|
||||
logicFunctionLayerId?: string;
|
||||
},
|
||||
workspaceId: string,
|
||||
): Promise<FlatLogicFunction> {
|
||||
let logicFunctionToCreateLayerId = logicFunctionInput.logicFunctionLayerId;
|
||||
|
||||
if (!isDefined(logicFunctionToCreateLayerId)) {
|
||||
const { id: commonLogicFunctionLayerId } =
|
||||
await this.logicFunctionLayerService.createCommonLayerIfNotExist(
|
||||
workspaceId,
|
||||
);
|
||||
|
||||
logicFunctionToCreateLayerId = commonLogicFunctionLayerId;
|
||||
}
|
||||
|
||||
const { workspaceCustomFlatApplication } =
|
||||
await this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(
|
||||
{
|
||||
workspaceId,
|
||||
},
|
||||
);
|
||||
|
||||
const flatLogicFunctionToCreate =
|
||||
fromCreateLogicFunctionInputToFlatLogicFunction({
|
||||
createLogicFunctionInput: {
|
||||
...logicFunctionInput,
|
||||
logicFunctionLayerId: logicFunctionToCreateLayerId,
|
||||
},
|
||||
workspaceId,
|
||||
workspaceCustomApplicationId:
|
||||
logicFunctionInput.applicationId ?? workspaceCustomFlatApplication.id,
|
||||
});
|
||||
|
||||
const validateAndBuildResult =
|
||||
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
|
||||
{
|
||||
allFlatEntityOperationByMetadataName: {
|
||||
logicFunction: {
|
||||
flatEntityToCreate: [flatLogicFunctionToCreate],
|
||||
flatEntityToDelete: [],
|
||||
flatEntityToUpdate: [],
|
||||
},
|
||||
},
|
||||
workspaceId,
|
||||
isSystemBuild: false,
|
||||
},
|
||||
);
|
||||
|
||||
if (isDefined(validateAndBuildResult)) {
|
||||
throw new WorkspaceMigrationBuilderException(
|
||||
validateAndBuildResult,
|
||||
'Multiple validation errors occurred while creating logic function',
|
||||
);
|
||||
}
|
||||
|
||||
const { flatLogicFunctionMaps: recomputedFlatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
return findFlatEntityByIdInFlatEntityMapsOrThrow({
|
||||
flatEntityId: flatLogicFunctionToCreate.id,
|
||||
flatEntityMaps: recomputedFlatLogicFunctionMaps,
|
||||
});
|
||||
}
|
||||
|
||||
async createDraftFromPublishedVersion({
|
||||
id,
|
||||
version,
|
||||
workspaceId,
|
||||
}: {
|
||||
id: string;
|
||||
version: string;
|
||||
workspaceId: string;
|
||||
}) {
|
||||
if (version === 'draft') {
|
||||
return;
|
||||
}
|
||||
|
||||
const { flatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const flatLogicFunction = findFlatLogicFunctionOrThrow({
|
||||
id,
|
||||
flatLogicFunctionMaps,
|
||||
});
|
||||
|
||||
await this.fileStorageService.copy({
|
||||
from: {
|
||||
folderPath: getLogicFunctionFolderOrThrow({
|
||||
flatLogicFunction,
|
||||
version,
|
||||
}),
|
||||
},
|
||||
to: {
|
||||
folderPath: getLogicFunctionFolderOrThrow({
|
||||
flatLogicFunction,
|
||||
version: 'draft',
|
||||
}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async duplicateLogicFunction({
|
||||
id,
|
||||
version,
|
||||
workspaceId,
|
||||
}: {
|
||||
id: string;
|
||||
version: string;
|
||||
workspaceId: string;
|
||||
}): Promise<FlatLogicFunction> {
|
||||
const { flatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const flatLogicFunctionToDuplicate = findFlatLogicFunctionOrThrow({
|
||||
id,
|
||||
flatLogicFunctionMaps,
|
||||
});
|
||||
|
||||
const newFlatLogicFunction = await this.createOneLogicFunction(
|
||||
{
|
||||
name: flatLogicFunctionToDuplicate.name,
|
||||
description: flatLogicFunctionToDuplicate.description ?? undefined,
|
||||
timeoutSeconds: flatLogicFunctionToDuplicate.timeoutSeconds,
|
||||
applicationId: flatLogicFunctionToDuplicate.applicationId ?? undefined,
|
||||
logicFunctionLayerId: flatLogicFunctionToDuplicate.logicFunctionLayerId,
|
||||
},
|
||||
workspaceId,
|
||||
);
|
||||
|
||||
await this.fileStorageService.copy({
|
||||
from: {
|
||||
folderPath: getLogicFunctionFolderOrThrow({
|
||||
flatLogicFunction: flatLogicFunctionToDuplicate,
|
||||
version,
|
||||
}),
|
||||
},
|
||||
to: {
|
||||
folderPath: getLogicFunctionFolderOrThrow({
|
||||
flatLogicFunction: newFlatLogicFunction,
|
||||
version: 'draft',
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
return newFlatLogicFunction;
|
||||
}
|
||||
|
||||
private async throttleExecution(workspaceId: string) {
|
||||
try {
|
||||
await this.throttlerService.tokenBucketThrottleOrThrow(
|
||||
`${workspaceId}-logic-function-execution`,
|
||||
1,
|
||||
this.twentyConfigService.get('LOGIC_FUNCTION_EXEC_THROTTLE_LIMIT'),
|
||||
this.twentyConfigService.get('LOGIC_FUNCTION_EXEC_THROTTLE_TTL'),
|
||||
);
|
||||
} catch {
|
||||
throw new LogicFunctionException(
|
||||
'Logic function execution rate limit exceeded',
|
||||
LogicFunctionExceptionCode.LOGIC_FUNCTION_EXECUTION_LIMIT_REACHED,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async callWithTimeout<T>({
|
||||
callback,
|
||||
timeoutMs,
|
||||
}: {
|
||||
callback: () => Promise<T>;
|
||||
timeoutMs: number;
|
||||
}): Promise<T> {
|
||||
let timeoutId: NodeJS.Timeout;
|
||||
|
||||
const timeoutPromise = new Promise<never>((_, reject) => {
|
||||
timeoutId = setTimeout(
|
||||
() =>
|
||||
reject(
|
||||
new LogicFunctionException(
|
||||
`Execution timeout: ${timeoutMs / 1000}s`,
|
||||
LogicFunctionExceptionCode.LOGIC_FUNCTION_EXECUTION_TIMEOUT,
|
||||
),
|
||||
),
|
||||
timeoutMs,
|
||||
);
|
||||
});
|
||||
|
||||
return Promise.race([callback(), timeoutPromise]).finally(() =>
|
||||
clearTimeout(timeoutId),
|
||||
) as Promise<T>;
|
||||
}
|
||||
}
|
||||
+270
@@ -0,0 +1,270 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
|
||||
import { ApplicationService } from 'src/engine/core-modules/application/application.service';
|
||||
import { WorkspaceManyOrAllFlatEntityMapsCacheService } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.service';
|
||||
import { findFlatEntityByIdInFlatEntityMapsOrThrow } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps-or-throw.util';
|
||||
import type { CreateLogicFunctionInput } from 'src/engine/metadata-modules/logic-function/dtos/create-logic-function.input';
|
||||
import { LogicFunctionIdInput } from 'src/engine/metadata-modules/logic-function/dtos/logic-function-id.input';
|
||||
import { UpdateLogicFunctionInput } from 'src/engine/metadata-modules/logic-function/dtos/update-logic-function.input';
|
||||
import {
|
||||
LogicFunctionException,
|
||||
LogicFunctionExceptionCode,
|
||||
} from 'src/engine/metadata-modules/logic-function/logic-function.exception';
|
||||
import { FlatLogicFunction } from 'src/engine/metadata-modules/logic-function/types/flat-logic-function.type';
|
||||
import { fromCreateLogicFunctionInputToFlatLogicFunction } from 'src/engine/metadata-modules/logic-function/utils/from-create-logic-function-input-to-flat-logic-function.util';
|
||||
import { fromUpdateLogicFunctionInputToFlatLogicFunctionToUpdateOrThrow } from 'src/engine/metadata-modules/logic-function/utils/from-update-logic-function-input-to-flat-logic-function-to-update-or-throw.util';
|
||||
import { WorkspaceMigrationBuilderException } from 'src/engine/workspace-manager/workspace-migration/exceptions/workspace-migration-builder-exception';
|
||||
import { WorkspaceMigrationValidateBuildAndRunService } from 'src/engine/workspace-manager/workspace-migration/services/workspace-migration-validate-build-and-run-service';
|
||||
|
||||
@Injectable()
|
||||
export class LogicFunctionV2Service {
|
||||
constructor(
|
||||
private readonly flatEntityMapsCacheService: WorkspaceManyOrAllFlatEntityMapsCacheService,
|
||||
private readonly workspaceMigrationValidateBuildAndRunService: WorkspaceMigrationValidateBuildAndRunService,
|
||||
private readonly applicationService: ApplicationService,
|
||||
) {}
|
||||
|
||||
async createOne({
|
||||
createLogicFunctionInput,
|
||||
workspaceId,
|
||||
applicationId,
|
||||
}: {
|
||||
createLogicFunctionInput: CreateLogicFunctionInput & {
|
||||
logicFunctionLayerId: string;
|
||||
};
|
||||
/**
|
||||
* @deprecated do not use call validateBuildAndRunWorkspaceMigration contextually
|
||||
* when interacting with another application than workspace custom one
|
||||
* */
|
||||
applicationId?: string;
|
||||
workspaceId: string;
|
||||
}) {
|
||||
const { workspaceCustomFlatApplication } =
|
||||
await this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(
|
||||
{
|
||||
workspaceId,
|
||||
},
|
||||
);
|
||||
|
||||
const flatLogicFunctionToCreate =
|
||||
fromCreateLogicFunctionInputToFlatLogicFunction({
|
||||
createLogicFunctionInput,
|
||||
workspaceId,
|
||||
workspaceCustomApplicationId:
|
||||
applicationId ?? workspaceCustomFlatApplication.id,
|
||||
});
|
||||
|
||||
const validateAndBuildResult =
|
||||
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
|
||||
{
|
||||
allFlatEntityOperationByMetadataName: {
|
||||
logicFunction: {
|
||||
flatEntityToCreate: [flatLogicFunctionToCreate],
|
||||
flatEntityToDelete: [],
|
||||
flatEntityToUpdate: [],
|
||||
},
|
||||
},
|
||||
workspaceId,
|
||||
isSystemBuild: false,
|
||||
},
|
||||
);
|
||||
|
||||
if (isDefined(validateAndBuildResult)) {
|
||||
throw new WorkspaceMigrationBuilderException(
|
||||
validateAndBuildResult,
|
||||
'Multiple validation errors occurred while creating logic function',
|
||||
);
|
||||
}
|
||||
|
||||
const { flatLogicFunctionMaps: recomputedExistingFlatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
return findFlatEntityByIdInFlatEntityMapsOrThrow({
|
||||
flatEntityId: flatLogicFunctionToCreate.id,
|
||||
flatEntityMaps: recomputedExistingFlatLogicFunctionMaps,
|
||||
});
|
||||
}
|
||||
|
||||
async updateOne(
|
||||
logicFunctionInput: UpdateLogicFunctionInput,
|
||||
workspaceId: string,
|
||||
) {
|
||||
const { flatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const optimisticallyUpdatedFlatLogicFunction =
|
||||
fromUpdateLogicFunctionInputToFlatLogicFunctionToUpdateOrThrow({
|
||||
flatLogicFunctionMaps,
|
||||
updateLogicFunctionInput: logicFunctionInput,
|
||||
});
|
||||
|
||||
const validateAndBuildResult =
|
||||
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
|
||||
{
|
||||
allFlatEntityOperationByMetadataName: {
|
||||
logicFunction: {
|
||||
flatEntityToCreate: [],
|
||||
flatEntityToDelete: [],
|
||||
flatEntityToUpdate: [optimisticallyUpdatedFlatLogicFunction],
|
||||
},
|
||||
},
|
||||
workspaceId,
|
||||
isSystemBuild: false,
|
||||
},
|
||||
);
|
||||
|
||||
if (isDefined(validateAndBuildResult)) {
|
||||
throw new WorkspaceMigrationBuilderException(
|
||||
validateAndBuildResult,
|
||||
'Multiple validation errors occurred while updating logic function',
|
||||
);
|
||||
}
|
||||
|
||||
const { flatLogicFunctionMaps: recomputedExistingFlatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
return findFlatEntityByIdInFlatEntityMapsOrThrow({
|
||||
flatEntityId: optimisticallyUpdatedFlatLogicFunction.id,
|
||||
flatEntityMaps: recomputedExistingFlatLogicFunctionMaps,
|
||||
});
|
||||
}
|
||||
|
||||
async deleteOne({
|
||||
deleteLogicFunctionInput,
|
||||
workspaceId,
|
||||
isSystemBuild = false,
|
||||
}: {
|
||||
deleteLogicFunctionInput: LogicFunctionIdInput;
|
||||
workspaceId: string;
|
||||
isSystemBuild?: boolean;
|
||||
}): Promise<FlatLogicFunction> {
|
||||
const { flatLogicFunctionMaps: existingFlatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const existingFlatLogicFunction =
|
||||
existingFlatLogicFunctionMaps.byId[deleteLogicFunctionInput.id];
|
||||
|
||||
if (!isDefined(existingFlatLogicFunction)) {
|
||||
throw new LogicFunctionException(
|
||||
'Logic function to delete not found',
|
||||
LogicFunctionExceptionCode.LOGIC_FUNCTION_NOT_FOUND,
|
||||
);
|
||||
}
|
||||
|
||||
const optimisticallyUpdatedFlatLogicFunctionWithDeletedAt = {
|
||||
...existingFlatLogicFunction,
|
||||
deletedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
const validateAndBuildResult =
|
||||
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
|
||||
{
|
||||
allFlatEntityOperationByMetadataName: {
|
||||
logicFunction: {
|
||||
flatEntityToCreate: [],
|
||||
flatEntityToDelete: [],
|
||||
flatEntityToUpdate: [
|
||||
optimisticallyUpdatedFlatLogicFunctionWithDeletedAt,
|
||||
],
|
||||
},
|
||||
},
|
||||
workspaceId,
|
||||
isSystemBuild,
|
||||
},
|
||||
);
|
||||
|
||||
if (isDefined(validateAndBuildResult)) {
|
||||
throw new WorkspaceMigrationBuilderException(
|
||||
validateAndBuildResult,
|
||||
'Multiple validation errors occurred while deleting logic function',
|
||||
);
|
||||
}
|
||||
|
||||
const { flatLogicFunctionMaps: recomputedExistingFlatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
return findFlatEntityByIdInFlatEntityMapsOrThrow({
|
||||
flatEntityId: optimisticallyUpdatedFlatLogicFunctionWithDeletedAt.id,
|
||||
flatEntityMaps: recomputedExistingFlatLogicFunctionMaps,
|
||||
});
|
||||
}
|
||||
|
||||
async destroyOne({
|
||||
destroyLogicFunctionInput,
|
||||
workspaceId,
|
||||
isSystemBuild = false,
|
||||
}: {
|
||||
destroyLogicFunctionInput: LogicFunctionIdInput;
|
||||
workspaceId: string;
|
||||
isSystemBuild?: boolean;
|
||||
}): Promise<FlatLogicFunction> {
|
||||
const { flatLogicFunctionMaps: existingFlatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const existingFlatLogicFunction =
|
||||
existingFlatLogicFunctionMaps.byId[destroyLogicFunctionInput.id];
|
||||
|
||||
if (!isDefined(existingFlatLogicFunction)) {
|
||||
throw new LogicFunctionException(
|
||||
'Logic function to destroy not found',
|
||||
LogicFunctionExceptionCode.LOGIC_FUNCTION_NOT_FOUND,
|
||||
);
|
||||
}
|
||||
|
||||
const validateAndBuildResult =
|
||||
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
|
||||
{
|
||||
allFlatEntityOperationByMetadataName: {
|
||||
logicFunction: {
|
||||
flatEntityToCreate: [],
|
||||
flatEntityToDelete: [existingFlatLogicFunction],
|
||||
flatEntityToUpdate: [],
|
||||
},
|
||||
},
|
||||
workspaceId,
|
||||
isSystemBuild,
|
||||
},
|
||||
);
|
||||
|
||||
if (isDefined(validateAndBuildResult)) {
|
||||
throw new WorkspaceMigrationBuilderException(
|
||||
validateAndBuildResult,
|
||||
'Multiple validation errors occurred while destroying logic function',
|
||||
);
|
||||
}
|
||||
|
||||
return existingFlatLogicFunction;
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
|
||||
import { Repository } from 'typeorm';
|
||||
|
||||
import { WorkspaceCacheProvider } from 'src/engine/workspace-cache/interfaces/workspace-cache-provider.service';
|
||||
|
||||
import { createEmptyFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/constant/create-empty-flat-entity-maps.constant';
|
||||
import { FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';
|
||||
import { LogicFunctionEntity } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
|
||||
import { FlatLogicFunction } from 'src/engine/metadata-modules/logic-function/types/flat-logic-function.type';
|
||||
import { fromLogicFunctionEntityToFlatLogicFunction } from 'src/engine/metadata-modules/logic-function/utils/from-logic-function-entity-to-flat-logic-function.util';
|
||||
import { WorkspaceCache } from 'src/engine/workspace-cache/decorators/workspace-cache.decorator';
|
||||
import { addFlatEntityToFlatEntityMapsThroughMutationOrThrow } from 'src/engine/workspace-manager/workspace-migration/utils/add-flat-entity-to-flat-entity-maps-through-mutation-or-throw.util';
|
||||
|
||||
@Injectable()
|
||||
@WorkspaceCache('flatLogicFunctionMaps')
|
||||
export class WorkspaceFlatLogicFunctionMapCacheService extends WorkspaceCacheProvider<
|
||||
FlatEntityMaps<FlatLogicFunction>
|
||||
> {
|
||||
constructor(
|
||||
@InjectRepository(LogicFunctionEntity)
|
||||
private readonly logicFunctionRepository: Repository<LogicFunctionEntity>,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async computeForCache(
|
||||
workspaceId: string,
|
||||
): Promise<FlatEntityMaps<FlatLogicFunction>> {
|
||||
const logicFunctions = await this.logicFunctionRepository.find({
|
||||
where: { workspaceId },
|
||||
withDeleted: true,
|
||||
});
|
||||
|
||||
const flatLogicFunctionMaps = createEmptyFlatEntityMaps();
|
||||
|
||||
for (const logicFunctionEntity of logicFunctions) {
|
||||
const flatLogicFunction =
|
||||
fromLogicFunctionEntityToFlatLogicFunction(logicFunctionEntity);
|
||||
|
||||
addFlatEntityToFlatEntityMapsThroughMutationOrThrow({
|
||||
flatEntity: flatLogicFunction,
|
||||
flatEntityMapsToMutate: flatLogicFunctionMaps,
|
||||
});
|
||||
}
|
||||
|
||||
return flatLogicFunctionMaps;
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
import { type Sources } from 'twenty-shared/types';
|
||||
|
||||
import { type FlatEntityFrom } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-from.type';
|
||||
import { type LogicFunctionEntity } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
|
||||
|
||||
export type FlatLogicFunction = FlatEntityFrom<LogicFunctionEntity> & {
|
||||
code?: Sources;
|
||||
};
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
|
||||
import { type MetadataFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/metadata-flat-entity-maps.type';
|
||||
import { findFlatEntityByIdInFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps.util';
|
||||
import {
|
||||
LogicFunctionException,
|
||||
LogicFunctionExceptionCode,
|
||||
} from 'src/engine/metadata-modules/logic-function/logic-function.exception';
|
||||
|
||||
export const findFlatLogicFunctionOrThrow = ({
|
||||
flatLogicFunctionMaps,
|
||||
id,
|
||||
}: {
|
||||
flatLogicFunctionMaps: MetadataFlatEntityMaps<'logicFunction'>;
|
||||
id: string;
|
||||
}) => {
|
||||
const flatLogicFunction = findFlatEntityByIdInFlatEntityMaps({
|
||||
flatEntityId: id,
|
||||
flatEntityMaps: flatLogicFunctionMaps,
|
||||
});
|
||||
|
||||
if (!isDefined(flatLogicFunction) || isDefined(flatLogicFunction.deletedAt)) {
|
||||
throw new LogicFunctionException(
|
||||
`Logic function with id ${id} not found`,
|
||||
LogicFunctionExceptionCode.LOGIC_FUNCTION_NOT_FOUND,
|
||||
);
|
||||
}
|
||||
|
||||
return flatLogicFunction;
|
||||
};
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
import { v4 } from 'uuid';
|
||||
|
||||
import { DEFAULT_TOOL_INPUT_SCHEMA } from 'src/engine/metadata-modules/logic-function/constants/default-tool-input-schema.constant';
|
||||
import { type CreateLogicFunctionInput } from 'src/engine/metadata-modules/logic-function/dtos/create-logic-function.input';
|
||||
import {
|
||||
DEFAULT_BUILT_HANDLER_PATH,
|
||||
DEFAULT_HANDLER_NAME,
|
||||
DEFAULT_SOURCE_HANDLER_PATH,
|
||||
LogicFunctionRuntime,
|
||||
} from 'src/engine/metadata-modules/logic-function/logic-function.entity';
|
||||
import { type FlatLogicFunction } from 'src/engine/metadata-modules/logic-function/types/flat-logic-function.type';
|
||||
import { logicFunctionCreateHash } from 'src/engine/metadata-modules/logic-function/utils/logic-function-create-hash.utils';
|
||||
|
||||
export type FromCreateLogicFunctionInputToFlatLogicFunctionArgs = {
|
||||
createLogicFunctionInput: CreateLogicFunctionInput & {
|
||||
logicFunctionLayerId: string;
|
||||
};
|
||||
workspaceId: string;
|
||||
workspaceCustomApplicationId: string;
|
||||
};
|
||||
|
||||
export const fromCreateLogicFunctionInputToFlatLogicFunction = ({
|
||||
createLogicFunctionInput: rawCreateLogicFunctionInput,
|
||||
workspaceId,
|
||||
workspaceCustomApplicationId,
|
||||
}: FromCreateLogicFunctionInputToFlatLogicFunctionArgs): FlatLogicFunction => {
|
||||
const id = v4();
|
||||
const currentDate = new Date();
|
||||
|
||||
return {
|
||||
id,
|
||||
cronTriggerSettings: null,
|
||||
databaseEventTriggerSettings: null,
|
||||
httpRouteTriggerSettings: null,
|
||||
name: rawCreateLogicFunctionInput.name,
|
||||
description: rawCreateLogicFunctionInput.description ?? null,
|
||||
sourceHandlerPath:
|
||||
rawCreateLogicFunctionInput.sourceHandlerPath ??
|
||||
DEFAULT_SOURCE_HANDLER_PATH,
|
||||
handlerName:
|
||||
rawCreateLogicFunctionInput.handlerName ?? DEFAULT_HANDLER_NAME,
|
||||
builtHandlerPath:
|
||||
rawCreateLogicFunctionInput.builtHandlerPath ??
|
||||
DEFAULT_BUILT_HANDLER_PATH,
|
||||
universalIdentifier:
|
||||
rawCreateLogicFunctionInput.universalIdentifier ?? v4(),
|
||||
createdAt: currentDate.toISOString(),
|
||||
updatedAt: currentDate.toISOString(),
|
||||
deletedAt: null,
|
||||
latestVersion: null,
|
||||
publishedVersions: [],
|
||||
applicationId: workspaceCustomApplicationId,
|
||||
runtime: LogicFunctionRuntime.NODE22,
|
||||
timeoutSeconds: rawCreateLogicFunctionInput.timeoutSeconds ?? 300,
|
||||
logicFunctionLayerId: rawCreateLogicFunctionInput.logicFunctionLayerId,
|
||||
workspaceId,
|
||||
code: rawCreateLogicFunctionInput?.code,
|
||||
checksum: rawCreateLogicFunctionInput?.code
|
||||
? logicFunctionCreateHash(
|
||||
JSON.stringify(rawCreateLogicFunctionInput.code),
|
||||
)
|
||||
: null,
|
||||
// If no schema provided and no code provided, use default schema
|
||||
// (because the default template will be used)
|
||||
toolInputSchema: isDefined(rawCreateLogicFunctionInput?.toolInputSchema)
|
||||
? rawCreateLogicFunctionInput.toolInputSchema
|
||||
: !isDefined(rawCreateLogicFunctionInput?.code)
|
||||
? DEFAULT_TOOL_INPUT_SCHEMA
|
||||
: null,
|
||||
isTool: rawCreateLogicFunctionInput?.isTool ?? false,
|
||||
};
|
||||
};
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
import { type LogicFunctionDTO } from 'src/engine/metadata-modules/logic-function/dtos/logic-function.dto';
|
||||
import { type FlatLogicFunction } from 'src/engine/metadata-modules/logic-function/types/flat-logic-function.type';
|
||||
|
||||
export const fromFlatLogicFunctionToLogicFunctionDto = ({
|
||||
flatLogicFunction,
|
||||
}: {
|
||||
flatLogicFunction: FlatLogicFunction;
|
||||
}): LogicFunctionDTO => {
|
||||
return {
|
||||
id: flatLogicFunction.id,
|
||||
name: flatLogicFunction.name,
|
||||
description: flatLogicFunction.description ?? undefined,
|
||||
runtime: flatLogicFunction.runtime,
|
||||
timeoutSeconds: flatLogicFunction.timeoutSeconds,
|
||||
latestVersion: flatLogicFunction.latestVersion ?? undefined,
|
||||
sourceHandlerPath: flatLogicFunction.sourceHandlerPath,
|
||||
builtHandlerPath: flatLogicFunction.builtHandlerPath,
|
||||
handlerName: flatLogicFunction.handlerName,
|
||||
publishedVersions: flatLogicFunction.publishedVersions,
|
||||
toolInputSchema: flatLogicFunction.toolInputSchema ?? undefined,
|
||||
isTool: flatLogicFunction.isTool,
|
||||
applicationId: flatLogicFunction.applicationId ?? undefined,
|
||||
workspaceId: flatLogicFunction.workspaceId,
|
||||
createdAt: new Date(flatLogicFunction.createdAt),
|
||||
updatedAt: new Date(flatLogicFunction.updatedAt),
|
||||
cronTriggerSettings: flatLogicFunction.cronTriggerSettings ?? undefined,
|
||||
databaseEventTriggerSettings:
|
||||
flatLogicFunction.databaseEventTriggerSettings ?? undefined,
|
||||
httpRouteTriggerSettings:
|
||||
flatLogicFunction.httpRouteTriggerSettings ?? undefined,
|
||||
};
|
||||
};
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
import { removePropertiesFromRecord } from 'twenty-shared/utils';
|
||||
|
||||
import { type LogicFunctionEntity } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
|
||||
import { type FlatLogicFunction } from 'src/engine/metadata-modules/logic-function/types/flat-logic-function.type';
|
||||
|
||||
export const fromLogicFunctionEntityToFlatLogicFunction = (
|
||||
logicFunctionEntity: LogicFunctionEntity,
|
||||
): FlatLogicFunction => {
|
||||
const logicFunctionWithoutRelations = removePropertiesFromRecord(
|
||||
logicFunctionEntity,
|
||||
['logicFunctionLayer', 'application'],
|
||||
);
|
||||
|
||||
return {
|
||||
...logicFunctionWithoutRelations,
|
||||
createdAt: logicFunctionEntity.createdAt.toISOString(),
|
||||
updatedAt: logicFunctionEntity.updatedAt.toISOString(),
|
||||
deletedAt: logicFunctionEntity.deletedAt?.toISOString() ?? null,
|
||||
universalIdentifier: logicFunctionEntity.universalIdentifier,
|
||||
};
|
||||
};
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
import {
|
||||
extractAndSanitizeObjectStringFields,
|
||||
trimAndRemoveDuplicatedWhitespacesFromObjectStringProperties,
|
||||
} from 'twenty-shared/utils';
|
||||
|
||||
import { type MetadataFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/metadata-flat-entity-maps.type';
|
||||
import { FLAT_LOGIC_FUNCTION_EDITABLE_PROPERTIES } from 'src/engine/metadata-modules/logic-function/constants/flat-logic-function-editable-properties.constant';
|
||||
import { type UpdateLogicFunctionInput } from 'src/engine/metadata-modules/logic-function/dtos/update-logic-function.input';
|
||||
import { type FlatLogicFunction } from 'src/engine/metadata-modules/logic-function/types/flat-logic-function.type';
|
||||
import { findFlatLogicFunctionOrThrow } from 'src/engine/metadata-modules/logic-function/utils/find-flat-logic-function-or-throw.util';
|
||||
import { logicFunctionCreateHash } from 'src/engine/metadata-modules/logic-function/utils/logic-function-create-hash.utils';
|
||||
import { mergeUpdateInExistingRecord } from 'src/utils/merge-update-in-existing-record.util';
|
||||
|
||||
export const fromUpdateLogicFunctionInputToFlatLogicFunctionToUpdateOrThrow = ({
|
||||
updateLogicFunctionInput: rawUpdateLogicFunctionInput,
|
||||
flatLogicFunctionMaps,
|
||||
}: {
|
||||
updateLogicFunctionInput: UpdateLogicFunctionInput;
|
||||
flatLogicFunctionMaps: MetadataFlatEntityMaps<'logicFunction'>;
|
||||
}): FlatLogicFunction => {
|
||||
const { id: logicFunctionToUpdateId } =
|
||||
trimAndRemoveDuplicatedWhitespacesFromObjectStringProperties(
|
||||
rawUpdateLogicFunctionInput,
|
||||
['id'],
|
||||
);
|
||||
|
||||
const existingFlatLogicFunctionToUpdate = findFlatLogicFunctionOrThrow({
|
||||
id: logicFunctionToUpdateId,
|
||||
flatLogicFunctionMaps,
|
||||
});
|
||||
const updatedEditableFieldProperties = {
|
||||
...extractAndSanitizeObjectStringFields(
|
||||
{
|
||||
...rawUpdateLogicFunctionInput.update,
|
||||
checksum: logicFunctionCreateHash(
|
||||
JSON.stringify(rawUpdateLogicFunctionInput.update.code),
|
||||
),
|
||||
},
|
||||
FLAT_LOGIC_FUNCTION_EDITABLE_PROPERTIES,
|
||||
),
|
||||
code: rawUpdateLogicFunctionInput.update.code,
|
||||
};
|
||||
|
||||
return mergeUpdateInExistingRecord({
|
||||
existing: existingFlatLogicFunctionToUpdate,
|
||||
properties: FLAT_LOGIC_FUNCTION_EDITABLE_PROPERTIES,
|
||||
update: updatedEditableFieldProperties,
|
||||
});
|
||||
};
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
import { createHash } from 'crypto';
|
||||
|
||||
export const logicFunctionCreateHash = (fileContent: string) => {
|
||||
return createHash('sha512')
|
||||
.update(fileContent)
|
||||
.digest('hex')
|
||||
.substring(0, 32);
|
||||
};
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
import { assertUnreachable } from 'twenty-shared/utils';
|
||||
|
||||
import {
|
||||
ConflictError,
|
||||
ForbiddenError,
|
||||
NotFoundError,
|
||||
TimeoutError,
|
||||
} from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
|
||||
import {
|
||||
LogicFunctionException,
|
||||
LogicFunctionExceptionCode,
|
||||
} from 'src/engine/metadata-modules/logic-function/logic-function.exception';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export const logicFunctionGraphQLApiExceptionHandler = (error: any) => {
|
||||
if (error instanceof LogicFunctionException) {
|
||||
switch (error.code) {
|
||||
case LogicFunctionExceptionCode.LOGIC_FUNCTION_NOT_FOUND:
|
||||
case LogicFunctionExceptionCode.LOGIC_FUNCTION_VERSION_NOT_FOUND:
|
||||
throw new NotFoundError(error);
|
||||
case LogicFunctionExceptionCode.LOGIC_FUNCTION_ALREADY_EXIST:
|
||||
throw new ConflictError(error);
|
||||
case LogicFunctionExceptionCode.LOGIC_FUNCTION_NOT_READY:
|
||||
case LogicFunctionExceptionCode.LOGIC_FUNCTION_BUILDING:
|
||||
case LogicFunctionExceptionCode.LOGIC_FUNCTION_EXECUTION_LIMIT_REACHED:
|
||||
throw new ForbiddenError(error);
|
||||
case LogicFunctionExceptionCode.LOGIC_FUNCTION_EXECUTION_TIMEOUT:
|
||||
throw new TimeoutError(error);
|
||||
case LogicFunctionExceptionCode.LOGIC_FUNCTION_CODE_UNCHANGED:
|
||||
case LogicFunctionExceptionCode.LOGIC_FUNCTION_CREATE_FAILED:
|
||||
throw error;
|
||||
case LogicFunctionExceptionCode.LOGIC_FUNCTION_DISABLED:
|
||||
throw new ForbiddenError(error);
|
||||
default: {
|
||||
return assertUnreachable(error.code);
|
||||
}
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
};
|
||||
Reference in New Issue
Block a user