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:
+3
-3
@@ -393,7 +393,7 @@ ${preloadedTools.length > 0 ? preloadedTools.map((t) => `- \`${t}\` ✓`).join('
|
||||
'DASHBOARD',
|
||||
'METADATA',
|
||||
'VIEW',
|
||||
'SERVERLESS_FUNCTION',
|
||||
'LOGIC_FUNCTION',
|
||||
];
|
||||
|
||||
for (const category of categoryOrder) {
|
||||
@@ -439,8 +439,8 @@ ${tools
|
||||
return 'View Tools (query views)';
|
||||
case 'DASHBOARD':
|
||||
return 'Dashboard Tools (create/manage dashboards)';
|
||||
case 'SERVERLESS_FUNCTION':
|
||||
return 'Serverless Functions (custom tools)';
|
||||
case 'LOGIC_FUNCTION':
|
||||
return 'Logic Functions (custom tools)';
|
||||
default:
|
||||
return category;
|
||||
}
|
||||
|
||||
+2
-4
@@ -4,12 +4,10 @@ import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
|
||||
import { CronTriggerCronCommand } from 'src/engine/metadata-modules/cron-trigger/crons/commands/cron-trigger.cron.command';
|
||||
import { CronTriggerCronJob } from 'src/engine/metadata-modules/cron-trigger/crons/jobs/cron-trigger.cron.job';
|
||||
import { ServerlessFunctionEntity } from 'src/engine/metadata-modules/serverless-function/serverless-function.entity';
|
||||
import { LogicFunctionEntity } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([WorkspaceEntity, ServerlessFunctionEntity]),
|
||||
],
|
||||
imports: [TypeOrmModule.forFeature([WorkspaceEntity, LogicFunctionEntity])],
|
||||
providers: [CronTriggerCronJob, CronTriggerCronCommand],
|
||||
exports: [CronTriggerCronCommand],
|
||||
})
|
||||
|
||||
+1
-2
@@ -9,8 +9,7 @@ import {
|
||||
} from 'src/engine/metadata-modules/cron-trigger/crons/jobs/cron-trigger.cron.job';
|
||||
@Command({
|
||||
name: 'cron:trigger:start-cron-trigger',
|
||||
description:
|
||||
'Starts a cron job to trigger cron triggered serverless functions',
|
||||
description: 'Starts a cron job to trigger cron triggered logic functions',
|
||||
})
|
||||
export class CronTriggerCronCommand extends CommandRunner {
|
||||
constructor(
|
||||
|
||||
+15
-15
@@ -12,10 +12,10 @@ import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queu
|
||||
import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
|
||||
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
|
||||
import {
|
||||
ServerlessFunctionTriggerJob,
|
||||
ServerlessFunctionTriggerJobData,
|
||||
} from 'src/engine/metadata-modules/serverless-function/jobs/serverless-function-trigger.job';
|
||||
import { ServerlessFunctionEntity } from 'src/engine/metadata-modules/serverless-function/serverless-function.entity';
|
||||
LogicFunctionTriggerJob,
|
||||
LogicFunctionTriggerJobData,
|
||||
} 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 { shouldRunNow } from 'src/utils/should-run-now.utils';
|
||||
|
||||
export const CRON_TRIGGER_CRON_PATTERN = '* * * * *';
|
||||
@@ -23,12 +23,12 @@ export const CRON_TRIGGER_CRON_PATTERN = '* * * * *';
|
||||
@Processor(MessageQueue.cronQueue)
|
||||
export class CronTriggerCronJob {
|
||||
constructor(
|
||||
@InjectMessageQueue(MessageQueue.serverlessFunctionQueue)
|
||||
@InjectMessageQueue(MessageQueue.logicFunctionQueue)
|
||||
private readonly messageQueueService: MessageQueueService,
|
||||
@InjectRepository(WorkspaceEntity)
|
||||
private readonly workspaceRepository: Repository<WorkspaceEntity>,
|
||||
@InjectRepository(ServerlessFunctionEntity)
|
||||
private readonly serverlessFunctionRepository: Repository<ServerlessFunctionEntity>,
|
||||
@InjectRepository(LogicFunctionEntity)
|
||||
private readonly logicFunctionRepository: Repository<LogicFunctionEntity>,
|
||||
) {}
|
||||
|
||||
@Process(CronTriggerCronJob.name)
|
||||
@@ -44,8 +44,8 @@ export class CronTriggerCronJob {
|
||||
const now = new Date();
|
||||
|
||||
for (const activeWorkspace of activeWorkspaces) {
|
||||
const serverlessFunctionsWithCronTrigger =
|
||||
await this.serverlessFunctionRepository.find({
|
||||
const logicFunctionsWithCronTrigger =
|
||||
await this.logicFunctionRepository.find({
|
||||
where: {
|
||||
workspaceId: activeWorkspace.id,
|
||||
cronTriggerSettings: Not(IsNull()),
|
||||
@@ -53,8 +53,8 @@ export class CronTriggerCronJob {
|
||||
select: ['id', 'cronTriggerSettings', 'workspaceId'],
|
||||
});
|
||||
|
||||
for (const serverlessFunction of serverlessFunctionsWithCronTrigger) {
|
||||
const cronSettings = serverlessFunction.cronTriggerSettings;
|
||||
for (const logicFunction of logicFunctionsWithCronTrigger) {
|
||||
const cronSettings = logicFunction.cronTriggerSettings;
|
||||
|
||||
if (!isDefined(cronSettings?.pattern)) {
|
||||
continue;
|
||||
@@ -64,12 +64,12 @@ export class CronTriggerCronJob {
|
||||
continue;
|
||||
}
|
||||
|
||||
await this.messageQueueService.add<ServerlessFunctionTriggerJobData[]>(
|
||||
ServerlessFunctionTriggerJob.name,
|
||||
await this.messageQueueService.add<LogicFunctionTriggerJobData[]>(
|
||||
LogicFunctionTriggerJob.name,
|
||||
[
|
||||
{
|
||||
serverlessFunctionId: serverlessFunction.id,
|
||||
workspaceId: serverlessFunction.workspaceId,
|
||||
logicFunctionId: logicFunction.id,
|
||||
workspaceId: logicFunction.workspaceId,
|
||||
payload: {},
|
||||
},
|
||||
],
|
||||
|
||||
+2
-2
@@ -2,10 +2,10 @@ import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
|
||||
import { CallDatabaseEventTriggerJobsJob } from 'src/engine/metadata-modules/database-event-trigger/jobs/call-database-event-trigger-jobs.job';
|
||||
import { ServerlessFunctionEntity } from 'src/engine/metadata-modules/serverless-function/serverless-function.entity';
|
||||
import { LogicFunctionEntity } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([ServerlessFunctionEntity])],
|
||||
imports: [TypeOrmModule.forFeature([LogicFunctionEntity])],
|
||||
providers: [CallDatabaseEventTriggerJobsJob],
|
||||
exports: [],
|
||||
})
|
||||
|
||||
+22
-22
@@ -13,10 +13,10 @@ import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queu
|
||||
import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
|
||||
import { transformEventBatchToEventPayloads } from 'src/engine/metadata-modules/database-event-trigger/utils/transform-event-batch-to-event-payloads';
|
||||
import {
|
||||
ServerlessFunctionTriggerJob,
|
||||
ServerlessFunctionTriggerJobData,
|
||||
} from 'src/engine/metadata-modules/serverless-function/jobs/serverless-function-trigger.job';
|
||||
import { ServerlessFunctionEntity } from 'src/engine/metadata-modules/serverless-function/serverless-function.entity';
|
||||
LogicFunctionTriggerJob,
|
||||
LogicFunctionTriggerJobData,
|
||||
} 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 { WorkspaceEventBatch } from 'src/engine/workspace-event-emitter/types/workspace-event-batch.type';
|
||||
|
||||
const DATABASE_EVENT_JOBS_CHUNK_SIZE = 20;
|
||||
@@ -24,16 +24,16 @@ const DATABASE_EVENT_JOBS_CHUNK_SIZE = 20;
|
||||
@Processor(MessageQueue.triggerQueue)
|
||||
export class CallDatabaseEventTriggerJobsJob {
|
||||
constructor(
|
||||
@InjectMessageQueue(MessageQueue.serverlessFunctionQueue)
|
||||
@InjectMessageQueue(MessageQueue.logicFunctionQueue)
|
||||
private readonly messageQueueService: MessageQueueService,
|
||||
@InjectRepository(ServerlessFunctionEntity)
|
||||
private readonly serverlessFunctionRepository: Repository<ServerlessFunctionEntity>,
|
||||
@InjectRepository(LogicFunctionEntity)
|
||||
private readonly logicFunctionRepository: Repository<LogicFunctionEntity>,
|
||||
) {}
|
||||
|
||||
@Process(CallDatabaseEventTriggerJobsJob.name)
|
||||
async handle(workspaceEventBatch: WorkspaceEventBatch<ObjectRecordEvent>) {
|
||||
const serverlessFunctionsWithDatabaseEventTrigger =
|
||||
await this.serverlessFunctionRepository.find({
|
||||
const logicFunctionsWithDatabaseEventTrigger =
|
||||
await this.logicFunctionRepository.find({
|
||||
where: {
|
||||
workspaceId: workspaceEventBatch.workspaceId,
|
||||
databaseEventTriggerSettings: Not(IsNull()),
|
||||
@@ -41,34 +41,34 @@ export class CallDatabaseEventTriggerJobsJob {
|
||||
select: ['id', 'databaseEventTriggerSettings', 'workspaceId'],
|
||||
});
|
||||
|
||||
const serverlessFunctionsToTrigger =
|
||||
serverlessFunctionsWithDatabaseEventTrigger.filter((serverlessFunction) =>
|
||||
const logicFunctionsToTrigger =
|
||||
logicFunctionsWithDatabaseEventTrigger.filter((logicFunction) =>
|
||||
this.shouldTriggerJob({
|
||||
workspaceEventBatch,
|
||||
eventName: isDefined(serverlessFunction.databaseEventTriggerSettings)
|
||||
? serverlessFunction.databaseEventTriggerSettings.eventName
|
||||
eventName: isDefined(logicFunction.databaseEventTriggerSettings)
|
||||
? logicFunction.databaseEventTriggerSettings.eventName
|
||||
: '',
|
||||
}),
|
||||
);
|
||||
|
||||
const serverlessFunctionPayloads = transformEventBatchToEventPayloads({
|
||||
serverlessFunctions: serverlessFunctionsToTrigger,
|
||||
const logicFunctionPayloads = transformEventBatchToEventPayloads({
|
||||
logicFunctions: logicFunctionsToTrigger,
|
||||
workspaceEventBatch,
|
||||
});
|
||||
|
||||
if (serverlessFunctionPayloads.length === 0) {
|
||||
if (logicFunctionPayloads.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const serverlessFunctionPayloadsChunks = chunk(
|
||||
serverlessFunctionPayloads,
|
||||
const logicFunctionPayloadsChunks = chunk(
|
||||
logicFunctionPayloads,
|
||||
DATABASE_EVENT_JOBS_CHUNK_SIZE,
|
||||
);
|
||||
|
||||
for (const serverlessFunctionPayloadsChunk of serverlessFunctionPayloadsChunks) {
|
||||
await this.messageQueueService.add<ServerlessFunctionTriggerJobData[]>(
|
||||
ServerlessFunctionTriggerJob.name,
|
||||
serverlessFunctionPayloadsChunk,
|
||||
for (const logicFunctionPayloadsChunk of logicFunctionPayloadsChunks) {
|
||||
await this.messageQueueService.add<LogicFunctionTriggerJobData[]>(
|
||||
LogicFunctionTriggerJob.name,
|
||||
logicFunctionPayloadsChunk,
|
||||
{ retryLimit: 3 },
|
||||
);
|
||||
}
|
||||
|
||||
+43
-43
@@ -2,12 +2,12 @@ import type { ObjectRecordEvent } from 'twenty-shared/database-events';
|
||||
|
||||
import { transformEventBatchToEventPayloads } from 'src/engine/metadata-modules/database-event-trigger/utils/transform-event-batch-to-event-payloads';
|
||||
import { getFlatObjectMetadataMock } from 'src/engine/metadata-modules/flat-object-metadata/__mocks__/get-flat-object-metadata.mock';
|
||||
import { type ServerlessFunctionEntity } from 'src/engine/metadata-modules/serverless-function/serverless-function.entity';
|
||||
import { type LogicFunctionEntity } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
|
||||
import type { WorkspaceEventBatch } from 'src/engine/workspace-event-emitter/types/workspace-event-batch.type';
|
||||
|
||||
const createMockServerlessFunction = (
|
||||
overrides: Partial<ServerlessFunctionEntity> = {},
|
||||
): ServerlessFunctionEntity =>
|
||||
const createMockLogicFunction = (
|
||||
overrides: Partial<LogicFunctionEntity> = {},
|
||||
): LogicFunctionEntity =>
|
||||
({
|
||||
id: 'function-1',
|
||||
workspaceId: 'workspace-1',
|
||||
@@ -15,7 +15,7 @@ const createMockServerlessFunction = (
|
||||
eventName: 'company.updated',
|
||||
},
|
||||
...overrides,
|
||||
}) as ServerlessFunctionEntity;
|
||||
}) as LogicFunctionEntity;
|
||||
|
||||
const createMockEvent = (
|
||||
overrides: Partial<ObjectRecordEvent> = {},
|
||||
@@ -43,18 +43,18 @@ const createMockWorkspaceEventBatch = (
|
||||
|
||||
describe('transformEventBatchToEventPayloads', () => {
|
||||
describe('basic transformation', () => {
|
||||
it('should transform a single event batch with a single serverless function', () => {
|
||||
it('should transform a single event batch with a single logic function', () => {
|
||||
const workspaceEventBatch = createMockWorkspaceEventBatch();
|
||||
const serverlessFunctions = [createMockServerlessFunction()];
|
||||
const logicFunctions = [createMockLogicFunction()];
|
||||
|
||||
const result = transformEventBatchToEventPayloads({
|
||||
workspaceEventBatch,
|
||||
serverlessFunctions,
|
||||
logicFunctions,
|
||||
});
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toEqual({
|
||||
serverlessFunctionId: 'function-1',
|
||||
logicFunctionId: 'function-1',
|
||||
workspaceId: 'workspace-1',
|
||||
payload: expect.objectContaining({
|
||||
name: 'company.updated',
|
||||
@@ -72,11 +72,11 @@ describe('transformEventBatchToEventPayloads', () => {
|
||||
createMockEvent({ recordId: 'record-3' }),
|
||||
],
|
||||
});
|
||||
const serverlessFunctions = [createMockServerlessFunction()];
|
||||
const logicFunctions = [createMockLogicFunction()];
|
||||
|
||||
const result = transformEventBatchToEventPayloads({
|
||||
workspaceEventBatch,
|
||||
serverlessFunctions,
|
||||
logicFunctions,
|
||||
});
|
||||
|
||||
expect(result).toHaveLength(3);
|
||||
@@ -85,24 +85,24 @@ describe('transformEventBatchToEventPayloads', () => {
|
||||
).toEqual(['record-1', 'record-2', 'record-3']);
|
||||
});
|
||||
|
||||
it('should create payloads for each serverless function', () => {
|
||||
it('should create payloads for each logic function', () => {
|
||||
const workspaceEventBatch = createMockWorkspaceEventBatch();
|
||||
const serverlessFunctions = [
|
||||
createMockServerlessFunction({
|
||||
const logicFunctions = [
|
||||
createMockLogicFunction({
|
||||
id: 'function-1',
|
||||
}),
|
||||
createMockServerlessFunction({
|
||||
createMockLogicFunction({
|
||||
id: 'function-2',
|
||||
}),
|
||||
];
|
||||
|
||||
const result = transformEventBatchToEventPayloads({
|
||||
workspaceEventBatch,
|
||||
serverlessFunctions,
|
||||
logicFunctions,
|
||||
});
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result.map((r) => r.serverlessFunctionId)).toEqual([
|
||||
expect(result.map((r) => r.logicFunctionId)).toEqual([
|
||||
'function-1',
|
||||
'function-2',
|
||||
]);
|
||||
@@ -124,15 +124,15 @@ describe('transformEventBatchToEventPayloads', () => {
|
||||
}),
|
||||
],
|
||||
});
|
||||
const serverlessFunctions = [
|
||||
createMockServerlessFunction({
|
||||
const logicFunctions = [
|
||||
createMockLogicFunction({
|
||||
databaseEventTriggerSettings: { eventName: 'company.updated' },
|
||||
}),
|
||||
];
|
||||
|
||||
const result = transformEventBatchToEventPayloads({
|
||||
workspaceEventBatch,
|
||||
serverlessFunctions,
|
||||
logicFunctions,
|
||||
});
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
@@ -152,8 +152,8 @@ describe('transformEventBatchToEventPayloads', () => {
|
||||
}),
|
||||
],
|
||||
});
|
||||
const serverlessFunctions = [
|
||||
createMockServerlessFunction({
|
||||
const logicFunctions = [
|
||||
createMockLogicFunction({
|
||||
databaseEventTriggerSettings: {
|
||||
eventName: 'company.updated',
|
||||
updatedFields: [],
|
||||
@@ -163,7 +163,7 @@ describe('transformEventBatchToEventPayloads', () => {
|
||||
|
||||
const result = transformEventBatchToEventPayloads({
|
||||
workspaceEventBatch,
|
||||
serverlessFunctions,
|
||||
logicFunctions,
|
||||
});
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
@@ -187,8 +187,8 @@ describe('transformEventBatchToEventPayloads', () => {
|
||||
}),
|
||||
],
|
||||
});
|
||||
const serverlessFunctions = [
|
||||
createMockServerlessFunction({
|
||||
const logicFunctions = [
|
||||
createMockLogicFunction({
|
||||
databaseEventTriggerSettings: {
|
||||
eventName: 'company.updated',
|
||||
updatedFields: ['name'],
|
||||
@@ -198,7 +198,7 @@ describe('transformEventBatchToEventPayloads', () => {
|
||||
|
||||
const result = transformEventBatchToEventPayloads({
|
||||
workspaceEventBatch,
|
||||
serverlessFunctions,
|
||||
logicFunctions,
|
||||
});
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
@@ -225,8 +225,8 @@ describe('transformEventBatchToEventPayloads', () => {
|
||||
}),
|
||||
],
|
||||
});
|
||||
const serverlessFunctions = [
|
||||
createMockServerlessFunction({
|
||||
const logicFunctions = [
|
||||
createMockLogicFunction({
|
||||
databaseEventTriggerSettings: {
|
||||
eventName: 'company.updated',
|
||||
updatedFields: ['name', 'address'],
|
||||
@@ -236,7 +236,7 @@ describe('transformEventBatchToEventPayloads', () => {
|
||||
|
||||
const result = transformEventBatchToEventPayloads({
|
||||
workspaceEventBatch,
|
||||
serverlessFunctions,
|
||||
logicFunctions,
|
||||
});
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
@@ -259,8 +259,8 @@ describe('transformEventBatchToEventPayloads', () => {
|
||||
}),
|
||||
],
|
||||
});
|
||||
const serverlessFunctions = [
|
||||
createMockServerlessFunction({
|
||||
const logicFunctions = [
|
||||
createMockLogicFunction({
|
||||
databaseEventTriggerSettings: {
|
||||
eventName: 'company.updated',
|
||||
updatedFields: ['phone'],
|
||||
@@ -270,13 +270,13 @@ describe('transformEventBatchToEventPayloads', () => {
|
||||
|
||||
const result = transformEventBatchToEventPayloads({
|
||||
workspaceEventBatch,
|
||||
serverlessFunctions,
|
||||
logicFunctions,
|
||||
});
|
||||
|
||||
expect(result).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should handle different updatedFields filters per serverless function', () => {
|
||||
it('should handle different updatedFields filters per logic function', () => {
|
||||
const workspaceEventBatch = createMockWorkspaceEventBatch({
|
||||
name: 'company.updated',
|
||||
events: [
|
||||
@@ -290,15 +290,15 @@ describe('transformEventBatchToEventPayloads', () => {
|
||||
}),
|
||||
],
|
||||
});
|
||||
const serverlessFunctions = [
|
||||
createMockServerlessFunction({
|
||||
const logicFunctions = [
|
||||
createMockLogicFunction({
|
||||
id: 'function-1',
|
||||
databaseEventTriggerSettings: {
|
||||
eventName: 'company.updated',
|
||||
updatedFields: ['name'],
|
||||
},
|
||||
}),
|
||||
createMockServerlessFunction({
|
||||
createMockLogicFunction({
|
||||
id: 'function-2',
|
||||
databaseEventTriggerSettings: {
|
||||
eventName: 'company.updated',
|
||||
@@ -309,16 +309,16 @@ describe('transformEventBatchToEventPayloads', () => {
|
||||
|
||||
const result = transformEventBatchToEventPayloads({
|
||||
workspaceEventBatch,
|
||||
serverlessFunctions,
|
||||
logicFunctions,
|
||||
});
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
|
||||
const function1Payloads = result.filter(
|
||||
(r) => r.serverlessFunctionId === 'function-1',
|
||||
(r) => r.logicFunctionId === 'function-1',
|
||||
);
|
||||
const function2Payloads = result.filter(
|
||||
(r) => r.serverlessFunctionId === 'function-2',
|
||||
(r) => r.logicFunctionId === 'function-2',
|
||||
);
|
||||
|
||||
expect(function1Payloads).toHaveLength(1);
|
||||
@@ -334,12 +334,12 @@ describe('transformEventBatchToEventPayloads', () => {
|
||||
});
|
||||
|
||||
describe('edge cases', () => {
|
||||
it('should return empty array when no serverless functions provided', () => {
|
||||
it('should return empty array when no logic functions provided', () => {
|
||||
const workspaceEventBatch = createMockWorkspaceEventBatch();
|
||||
|
||||
const result = transformEventBatchToEventPayloads({
|
||||
workspaceEventBatch,
|
||||
serverlessFunctions: [],
|
||||
logicFunctions: [],
|
||||
});
|
||||
|
||||
expect(result).toHaveLength(0);
|
||||
@@ -349,11 +349,11 @@ describe('transformEventBatchToEventPayloads', () => {
|
||||
const workspaceEventBatch = createMockWorkspaceEventBatch({
|
||||
events: [],
|
||||
});
|
||||
const serverlessFunctions = [createMockServerlessFunction()];
|
||||
const logicFunctions = [createMockLogicFunction()];
|
||||
|
||||
const result = transformEventBatchToEventPayloads({
|
||||
workspaceEventBatch,
|
||||
serverlessFunctions,
|
||||
logicFunctions,
|
||||
});
|
||||
|
||||
expect(result).toHaveLength(0);
|
||||
|
||||
+10
-10
@@ -5,24 +5,24 @@ import type {
|
||||
ObjectRecordEvent,
|
||||
} from 'twenty-shared/database-events';
|
||||
|
||||
import { type ServerlessFunctionTriggerJobData } from 'src/engine/metadata-modules/serverless-function/jobs/serverless-function-trigger.job';
|
||||
import { type ServerlessFunctionEntity } from 'src/engine/metadata-modules/serverless-function/serverless-function.entity';
|
||||
import { type LogicFunctionTriggerJobData } from 'src/engine/metadata-modules/logic-function/jobs/logic-function-trigger.job';
|
||||
import { type LogicFunctionEntity } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
|
||||
import type { WorkspaceEventBatch } from 'src/engine/workspace-event-emitter/types/workspace-event-batch.type';
|
||||
|
||||
export const transformEventBatchToEventPayloads = ({
|
||||
workspaceEventBatch,
|
||||
serverlessFunctions,
|
||||
logicFunctions,
|
||||
}: {
|
||||
workspaceEventBatch: WorkspaceEventBatch<ObjectRecordEvent>;
|
||||
serverlessFunctions: ServerlessFunctionEntity[];
|
||||
}): ServerlessFunctionTriggerJobData[] => {
|
||||
const result: ServerlessFunctionTriggerJobData[] = [];
|
||||
logicFunctions: LogicFunctionEntity[];
|
||||
}): LogicFunctionTriggerJobData[] => {
|
||||
const result: LogicFunctionTriggerJobData[] = [];
|
||||
const { events, ...batchEventInfo } = workspaceEventBatch;
|
||||
const [, operation] = workspaceEventBatch.name.split('.');
|
||||
|
||||
for (const serverlessFunction of serverlessFunctions) {
|
||||
for (const logicFunction of logicFunctions) {
|
||||
const triggerUpdatedFields =
|
||||
serverlessFunction.databaseEventTriggerSettings?.updatedFields;
|
||||
logicFunction.databaseEventTriggerSettings?.updatedFields;
|
||||
|
||||
const filteredEvents = filterEventsByUpdatedFields({
|
||||
events,
|
||||
@@ -34,8 +34,8 @@ export const transformEventBatchToEventPayloads = ({
|
||||
const payload: DatabaseEventPayload = { ...batchEventInfo, ...event };
|
||||
|
||||
result.push({
|
||||
serverlessFunctionId: serverlessFunction.id,
|
||||
workspaceId: serverlessFunction.workspaceId,
|
||||
logicFunctionId: logicFunction.id,
|
||||
workspaceId: logicFunction.workspaceId,
|
||||
payload,
|
||||
});
|
||||
}
|
||||
|
||||
+3
-15
@@ -20,7 +20,7 @@ import { FLAT_VIEW_FILTER_GROUP_EDITABLE_PROPERTIES } from 'src/engine/metadata-
|
||||
import { FLAT_VIEW_FILTER_EDITABLE_PROPERTIES } from 'src/engine/metadata-modules/flat-view-filter/constants/flat-view-filter-editable-properties.constant';
|
||||
import { FLAT_VIEW_GROUP_EDITABLE_PROPERTIES } from 'src/engine/metadata-modules/flat-view-group/constants/flat-view-group-editable-properties.constant';
|
||||
import { FLAT_VIEW_EDITABLE_PROPERTIES } from 'src/engine/metadata-modules/flat-view/constants/flat-view-editable-properties.constant';
|
||||
import { FLAT_SERVERLESS_FUNCTION_EDITABLE_PROPERTIES } from 'src/engine/metadata-modules/serverless-function/constants/flat-serverless-function-editable-properties.constant';
|
||||
import { FLAT_LOGIC_FUNCTION_EDITABLE_PROPERTIES } from 'src/engine/metadata-modules/logic-function/constants/flat-logic-function-editable-properties.constant';
|
||||
|
||||
type OneFlatEntityConfiguration<T extends AllMetadataName> = {
|
||||
propertiesToCompare: (keyof MetadataFlatEntity<T>)[];
|
||||
@@ -73,9 +73,9 @@ export const ALL_FLAT_ENTITY_PROPERTIES_TO_COMPARE_AND_STRINGIFY = {
|
||||
],
|
||||
propertiesToStringify: ['flatIndexFieldMetadatas'],
|
||||
},
|
||||
serverlessFunction: {
|
||||
logicFunction: {
|
||||
propertiesToCompare: [
|
||||
...FLAT_SERVERLESS_FUNCTION_EDITABLE_PROPERTIES.filter(
|
||||
...FLAT_LOGIC_FUNCTION_EDITABLE_PROPERTIES.filter(
|
||||
(property) => property !== 'code',
|
||||
),
|
||||
'deletedAt',
|
||||
@@ -84,18 +84,6 @@ export const ALL_FLAT_ENTITY_PROPERTIES_TO_COMPARE_AND_STRINGIFY = {
|
||||
],
|
||||
propertiesToStringify: ['toolInputSchema', 'publishedVersions'],
|
||||
},
|
||||
cronTrigger: {
|
||||
propertiesToCompare: [],
|
||||
propertiesToStringify: [],
|
||||
},
|
||||
databaseEventTrigger: {
|
||||
propertiesToCompare: [],
|
||||
propertiesToStringify: [],
|
||||
},
|
||||
routeTrigger: {
|
||||
propertiesToCompare: [],
|
||||
propertiesToStringify: [],
|
||||
},
|
||||
viewFilter: {
|
||||
propertiesToCompare: [
|
||||
'viewId',
|
||||
|
||||
+2
-5
@@ -16,7 +16,7 @@ import { RoleTargetEntity } from 'src/engine/metadata-modules/role-target/role-t
|
||||
import { RoleEntity } from 'src/engine/metadata-modules/role/role.entity';
|
||||
import { RowLevelPermissionPredicateGroupEntity } from 'src/engine/metadata-modules/row-level-permission-predicate/entities/row-level-permission-predicate-group.entity';
|
||||
import { RowLevelPermissionPredicateEntity } from 'src/engine/metadata-modules/row-level-permission-predicate/entities/row-level-permission-predicate.entity';
|
||||
import { ServerlessFunctionEntity } from 'src/engine/metadata-modules/serverless-function/serverless-function.entity';
|
||||
import { LogicFunctionEntity } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
|
||||
import { SkillEntity } from 'src/engine/metadata-modules/skill/entities/skill.entity';
|
||||
import { ViewFieldEntity } from 'src/engine/metadata-modules/view-field/entities/view-field.entity';
|
||||
import { ViewFilterGroupEntity } from 'src/engine/metadata-modules/view-filter-group/entities/view-filter-group.entity';
|
||||
@@ -36,14 +36,11 @@ export const ALL_METADATA_ENTITY_BY_METADATA_NAME = {
|
||||
view: ViewEntity,
|
||||
index: IndexMetadataEntity,
|
||||
pageLayoutTab: PageLayoutTabEntity,
|
||||
routeTrigger: ServerlessFunctionEntity,
|
||||
cronTrigger: ServerlessFunctionEntity,
|
||||
databaseEventTrigger: ServerlessFunctionEntity,
|
||||
frontComponent: FrontComponentEntity,
|
||||
fieldMetadata: FieldMetadataEntity,
|
||||
pageLayout: PageLayoutEntity,
|
||||
skill: SkillEntity,
|
||||
serverlessFunction: ServerlessFunctionEntity,
|
||||
logicFunction: LogicFunctionEntity,
|
||||
objectMetadata: ObjectMetadataEntity,
|
||||
role: RoleEntity,
|
||||
agent: AgentEntity,
|
||||
|
||||
+2
-26
@@ -261,35 +261,11 @@ export const ALL_METADATA_RELATIONS = {
|
||||
indexFieldMetadatas: null,
|
||||
},
|
||||
},
|
||||
serverlessFunction: {
|
||||
logicFunction: {
|
||||
manyToOne: {
|
||||
workspace: null,
|
||||
application: null,
|
||||
serverlessFunctionLayer: null,
|
||||
},
|
||||
oneToMany: {},
|
||||
},
|
||||
cronTrigger: {
|
||||
manyToOne: {
|
||||
application: null,
|
||||
serverlessFunctionLayer: null,
|
||||
workspace: null,
|
||||
},
|
||||
oneToMany: {},
|
||||
},
|
||||
databaseEventTrigger: {
|
||||
manyToOne: {
|
||||
application: null,
|
||||
serverlessFunctionLayer: null,
|
||||
workspace: null,
|
||||
},
|
||||
oneToMany: {},
|
||||
},
|
||||
routeTrigger: {
|
||||
manyToOne: {
|
||||
application: null,
|
||||
serverlessFunctionLayer: null,
|
||||
workspace: null,
|
||||
logicFunctionLayer: null,
|
||||
},
|
||||
oneToMany: {},
|
||||
},
|
||||
|
||||
+1
-10
@@ -31,16 +31,7 @@ export const ALL_METADATA_REQUIRED_METADATA_FOR_VALIDATION = {
|
||||
objectMetadata: true,
|
||||
fieldMetadata: true,
|
||||
},
|
||||
serverlessFunction: {},
|
||||
cronTrigger: {
|
||||
serverlessFunction: true,
|
||||
},
|
||||
databaseEventTrigger: {
|
||||
serverlessFunction: true,
|
||||
},
|
||||
routeTrigger: {
|
||||
serverlessFunction: true,
|
||||
},
|
||||
logicFunction: {},
|
||||
viewFilter: {
|
||||
view: true,
|
||||
fieldMetadata: true,
|
||||
|
||||
+11
-38
@@ -21,7 +21,7 @@ import { type FlatView } from 'src/engine/metadata-modules/flat-view/types/flat-
|
||||
import { type NavigationMenuItemEntity } from 'src/engine/metadata-modules/navigation-menu-item/entities/navigation-menu-item.entity';
|
||||
import { type FlatRowLevelPermissionPredicateGroup } from 'src/engine/metadata-modules/row-level-permission-predicate/types/flat-row-level-permission-predicate-group.type';
|
||||
import { type FlatRowLevelPermissionPredicate } from 'src/engine/metadata-modules/row-level-permission-predicate/types/flat-row-level-permission-predicate.type';
|
||||
import { type FlatServerlessFunction } from 'src/engine/metadata-modules/serverless-function/types/flat-serverless-function.type';
|
||||
import { type FlatLogicFunction } from 'src/engine/metadata-modules/logic-function/types/flat-logic-function.type';
|
||||
import {
|
||||
type CreateAgentAction,
|
||||
type DeleteAgentAction,
|
||||
@@ -93,10 +93,10 @@ import {
|
||||
type UpdateRowLevelPermissionPredicateAction,
|
||||
} from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/row-level-permission-predicate/types/workspace-migration-row-level-permission-predicate-action.type';
|
||||
import {
|
||||
type CreateServerlessFunctionAction,
|
||||
type DeleteServerlessFunctionAction,
|
||||
type UpdateServerlessFunctionAction,
|
||||
} from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/serverless-function/types/workspace-migration-serverless-function-action.type';
|
||||
type CreateLogicFunctionAction,
|
||||
type DeleteLogicFunctionAction,
|
||||
type UpdateLogicFunctionAction,
|
||||
} from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/logic-function/types/workspace-migration-logic-function-action.type';
|
||||
import {
|
||||
type CreateSkillAction,
|
||||
type DeleteSkillAction,
|
||||
@@ -215,41 +215,14 @@ export type AllFlatEntityTypesByMetadataName = {
|
||||
flatEntity: FlatIndexMetadata;
|
||||
entity: MetadataEntity<'index'>;
|
||||
};
|
||||
serverlessFunction: {
|
||||
logicFunction: {
|
||||
actions: {
|
||||
create: CreateServerlessFunctionAction;
|
||||
update: UpdateServerlessFunctionAction;
|
||||
delete: DeleteServerlessFunctionAction;
|
||||
create: CreateLogicFunctionAction;
|
||||
update: UpdateLogicFunctionAction;
|
||||
delete: DeleteLogicFunctionAction;
|
||||
};
|
||||
flatEntity: FlatServerlessFunction;
|
||||
entity: MetadataEntity<'serverlessFunction'>;
|
||||
};
|
||||
cronTrigger: {
|
||||
actions: {
|
||||
create: never;
|
||||
update: never;
|
||||
delete: never;
|
||||
};
|
||||
flatEntity: FlatServerlessFunction;
|
||||
entity: MetadataEntity<'serverlessFunction'>;
|
||||
};
|
||||
databaseEventTrigger: {
|
||||
actions: {
|
||||
create: never;
|
||||
update: never;
|
||||
delete: never;
|
||||
};
|
||||
flatEntity: FlatServerlessFunction;
|
||||
entity: MetadataEntity<'serverlessFunction'>;
|
||||
};
|
||||
routeTrigger: {
|
||||
actions: {
|
||||
create: never;
|
||||
update: never;
|
||||
delete: never;
|
||||
};
|
||||
flatEntity: FlatServerlessFunction;
|
||||
entity: MetadataEntity<'serverlessFunction'>;
|
||||
flatEntity: FlatLogicFunction;
|
||||
entity: MetadataEntity<'logicFunction'>;
|
||||
};
|
||||
viewFilter: {
|
||||
actions: {
|
||||
|
||||
+2
-8
@@ -8,10 +8,6 @@ exports[`getMetadataRelatedMetadataNames should return related metadata names fo
|
||||
]
|
||||
`;
|
||||
|
||||
exports[`getMetadataRelatedMetadataNames should return related metadata names for cronTrigger 1`] = `[]`;
|
||||
|
||||
exports[`getMetadataRelatedMetadataNames should return related metadata names for databaseEventTrigger 1`] = `[]`;
|
||||
|
||||
exports[`getMetadataRelatedMetadataNames should return related metadata names for fieldMetadata 1`] = `
|
||||
[
|
||||
"objectMetadata",
|
||||
@@ -30,6 +26,8 @@ exports[`getMetadataRelatedMetadataNames should return related metadata names fo
|
||||
]
|
||||
`;
|
||||
|
||||
exports[`getMetadataRelatedMetadataNames should return related metadata names for logicFunction 1`] = `[]`;
|
||||
|
||||
exports[`getMetadataRelatedMetadataNames should return related metadata names for navigationMenuItem 1`] = `
|
||||
[
|
||||
"objectMetadata",
|
||||
@@ -81,8 +79,6 @@ exports[`getMetadataRelatedMetadataNames should return related metadata names fo
|
||||
]
|
||||
`;
|
||||
|
||||
exports[`getMetadataRelatedMetadataNames should return related metadata names for routeTrigger 1`] = `[]`;
|
||||
|
||||
exports[`getMetadataRelatedMetadataNames should return related metadata names for rowLevelPermissionPredicate 1`] = `
|
||||
[
|
||||
"role",
|
||||
@@ -101,8 +97,6 @@ exports[`getMetadataRelatedMetadataNames should return related metadata names fo
|
||||
]
|
||||
`;
|
||||
|
||||
exports[`getMetadataRelatedMetadataNames should return related metadata names for serverlessFunction 1`] = `[]`;
|
||||
|
||||
exports[`getMetadataRelatedMetadataNames should return related metadata names for skill 1`] = `[]`;
|
||||
|
||||
exports[`getMetadataRelatedMetadataNames should return related metadata names for view 1`] = `
|
||||
|
||||
+1
-4
@@ -13,13 +13,10 @@ exports[`sortMetadataNamesChildrenFirst should return metadata names sorted with
|
||||
"rowLevelPermissionPredicateGroup",
|
||||
"viewGroup",
|
||||
"agent",
|
||||
"cronTrigger",
|
||||
"databaseEventTrigger",
|
||||
"frontComponent",
|
||||
"logicFunction",
|
||||
"pageLayout",
|
||||
"pageLayoutTab",
|
||||
"routeTrigger",
|
||||
"serverlessFunction",
|
||||
"skill",
|
||||
"view",
|
||||
"viewFilterGroup",
|
||||
|
||||
+18
-18
@@ -7,47 +7,47 @@ import { build } from 'esbuild';
|
||||
import { FileFolder } from 'twenty-shared/types';
|
||||
|
||||
import { FileStorageService } from 'src/engine/core-modules/file-storage/file-storage.service';
|
||||
import { LambdaBuildDirectoryManager } from 'src/engine/core-modules/serverless/drivers/utils/lambda-build-directory-manager';
|
||||
import { getServerlessFolderOrThrow } from 'src/engine/core-modules/serverless/utils/get-serverless-folder-or-throw.utils';
|
||||
import { type FlatServerlessFunction } from 'src/engine/metadata-modules/serverless-function/types/flat-serverless-function.type';
|
||||
import { LambdaBuildDirectoryManager } from 'src/engine/core-modules/logic-function-executor/drivers/utils/lambda-build-directory-manager';
|
||||
import { getLogicFunctionFolderOrThrow } from 'src/engine/core-modules/logic-function-executor/utils/get-logic-function-folder-or-throw.utils';
|
||||
import { type FlatLogicFunction } from 'src/engine/metadata-modules/logic-function/types/flat-logic-function.type';
|
||||
|
||||
@Injectable()
|
||||
export class FunctionBuildService {
|
||||
constructor(private readonly fileStorageService: FileStorageService) {}
|
||||
|
||||
async isBuilt({
|
||||
flatServerlessFunction,
|
||||
flatLogicFunction,
|
||||
version,
|
||||
}: {
|
||||
flatServerlessFunction: FlatServerlessFunction;
|
||||
flatLogicFunction: FlatLogicFunction;
|
||||
version: string;
|
||||
}): Promise<boolean> {
|
||||
const folderPath = getServerlessFolderOrThrow({
|
||||
flatServerlessFunction,
|
||||
const folderPath = getLogicFunctionFolderOrThrow({
|
||||
flatLogicFunction,
|
||||
version,
|
||||
});
|
||||
|
||||
return await this.fileStorageService.checkFileExists({
|
||||
folderPath,
|
||||
filename: flatServerlessFunction.builtHandlerPath,
|
||||
filename: flatLogicFunction.builtHandlerPath,
|
||||
});
|
||||
}
|
||||
|
||||
async buildAndUpload({
|
||||
flatServerlessFunction,
|
||||
flatLogicFunction,
|
||||
version,
|
||||
}: {
|
||||
flatServerlessFunction: FlatServerlessFunction;
|
||||
flatLogicFunction: FlatLogicFunction;
|
||||
version: string;
|
||||
}): Promise<void> {
|
||||
const sourceFolderPath = getServerlessFolderOrThrow({
|
||||
flatServerlessFunction,
|
||||
const sourceFolderPath = getLogicFunctionFolderOrThrow({
|
||||
flatLogicFunction,
|
||||
version,
|
||||
fileFolder: FileFolder.ServerlessFunction,
|
||||
fileFolder: FileFolder.LogicFunction,
|
||||
});
|
||||
|
||||
const builtFolderPath = getServerlessFolderOrThrow({
|
||||
flatServerlessFunction,
|
||||
const builtFolderPath = getLogicFunctionFolderOrThrow({
|
||||
flatLogicFunction,
|
||||
version,
|
||||
fileFolder: FileFolder.BuiltFunction,
|
||||
});
|
||||
@@ -64,15 +64,15 @@ export class FunctionBuildService {
|
||||
|
||||
const builtBundleFilePath = await this.buildInMemory({
|
||||
sourceTemporaryDir,
|
||||
sourceHandlerPath: flatServerlessFunction.sourceHandlerPath,
|
||||
builtHandlerPath: flatServerlessFunction.builtHandlerPath,
|
||||
sourceHandlerPath: flatLogicFunction.sourceHandlerPath,
|
||||
builtHandlerPath: flatLogicFunction.builtHandlerPath,
|
||||
});
|
||||
|
||||
const builtFile = await fs.readFile(builtBundleFilePath, 'utf-8');
|
||||
|
||||
await this.fileStorageService.write({
|
||||
file: builtFile,
|
||||
name: flatServerlessFunction.builtHandlerPath,
|
||||
name: flatLogicFunction.builtHandlerPath,
|
||||
mimeType: 'application/javascript',
|
||||
folder: builtFolderPath,
|
||||
});
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ import GraphQLJSON from 'graphql-type-json';
|
||||
import { PackageJson } from 'twenty-shared/application';
|
||||
|
||||
@ArgsType()
|
||||
export class CreateServerlessFunctionLayerInput {
|
||||
export class CreateLogicFunctionLayerInput {
|
||||
@Field(() => GraphQLJSON, { nullable: false })
|
||||
packageJson: PackageJson;
|
||||
|
||||
+2
-2
@@ -5,8 +5,8 @@ import { IDField } from '@ptc-org/nestjs-query-graphql';
|
||||
|
||||
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
|
||||
|
||||
@ObjectType('ServerlessFunctionLayer')
|
||||
export class ServerlessFunctionLayerDTO {
|
||||
@ObjectType('LogicFunctionLayer')
|
||||
export class LogicFunctionLayerDTO {
|
||||
@IDField(() => UUIDScalarType)
|
||||
id: string;
|
||||
|
||||
+6
-6
@@ -9,11 +9,11 @@ import {
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
|
||||
import { ServerlessFunctionEntity } from 'src/engine/metadata-modules/serverless-function/serverless-function.entity';
|
||||
import { LogicFunctionEntity } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
|
||||
import { WorkspaceRelatedEntity } from 'src/engine/workspace-manager/types/workspace-related-entity';
|
||||
|
||||
@Entity('serverlessFunctionLayer')
|
||||
export class ServerlessFunctionLayerEntity extends WorkspaceRelatedEntity {
|
||||
@Entity('logicFunctionLayer')
|
||||
export class LogicFunctionLayerEntity extends WorkspaceRelatedEntity {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@@ -27,13 +27,13 @@ export class ServerlessFunctionLayerEntity extends WorkspaceRelatedEntity {
|
||||
checksum: string;
|
||||
|
||||
@OneToMany(
|
||||
() => ServerlessFunctionEntity,
|
||||
(serverlessFunction) => serverlessFunction.serverlessFunctionLayer,
|
||||
() => LogicFunctionEntity,
|
||||
(logicFunction) => logicFunction.logicFunctionLayer,
|
||||
{
|
||||
onDelete: 'RESTRICT',
|
||||
},
|
||||
)
|
||||
serverlessFunctions: Relation<ServerlessFunctionEntity[]>;
|
||||
logicFunctions: Relation<LogicFunctionEntity[]>;
|
||||
|
||||
@CreateDateColumn({ type: 'timestamptz' })
|
||||
createdAt: Date;
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
|
||||
import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permissions.module';
|
||||
import { LogicFunctionLayerEntity } from 'src/engine/metadata-modules/logic-function-layer/logic-function-layer.entity';
|
||||
import { LogicFunctionLayerResolver } from 'src/engine/metadata-modules/logic-function-layer/logic-function-layer.resolver';
|
||||
import { LogicFunctionLayerService } from 'src/engine/metadata-modules/logic-function-layer/logic-function-layer.service';
|
||||
import { WorkspaceLogicFunctionLayerMapCacheService } from 'src/engine/metadata-modules/logic-function-layer/services/workspace-logic-function-layer-map-cache.service';
|
||||
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
PermissionsModule,
|
||||
TypeOrmModule.forFeature([LogicFunctionLayerEntity]),
|
||||
WorkspaceCacheModule,
|
||||
],
|
||||
providers: [
|
||||
LogicFunctionLayerService,
|
||||
LogicFunctionLayerResolver,
|
||||
WorkspaceLogicFunctionLayerMapCacheService,
|
||||
],
|
||||
exports: [
|
||||
LogicFunctionLayerService,
|
||||
WorkspaceLogicFunctionLayerMapCacheService,
|
||||
],
|
||||
})
|
||||
export class LogicFunctionLayerModule {}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
import { UseGuards } from '@nestjs/common';
|
||||
import { Args, Mutation, Resolver } from '@nestjs/graphql';
|
||||
|
||||
import { PermissionFlagType } from 'twenty-shared/constants';
|
||||
|
||||
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
|
||||
import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
|
||||
import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';
|
||||
import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
|
||||
import { CreateLogicFunctionLayerInput } from 'src/engine/metadata-modules/logic-function-layer/dtos/create-logic-function-layer.input';
|
||||
import { LogicFunctionLayerDTO } from 'src/engine/metadata-modules/logic-function-layer/dtos/logic-function-layer.dto';
|
||||
import { LogicFunctionLayerService } from 'src/engine/metadata-modules/logic-function-layer/logic-function-layer.service';
|
||||
|
||||
@UseGuards(WorkspaceAuthGuard)
|
||||
@Resolver()
|
||||
export class LogicFunctionLayerResolver {
|
||||
constructor(
|
||||
private readonly logicFunctionLayerService: LogicFunctionLayerService,
|
||||
) {}
|
||||
|
||||
@Mutation(() => LogicFunctionLayerDTO)
|
||||
@UseGuards(SettingsPermissionGuard(PermissionFlagType.WORKFLOWS))
|
||||
async createOneLogicFunctionLayer(
|
||||
@Args()
|
||||
createLogicFunctionLayerInput: CreateLogicFunctionLayerInput,
|
||||
@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
|
||||
) {
|
||||
return this.logicFunctionLayerService.create(
|
||||
createLogicFunctionLayerInput,
|
||||
workspaceId,
|
||||
);
|
||||
}
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
|
||||
import { Repository } from 'typeorm';
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
|
||||
import type { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
|
||||
|
||||
import { LogicFunctionLayerEntity } from 'src/engine/metadata-modules/logic-function-layer/logic-function-layer.entity';
|
||||
import { CreateLogicFunctionLayerInput } from 'src/engine/metadata-modules/logic-function-layer/dtos/create-logic-function-layer.input';
|
||||
import { getLastCommonLayerDependencies } from 'src/engine/core-modules/logic-function-executor/drivers/utils/get-last-common-layer-dependencies';
|
||||
import { logicFunctionCreateHash } from 'src/engine/metadata-modules/logic-function/utils/logic-function-create-hash.utils';
|
||||
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
|
||||
|
||||
@Injectable()
|
||||
export class LogicFunctionLayerService {
|
||||
constructor(
|
||||
@InjectRepository(LogicFunctionLayerEntity)
|
||||
private readonly logicFunctionLayerRepository: Repository<LogicFunctionLayerEntity>,
|
||||
private readonly workspaceCacheService: WorkspaceCacheService,
|
||||
) {}
|
||||
|
||||
async create(
|
||||
{ packageJson, yarnLock }: CreateLogicFunctionLayerInput,
|
||||
workspaceId: string,
|
||||
) {
|
||||
const checksum = logicFunctionCreateHash(yarnLock);
|
||||
|
||||
const logicFunctionLayer = this.logicFunctionLayerRepository.create({
|
||||
packageJson,
|
||||
yarnLock,
|
||||
checksum,
|
||||
workspaceId,
|
||||
});
|
||||
|
||||
const savedLayer =
|
||||
await this.logicFunctionLayerRepository.save(logicFunctionLayer);
|
||||
|
||||
await this.workspaceCacheService.invalidateAndRecompute(workspaceId, [
|
||||
'logicFunctionLayerMaps',
|
||||
]);
|
||||
|
||||
return savedLayer;
|
||||
}
|
||||
|
||||
async update(
|
||||
id: string,
|
||||
data: QueryDeepPartialEntity<LogicFunctionLayerEntity>,
|
||||
workspaceId: string,
|
||||
) {
|
||||
const checksum = data.yarnLock
|
||||
? logicFunctionCreateHash(data.yarnLock as string)
|
||||
: undefined;
|
||||
|
||||
const updateData = { ...data, ...(checksum && { checksum }) };
|
||||
|
||||
const result = await this.logicFunctionLayerRepository.update(
|
||||
id,
|
||||
updateData,
|
||||
);
|
||||
|
||||
await this.workspaceCacheService.invalidateAndRecompute(workspaceId, [
|
||||
'logicFunctionLayerMaps',
|
||||
]);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async createCommonLayerIfNotExist(workspaceId: string) {
|
||||
const { packageJson, yarnLock } = await getLastCommonLayerDependencies();
|
||||
const checksum = logicFunctionCreateHash(yarnLock);
|
||||
const commonLayer = await this.logicFunctionLayerRepository.findOne({
|
||||
where: {
|
||||
checksum,
|
||||
workspaceId,
|
||||
},
|
||||
});
|
||||
|
||||
if (isDefined(commonLayer)) {
|
||||
return commonLayer;
|
||||
}
|
||||
|
||||
return this.create({ packageJson, yarnLock }, workspaceId);
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
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 { LogicFunctionLayerEntity } from 'src/engine/metadata-modules/logic-function-layer/logic-function-layer.entity';
|
||||
import { type LogicFunctionLayerCacheMaps } from 'src/engine/metadata-modules/logic-function-layer/types/logic-function-layer-cache-maps.type';
|
||||
import { fromLogicFunctionLayerEntityToFlatLogicFunctionLayer } from 'src/engine/metadata-modules/logic-function-layer/utils/from-logic-function-layer-entity-to-flat-logic-function-layer.util';
|
||||
import { WorkspaceCache } from 'src/engine/workspace-cache/decorators/workspace-cache.decorator';
|
||||
|
||||
@Injectable()
|
||||
@WorkspaceCache('logicFunctionLayerMaps')
|
||||
export class WorkspaceLogicFunctionLayerMapCacheService extends WorkspaceCacheProvider<LogicFunctionLayerCacheMaps> {
|
||||
constructor(
|
||||
@InjectRepository(LogicFunctionLayerEntity)
|
||||
private readonly logicFunctionLayerRepository: Repository<LogicFunctionLayerEntity>,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async computeForCache(
|
||||
workspaceId: string,
|
||||
): Promise<LogicFunctionLayerCacheMaps> {
|
||||
const logicFunctionLayerEntities =
|
||||
await this.logicFunctionLayerRepository.find({
|
||||
where: {
|
||||
workspaceId,
|
||||
},
|
||||
});
|
||||
|
||||
const logicFunctionLayerMaps: LogicFunctionLayerCacheMaps = {
|
||||
byId: {},
|
||||
};
|
||||
|
||||
for (const entity of logicFunctionLayerEntities) {
|
||||
const flatLogicFunctionLayer =
|
||||
fromLogicFunctionLayerEntityToFlatLogicFunctionLayer(entity);
|
||||
|
||||
logicFunctionLayerMaps.byId[flatLogicFunctionLayer.id] =
|
||||
flatLogicFunctionLayer;
|
||||
}
|
||||
|
||||
return logicFunctionLayerMaps;
|
||||
}
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
import { type FlatEntityFrom } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-from.type';
|
||||
import { type LogicFunctionLayerEntity } from 'src/engine/metadata-modules/logic-function-layer/logic-function-layer.entity';
|
||||
|
||||
export type FlatLogicFunctionLayer = FlatEntityFrom<LogicFunctionLayerEntity>;
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
import { type FlatLogicFunctionLayer } from 'src/engine/metadata-modules/logic-function-layer/types/flat-logic-function-layer.type';
|
||||
|
||||
export type LogicFunctionLayerCacheMaps = {
|
||||
byId: Partial<Record<string, FlatLogicFunctionLayer>>;
|
||||
};
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
import { type LogicFunctionLayerEntity } from 'src/engine/metadata-modules/logic-function-layer/logic-function-layer.entity';
|
||||
import { type FlatLogicFunctionLayer } from 'src/engine/metadata-modules/logic-function-layer/types/flat-logic-function-layer.type';
|
||||
|
||||
export const fromLogicFunctionLayerEntityToFlatLogicFunctionLayer = (
|
||||
entity: LogicFunctionLayerEntity,
|
||||
): FlatLogicFunctionLayer => ({
|
||||
id: entity.id,
|
||||
packageJson: entity.packageJson,
|
||||
yarnLock: entity.yarnLock,
|
||||
checksum: entity.checksum,
|
||||
workspaceId: entity.workspaceId,
|
||||
createdAt: entity.createdAt.toISOString(),
|
||||
updatedAt: entity.updatedAt.toISOString(),
|
||||
logicFunctionIds: entity.logicFunctions?.map((lf) => lf.id) ?? [],
|
||||
});
|
||||
+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';
|
||||
+1
-1
@@ -3,7 +3,7 @@ import { ID, InputType } from '@nestjs/graphql';
|
||||
import { IDField } from '@ptc-org/nestjs-query-graphql';
|
||||
|
||||
@InputType()
|
||||
export class PublishServerlessFunctionInput {
|
||||
export class BuildDraftLogicFunctionInput {
|
||||
@IDField(() => ID, { description: 'The id of the function.' })
|
||||
id!: string;
|
||||
}
|
||||
+2
-2
@@ -14,7 +14,7 @@ import graphqlTypeJson from 'graphql-type-json';
|
||||
import { Sources } from 'twenty-shared/types';
|
||||
|
||||
@InputType()
|
||||
export class CreateServerlessFunctionInput {
|
||||
export class CreateLogicFunctionInput {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@Field()
|
||||
@@ -39,7 +39,7 @@ export class CreateServerlessFunctionInput {
|
||||
universalIdentifier?: string;
|
||||
|
||||
@HideField()
|
||||
serverlessFunctionLayerId?: string;
|
||||
logicFunctionLayerId?: string;
|
||||
|
||||
@Field(() => graphqlTypeJson, { nullable: true })
|
||||
@IsObject()
|
||||
+3
-3
@@ -6,9 +6,9 @@ import graphqlTypeJson from 'graphql-type-json';
|
||||
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
|
||||
|
||||
@InputType()
|
||||
export class ExecuteServerlessFunctionInput {
|
||||
export class ExecuteLogicFunctionInput {
|
||||
@Field(() => UUIDScalarType, {
|
||||
description: 'Id of the serverless function to execute',
|
||||
description: 'Id of the logic function to execute',
|
||||
})
|
||||
@IsNotEmpty()
|
||||
@IsUUID()
|
||||
@@ -22,7 +22,7 @@ export class ExecuteServerlessFunctionInput {
|
||||
|
||||
@Field(() => String, {
|
||||
nullable: false,
|
||||
description: 'Version of the serverless function to execute',
|
||||
description: 'Version of the logic function to execute',
|
||||
defaultValue: 'latest',
|
||||
})
|
||||
version: string;
|
||||
+1
-1
@@ -3,7 +3,7 @@ import { Field, ID, InputType } from '@nestjs/graphql';
|
||||
import { IDField } from '@ptc-org/nestjs-query-graphql';
|
||||
|
||||
@InputType()
|
||||
export class GetServerlessFunctionSourceCodeInput {
|
||||
export class GetLogicFunctionSourceCodeInput {
|
||||
@IDField(() => ID, { description: 'The id of the function.' })
|
||||
id!: string;
|
||||
|
||||
+8
-8
@@ -3,19 +3,19 @@ import { Field, ObjectType, registerEnumType } from '@nestjs/graphql';
|
||||
import { IsObject, IsOptional } from 'class-validator';
|
||||
import graphqlTypeJson from 'graphql-type-json';
|
||||
|
||||
export enum ServerlessFunctionExecutionStatus {
|
||||
export enum LogicFunctionExecutionStatus {
|
||||
IDLE = 'IDLE',
|
||||
SUCCESS = 'SUCCESS',
|
||||
ERROR = 'ERROR',
|
||||
}
|
||||
|
||||
registerEnumType(ServerlessFunctionExecutionStatus, {
|
||||
name: 'ServerlessFunctionExecutionStatus',
|
||||
description: 'Status of the serverless function execution',
|
||||
registerEnumType(LogicFunctionExecutionStatus, {
|
||||
name: 'LogicFunctionExecutionStatus',
|
||||
description: 'Status of the logic function execution',
|
||||
});
|
||||
|
||||
@ObjectType('ServerlessFunctionExecutionResult')
|
||||
export class ServerlessFunctionExecutionResultDTO {
|
||||
@ObjectType('LogicFunctionExecutionResult')
|
||||
export class LogicFunctionExecutionResultDTO {
|
||||
@IsObject()
|
||||
@Field(() => graphqlTypeJson, {
|
||||
description: 'Execution result in JSON format',
|
||||
@@ -29,10 +29,10 @@ export class ServerlessFunctionExecutionResultDTO {
|
||||
@Field({ description: 'Execution duration in milliseconds' })
|
||||
duration: number;
|
||||
|
||||
@Field(() => ServerlessFunctionExecutionStatus, {
|
||||
@Field(() => LogicFunctionExecutionStatus, {
|
||||
description: 'Execution status',
|
||||
})
|
||||
status: ServerlessFunctionExecutionStatus;
|
||||
status: LogicFunctionExecutionStatus;
|
||||
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
+1
-1
@@ -3,7 +3,7 @@ import { ID, InputType } from '@nestjs/graphql';
|
||||
import { IDField } from '@ptc-org/nestjs-query-graphql';
|
||||
|
||||
@InputType()
|
||||
export class ServerlessFunctionIdInput {
|
||||
export class LogicFunctionIdInput {
|
||||
@IDField(() => ID, { description: 'The id of the function.' })
|
||||
id!: string;
|
||||
}
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
import { Field, HideField, ObjectType } from '@nestjs/graphql';
|
||||
|
||||
@ObjectType('ServerlessFunctionLogs')
|
||||
export class ServerlessFunctionLogsDTO {
|
||||
@ObjectType('LogicFunctionLogs')
|
||||
export class LogicFunctionLogsDTO {
|
||||
@Field({ description: 'Execution Logs' })
|
||||
logs: string;
|
||||
|
||||
+2
-2
@@ -2,8 +2,8 @@ import { Field, InputType } from '@nestjs/graphql';
|
||||
|
||||
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
|
||||
|
||||
@InputType('ServerlessFunctionLogsInput')
|
||||
export class ServerlessFunctionLogsInput {
|
||||
@InputType('LogicFunctionLogsInput')
|
||||
export class LogicFunctionLogsInput {
|
||||
@Field(() => UUIDScalarType, { nullable: true })
|
||||
applicationId?: string;
|
||||
|
||||
+3
-3
@@ -23,9 +23,9 @@ import {
|
||||
CronTriggerSettings,
|
||||
DatabaseEventTriggerSettings,
|
||||
HttpRouteTriggerSettings,
|
||||
} from 'src/engine/metadata-modules/serverless-function/serverless-function.entity';
|
||||
} from 'src/engine/metadata-modules/logic-function/logic-function.entity';
|
||||
|
||||
@ObjectType('ServerlessFunction')
|
||||
@ObjectType('LogicFunction')
|
||||
@Authorize({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authorize: (context: any) => ({
|
||||
@@ -36,7 +36,7 @@ import {
|
||||
defaultResultSize: 10,
|
||||
maxResultsSize: 1000,
|
||||
})
|
||||
export class ServerlessFunctionDTO {
|
||||
export class LogicFunctionDTO {
|
||||
@IsUUID()
|
||||
@IsNotEmpty()
|
||||
@IDField(() => UUIDScalarType)
|
||||
+1
-1
@@ -3,7 +3,7 @@ import { ID, InputType } from '@nestjs/graphql';
|
||||
import { IDField } from '@ptc-org/nestjs-query-graphql';
|
||||
|
||||
@InputType()
|
||||
export class BuildDraftServerlessFunctionInput {
|
||||
export class PublishLogicFunctionInput {
|
||||
@IDField(() => ID, { description: 'The id of the function.' })
|
||||
id!: string;
|
||||
}
|
||||
+7
-7
@@ -20,7 +20,7 @@ import type { Sources } from 'twenty-shared/types';
|
||||
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
|
||||
|
||||
@InputType()
|
||||
class UpdateServerlessFunctionInputUpdates {
|
||||
class UpdateLogicFunctionInputUpdates {
|
||||
@IsString()
|
||||
@Field()
|
||||
@IsOptional()
|
||||
@@ -64,18 +64,18 @@ class UpdateServerlessFunctionInputUpdates {
|
||||
}
|
||||
|
||||
@InputType()
|
||||
export class UpdateServerlessFunctionInput {
|
||||
export class UpdateLogicFunctionInput {
|
||||
@Field(() => UUIDScalarType, {
|
||||
description: 'Id of the serverless function to update',
|
||||
description: 'Id of the logic function to update',
|
||||
})
|
||||
@IsNotEmpty()
|
||||
@IsUUID()
|
||||
id: string;
|
||||
|
||||
@Type(() => UpdateServerlessFunctionInputUpdates)
|
||||
@Type(() => UpdateLogicFunctionInputUpdates)
|
||||
@ValidateNested()
|
||||
@Field(() => UpdateServerlessFunctionInputUpdates, {
|
||||
description: 'The serverless function updates',
|
||||
@Field(() => UpdateLogicFunctionInputUpdates, {
|
||||
description: 'The logic function updates',
|
||||
})
|
||||
update: UpdateServerlessFunctionInputUpdates;
|
||||
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',
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
+16
-16
@@ -14,7 +14,7 @@ import {
|
||||
} from 'typeorm';
|
||||
|
||||
import { type JsonbProperty } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/jsonb-property.type';
|
||||
import { ServerlessFunctionLayerEntity } from 'src/engine/metadata-modules/serverless-function-layer/serverless-function-layer.entity';
|
||||
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 = {
|
||||
@@ -33,9 +33,9 @@ export type HttpRouteTriggerSettings = {
|
||||
forwardedRequestHeaders?: string[];
|
||||
};
|
||||
|
||||
const DEFAULT_SERVERLESS_TIMEOUT_SECONDS = 300; // 5 minutes
|
||||
const DEFAULT_LOGIC_FUNCTION_TIMEOUT_SECONDS = 300; // 5 minutes
|
||||
|
||||
export enum ServerlessFunctionRuntime {
|
||||
export enum LogicFunctionRuntime {
|
||||
NODE18 = 'nodejs18.x',
|
||||
NODE22 = 'nodejs22.x',
|
||||
}
|
||||
@@ -44,12 +44,12 @@ export const DEFAULT_SOURCE_HANDLER_PATH = 'src/index.ts';
|
||||
export const DEFAULT_BUILT_HANDLER_PATH = 'index.mjs';
|
||||
export const DEFAULT_HANDLER_NAME = 'main';
|
||||
|
||||
@Entity('serverlessFunction')
|
||||
@Index('IDX_SERVERLESS_FUNCTION_ID_DELETED_AT', ['id', 'deletedAt'])
|
||||
@Index('IDX_SERVERLESS_FUNCTION_LAYER_ID', ['serverlessFunctionLayerId'])
|
||||
export class ServerlessFunctionEntity
|
||||
@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<ServerlessFunctionEntity>
|
||||
implements Required<LogicFunctionEntity>
|
||||
{
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
@@ -75,10 +75,10 @@ export class ServerlessFunctionEntity
|
||||
@Column({ nullable: false, type: 'jsonb', default: [] })
|
||||
publishedVersions: JsonbProperty<string[]>;
|
||||
|
||||
@Column({ nullable: false, default: ServerlessFunctionRuntime.NODE22 })
|
||||
runtime: ServerlessFunctionRuntime;
|
||||
@Column({ nullable: false, default: LogicFunctionRuntime.NODE22 })
|
||||
runtime: LogicFunctionRuntime;
|
||||
|
||||
@Column({ nullable: false, default: DEFAULT_SERVERLESS_TIMEOUT_SECONDS })
|
||||
@Column({ nullable: false, default: DEFAULT_LOGIC_FUNCTION_TIMEOUT_SECONDS })
|
||||
@Check(`"timeoutSeconds" >= 1 AND "timeoutSeconds" <= 900`)
|
||||
timeoutSeconds: number;
|
||||
|
||||
@@ -92,15 +92,15 @@ export class ServerlessFunctionEntity
|
||||
isTool: boolean;
|
||||
|
||||
@Column({ nullable: false, type: 'uuid' })
|
||||
serverlessFunctionLayerId: string;
|
||||
logicFunctionLayerId: string;
|
||||
|
||||
@ManyToOne(
|
||||
() => ServerlessFunctionLayerEntity,
|
||||
(serverlessFunctionLayer) => serverlessFunctionLayer.serverlessFunctions,
|
||||
() => LogicFunctionLayerEntity,
|
||||
(logicFunctionLayer) => logicFunctionLayer.logicFunctions,
|
||||
{ nullable: false },
|
||||
)
|
||||
@JoinColumn({ name: 'serverlessFunctionLayerId' })
|
||||
serverlessFunctionLayer: Relation<ServerlessFunctionLayerEntity>;
|
||||
@JoinColumn({ name: 'logicFunctionLayerId' })
|
||||
logicFunctionLayer: Relation<LogicFunctionLayerEntity>;
|
||||
|
||||
@Column({ nullable: true, type: 'jsonb' })
|
||||
cronTriggerSettings: JsonbProperty<CronTriggerSettings> | 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),
|
||||
});
|
||||
}
|
||||
}
|
||||
+16
-16
@@ -14,13 +14,13 @@ import { SecretEncryptionModule } from 'src/engine/core-modules/secret-encryptio
|
||||
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 { ServerlessFunctionLayerModule } from 'src/engine/metadata-modules/serverless-function-layer/serverless-function-layer.module';
|
||||
import { ServerlessFunctionTriggerJob } from 'src/engine/metadata-modules/serverless-function/jobs/serverless-function-trigger.job';
|
||||
import { ServerlessFunctionEntity } from 'src/engine/metadata-modules/serverless-function/serverless-function.entity';
|
||||
import { ServerlessFunctionResolver } from 'src/engine/metadata-modules/serverless-function/serverless-function.resolver';
|
||||
import { ServerlessFunctionService } from 'src/engine/metadata-modules/serverless-function/serverless-function.service';
|
||||
import { ServerlessFunctionV2Service } from 'src/engine/metadata-modules/serverless-function/services/serverless-function-v2.service';
|
||||
import { WorkspaceFlatServerlessFunctionMapCacheService } from 'src/engine/metadata-modules/serverless-function/services/workspace-flat-serverless-function-map-cache.service';
|
||||
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';
|
||||
@@ -29,7 +29,7 @@ import { FunctionBuildModule } from 'src/engine/metadata-modules/function-build/
|
||||
@Module({
|
||||
imports: [
|
||||
FileUploadModule,
|
||||
NestjsQueryTypeOrmModule.forFeature([ServerlessFunctionEntity]),
|
||||
NestjsQueryTypeOrmModule.forFeature([LogicFunctionEntity]),
|
||||
TypeOrmModule.forFeature([FeatureFlagEntity]),
|
||||
FileModule,
|
||||
ThrottlerModule,
|
||||
@@ -40,19 +40,19 @@ import { FunctionBuildModule } from 'src/engine/metadata-modules/function-build/
|
||||
WorkspaceManyOrAllFlatEntityMapsCacheModule,
|
||||
WorkspaceMigrationModule,
|
||||
FunctionBuildModule,
|
||||
ServerlessFunctionLayerModule,
|
||||
LogicFunctionLayerModule,
|
||||
SubscriptionsModule,
|
||||
WorkspaceCacheModule,
|
||||
TokenModule,
|
||||
SecretEncryptionModule,
|
||||
],
|
||||
providers: [
|
||||
ServerlessFunctionService,
|
||||
ServerlessFunctionV2Service,
|
||||
ServerlessFunctionTriggerJob,
|
||||
ServerlessFunctionResolver,
|
||||
WorkspaceFlatServerlessFunctionMapCacheService,
|
||||
LogicFunctionService,
|
||||
LogicFunctionV2Service,
|
||||
LogicFunctionTriggerJob,
|
||||
LogicFunctionResolver,
|
||||
WorkspaceFlatLogicFunctionMapCacheService,
|
||||
],
|
||||
exports: [ServerlessFunctionService, ServerlessFunctionV2Service],
|
||||
exports: [LogicFunctionService, LogicFunctionV2Service],
|
||||
})
|
||||
export class ServerlessFunctionModule {}
|
||||
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,
|
||||
});
|
||||
}
|
||||
}
|
||||
+236
-252
@@ -11,34 +11,34 @@ 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 ServerlessExecuteResult } from 'src/engine/core-modules/serverless/drivers/interfaces/serverless-driver.interface';
|
||||
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 { SERVERLESS_FUNCTION_EXECUTED_EVENT } from 'src/engine/core-modules/audit/utils/events/workspace-event/serverless-function/serverless-function-executed';
|
||||
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/serverless/drivers/utils/build-env-var';
|
||||
import { ServerlessService } from 'src/engine/core-modules/serverless/serverless.service';
|
||||
import { getServerlessFolderOrThrow } from 'src/engine/core-modules/serverless/utils/get-serverless-folder-or-throw.utils';
|
||||
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 { ServerlessFunctionLayerService } from 'src/engine/metadata-modules/serverless-function-layer/serverless-function-layer.service';
|
||||
import { CreateServerlessFunctionInput } from 'src/engine/metadata-modules/serverless-function/dtos/create-serverless-function.input';
|
||||
import { type UpdateServerlessFunctionInput } from 'src/engine/metadata-modules/serverless-function/dtos/update-serverless-function.input';
|
||||
import { ServerlessFunctionEntity } from 'src/engine/metadata-modules/serverless-function/serverless-function.entity';
|
||||
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 {
|
||||
ServerlessFunctionException,
|
||||
ServerlessFunctionExceptionCode,
|
||||
} from 'src/engine/metadata-modules/serverless-function/serverless-function.exception';
|
||||
import { type FlatServerlessFunction } from 'src/engine/metadata-modules/serverless-function/types/flat-serverless-function.type';
|
||||
import { findFlatServerlessFunctionOrThrow } from 'src/engine/metadata-modules/serverless-function/utils/find-flat-serverless-function-or-throw.util';
|
||||
import { fromCreateServerlessFunctionInputToFlatServerlessFunction } from 'src/engine/metadata-modules/serverless-function/utils/from-create-serverless-function-input-to-flat-serverless-function.util';
|
||||
import { fromUpdateServerlessFunctionInputToFlatServerlessFunctionToUpdateOrThrow } from 'src/engine/metadata-modules/serverless-function/utils/from-update-serverless-function-input-to-flat-serverless-function-to-update-or-throw.util';
|
||||
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';
|
||||
@@ -54,14 +54,14 @@ import { FunctionBuildService } from 'src/engine/metadata-modules/function-build
|
||||
const MIN_TOKEN_EXPIRATION_IN_SECONDS = 5;
|
||||
|
||||
@Injectable()
|
||||
export class ServerlessFunctionService {
|
||||
export class LogicFunctionService {
|
||||
constructor(
|
||||
private readonly fileStorageService: FileStorageService,
|
||||
private readonly serverlessService: ServerlessService,
|
||||
private readonly logicFunctionExecutorService: LogicFunctionExecutorService,
|
||||
private readonly functionBuildService: FunctionBuildService,
|
||||
private readonly serverlessFunctionLayerService: ServerlessFunctionLayerService,
|
||||
@InjectRepository(ServerlessFunctionEntity)
|
||||
private readonly serverlessFunctionRepository: Repository<ServerlessFunctionEntity>,
|
||||
private readonly logicFunctionLayerService: LogicFunctionLayerService,
|
||||
@InjectRepository(LogicFunctionEntity)
|
||||
private readonly logicFunctionRepository: Repository<LogicFunctionEntity>,
|
||||
private readonly throttlerService: ThrottlerService,
|
||||
private readonly twentyConfigService: TwentyConfigService,
|
||||
private readonly auditService: AuditService,
|
||||
@@ -74,51 +74,51 @@ export class ServerlessFunctionService {
|
||||
private readonly secretEncryptionService: SecretEncryptionService,
|
||||
) {}
|
||||
|
||||
async hasServerlessFunctionPublishedVersion(
|
||||
serverlessFunctionId: string,
|
||||
async hasLogicFunctionPublishedVersion(
|
||||
logicFunctionId: string,
|
||||
workspaceId: string,
|
||||
) {
|
||||
const { flatServerlessFunctionMaps } =
|
||||
const { flatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatServerlessFunctionMaps'],
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const flatServerlessFunction = findFlatEntityByIdInFlatEntityMaps({
|
||||
flatEntityId: serverlessFunctionId,
|
||||
flatEntityMaps: flatServerlessFunctionMaps,
|
||||
const flatLogicFunction = findFlatEntityByIdInFlatEntityMaps({
|
||||
flatEntityId: logicFunctionId,
|
||||
flatEntityMaps: flatLogicFunctionMaps,
|
||||
});
|
||||
|
||||
return (
|
||||
isDefined(flatServerlessFunction) &&
|
||||
!isDefined(flatServerlessFunction.deletedAt) &&
|
||||
isDefined(flatServerlessFunction.latestVersion)
|
||||
isDefined(flatLogicFunction) &&
|
||||
!isDefined(flatLogicFunction.deletedAt) &&
|
||||
isDefined(flatLogicFunction.latestVersion)
|
||||
);
|
||||
}
|
||||
|
||||
async getServerlessFunctionSourceCode(
|
||||
async getLogicFunctionSourceCode(
|
||||
workspaceId: string,
|
||||
id: string,
|
||||
version: string,
|
||||
) {
|
||||
const { flatServerlessFunctionMaps } =
|
||||
const { flatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatServerlessFunctionMaps'],
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const flatServerlessFunction = findFlatServerlessFunctionOrThrow({
|
||||
const flatLogicFunction = findFlatLogicFunctionOrThrow({
|
||||
id,
|
||||
flatServerlessFunctionMaps,
|
||||
flatLogicFunctionMaps,
|
||||
});
|
||||
|
||||
try {
|
||||
const folderPath = getServerlessFolderOrThrow({
|
||||
flatServerlessFunction,
|
||||
const folderPath = getLogicFunctionFolderOrThrow({
|
||||
flatLogicFunction,
|
||||
version,
|
||||
});
|
||||
|
||||
@@ -131,7 +131,7 @@ export class ServerlessFunctionService {
|
||||
}
|
||||
}
|
||||
|
||||
async executeOneServerlessFunction({
|
||||
async executeOneLogicFunction({
|
||||
id,
|
||||
workspaceId,
|
||||
payload,
|
||||
@@ -141,46 +141,42 @@ export class ServerlessFunctionService {
|
||||
workspaceId: string;
|
||||
payload: object;
|
||||
version?: string;
|
||||
}): Promise<ServerlessExecuteResult> {
|
||||
}): Promise<LogicFunctionExecuteResult> {
|
||||
await this.throttleExecution(workspaceId);
|
||||
|
||||
const {
|
||||
flatServerlessFunctionMaps,
|
||||
flatLogicFunctionMaps,
|
||||
flatApplicationMaps,
|
||||
applicationVariableMaps,
|
||||
serverlessFunctionLayerMaps,
|
||||
logicFunctionLayerMaps,
|
||||
} = await this.workspaceCacheService.getOrRecompute(workspaceId, [
|
||||
'flatServerlessFunctionMaps',
|
||||
'flatLogicFunctionMaps',
|
||||
'flatApplicationMaps',
|
||||
'applicationVariableMaps',
|
||||
'serverlessFunctionLayerMaps',
|
||||
'logicFunctionLayerMaps',
|
||||
]);
|
||||
|
||||
const flatServerlessFunction = findFlatServerlessFunctionOrThrow({
|
||||
const flatLogicFunction = findFlatLogicFunctionOrThrow({
|
||||
id,
|
||||
flatServerlessFunctionMaps,
|
||||
flatLogicFunctionMaps,
|
||||
});
|
||||
|
||||
const flatServerlessFunctionLayer =
|
||||
serverlessFunctionLayerMaps.byId[
|
||||
flatServerlessFunction.serverlessFunctionLayerId
|
||||
];
|
||||
const flatLogicFunctionLayer =
|
||||
logicFunctionLayerMaps.byId[flatLogicFunction.logicFunctionLayerId];
|
||||
|
||||
if (!isDefined(flatServerlessFunctionLayer)) {
|
||||
throw new ServerlessFunctionException(
|
||||
`Serverless function layer with id ${flatServerlessFunction.serverlessFunctionLayerId} not found`,
|
||||
ServerlessFunctionExceptionCode.SERVERLESS_FUNCTION_NOT_FOUND,
|
||||
if (!isDefined(flatLogicFunctionLayer)) {
|
||||
throw new LogicFunctionException(
|
||||
`Logic function layer with id ${flatLogicFunction.logicFunctionLayerId} not found`,
|
||||
LogicFunctionExceptionCode.LOGIC_FUNCTION_NOT_FOUND,
|
||||
);
|
||||
}
|
||||
|
||||
const applicationAccessToken = isDefined(
|
||||
flatServerlessFunction.applicationId,
|
||||
)
|
||||
const applicationAccessToken = isDefined(flatLogicFunction.applicationId)
|
||||
? await this.applicationTokenService.generateApplicationToken({
|
||||
workspaceId,
|
||||
applicationId: flatServerlessFunction.applicationId,
|
||||
applicationId: flatLogicFunction.applicationId,
|
||||
expiresInSeconds: Math.max(
|
||||
flatServerlessFunction.timeoutSeconds,
|
||||
flatLogicFunction.timeoutSeconds,
|
||||
MIN_TOKEN_EXPIRATION_IN_SECONDS,
|
||||
),
|
||||
})
|
||||
@@ -188,11 +184,9 @@ export class ServerlessFunctionService {
|
||||
|
||||
const baseUrl = cleanServerUrl(this.twentyConfigService.get('SERVER_URL'));
|
||||
|
||||
const flatApplicationVariables = isDefined(
|
||||
flatServerlessFunction.applicationId,
|
||||
)
|
||||
const flatApplicationVariables = isDefined(flatLogicFunction.applicationId)
|
||||
? (applicationVariableMaps.byApplicationId[
|
||||
flatServerlessFunction.applicationId
|
||||
flatLogicFunction.applicationId
|
||||
] ?? [])
|
||||
: [];
|
||||
|
||||
@@ -213,50 +207,50 @@ export class ServerlessFunctionService {
|
||||
// We keep that check to build functions
|
||||
if (
|
||||
!(await this.functionBuildService.isBuilt({
|
||||
flatServerlessFunction,
|
||||
flatLogicFunction,
|
||||
version,
|
||||
}))
|
||||
) {
|
||||
await this.functionBuildService.buildAndUpload({
|
||||
flatServerlessFunction,
|
||||
flatLogicFunction,
|
||||
version,
|
||||
});
|
||||
}
|
||||
|
||||
const resultServerlessFunction = await this.callWithTimeout({
|
||||
const resultLogicFunction = await this.callWithTimeout({
|
||||
callback: () =>
|
||||
this.serverlessService.execute({
|
||||
flatServerlessFunction,
|
||||
flatServerlessFunctionLayer,
|
||||
this.logicFunctionExecutorService.execute({
|
||||
flatLogicFunction,
|
||||
flatLogicFunctionLayer,
|
||||
payload,
|
||||
version,
|
||||
env: envVariables,
|
||||
}),
|
||||
timeoutMs: flatServerlessFunction.timeoutSeconds * 1000,
|
||||
timeoutMs: flatLogicFunction.timeoutSeconds * 1000,
|
||||
});
|
||||
|
||||
if (this.twentyConfigService.get('SERVERLESS_LOGS_ENABLED')) {
|
||||
if (this.twentyConfigService.get('LOGIC_FUNCTION_LOGS_ENABLED')) {
|
||||
/* eslint-disable no-console */
|
||||
console.log(resultServerlessFunction.logs);
|
||||
console.log(resultLogicFunction.logs);
|
||||
}
|
||||
|
||||
const applicationUniversalIdentifier = isDefined(
|
||||
flatServerlessFunction.applicationId,
|
||||
flatLogicFunction.applicationId,
|
||||
)
|
||||
? flatApplicationMaps.byId[flatServerlessFunction.applicationId]
|
||||
? flatApplicationMaps.byId[flatLogicFunction.applicationId]
|
||||
?.universalIdentifier
|
||||
: undefined;
|
||||
|
||||
await this.subscriptionService.publish({
|
||||
channel: SubscriptionChannel.SERVERLESS_FUNCTION_LOGS_CHANNEL,
|
||||
channel: SubscriptionChannel.LOGIC_FUNCTION_LOGS_CHANNEL,
|
||||
workspaceId,
|
||||
payload: {
|
||||
serverlessFunctionLogs: {
|
||||
logs: resultServerlessFunction.logs,
|
||||
id: flatServerlessFunction.id,
|
||||
name: flatServerlessFunction.name,
|
||||
universalIdentifier: flatServerlessFunction.universalIdentifier,
|
||||
applicationId: flatServerlessFunction.applicationId,
|
||||
logicFunctionLogs: {
|
||||
logs: resultLogicFunction.logs,
|
||||
id: flatLogicFunction.id,
|
||||
name: flatLogicFunction.name,
|
||||
universalIdentifier: flatLogicFunction.universalIdentifier,
|
||||
applicationId: flatLogicFunction.applicationId,
|
||||
applicationUniversalIdentifier,
|
||||
},
|
||||
},
|
||||
@@ -266,67 +260,67 @@ export class ServerlessFunctionService {
|
||||
.createContext({
|
||||
workspaceId,
|
||||
})
|
||||
.insertWorkspaceEvent(SERVERLESS_FUNCTION_EXECUTED_EVENT, {
|
||||
duration: resultServerlessFunction.duration,
|
||||
status: resultServerlessFunction.status,
|
||||
...(resultServerlessFunction.error && {
|
||||
errorType: resultServerlessFunction.error.errorType,
|
||||
.insertWorkspaceEvent(LOGIC_FUNCTION_EXECUTED_EVENT, {
|
||||
duration: resultLogicFunction.duration,
|
||||
status: resultLogicFunction.status,
|
||||
...(resultLogicFunction.error && {
|
||||
errorType: resultLogicFunction.error.errorType,
|
||||
}),
|
||||
functionId: flatServerlessFunction.id,
|
||||
functionName: flatServerlessFunction.name,
|
||||
functionId: flatLogicFunction.id,
|
||||
functionName: flatLogicFunction.name,
|
||||
});
|
||||
|
||||
return resultServerlessFunction;
|
||||
return resultLogicFunction;
|
||||
}
|
||||
|
||||
async publishOneServerlessFunctionOrFail(
|
||||
async publishOneLogicFunctionOrFail(
|
||||
id: string,
|
||||
workspaceId: string,
|
||||
): Promise<FlatServerlessFunction> {
|
||||
const { flatServerlessFunctionMaps } =
|
||||
): Promise<FlatLogicFunction> {
|
||||
const { flatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatServerlessFunctionMaps'],
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const existingFlatServerlessFunction = findFlatServerlessFunctionOrThrow({
|
||||
const existingFlatLogicFunction = findFlatLogicFunctionOrThrow({
|
||||
id,
|
||||
flatServerlessFunctionMaps,
|
||||
flatLogicFunctionMaps,
|
||||
});
|
||||
|
||||
if (isDefined(existingFlatServerlessFunction.latestVersion)) {
|
||||
const latestCode = await this.getServerlessFunctionSourceCode(
|
||||
if (isDefined(existingFlatLogicFunction.latestVersion)) {
|
||||
const latestCode = await this.getLogicFunctionSourceCode(
|
||||
workspaceId,
|
||||
id,
|
||||
'latest',
|
||||
);
|
||||
const draftCode = await this.getServerlessFunctionSourceCode(
|
||||
const draftCode = await this.getLogicFunctionSourceCode(
|
||||
workspaceId,
|
||||
id,
|
||||
'draft',
|
||||
);
|
||||
|
||||
if (deepEqual(latestCode, draftCode)) {
|
||||
return existingFlatServerlessFunction;
|
||||
return existingFlatLogicFunction;
|
||||
}
|
||||
}
|
||||
|
||||
const newVersion = existingFlatServerlessFunction.latestVersion
|
||||
? `${parseInt(existingFlatServerlessFunction.latestVersion, 10) + 1}`
|
||||
const newVersion = existingFlatLogicFunction.latestVersion
|
||||
? `${parseInt(existingFlatLogicFunction.latestVersion, 10) + 1}`
|
||||
: '1';
|
||||
|
||||
const draftSourceFolderPath = getServerlessFolderOrThrow({
|
||||
flatServerlessFunction: existingFlatServerlessFunction,
|
||||
const draftSourceFolderPath = getLogicFunctionFolderOrThrow({
|
||||
flatLogicFunction: existingFlatLogicFunction,
|
||||
version: 'draft',
|
||||
fileFolder: FileFolder.ServerlessFunction,
|
||||
fileFolder: FileFolder.LogicFunction,
|
||||
});
|
||||
|
||||
const newSourceFolderPath = getServerlessFolderOrThrow({
|
||||
flatServerlessFunction: existingFlatServerlessFunction,
|
||||
const newSourceFolderPath = getLogicFunctionFolderOrThrow({
|
||||
flatLogicFunction: existingFlatLogicFunction,
|
||||
version: newVersion,
|
||||
fileFolder: FileFolder.ServerlessFunction,
|
||||
fileFolder: FileFolder.LogicFunction,
|
||||
});
|
||||
|
||||
await this.fileStorageService.copy({
|
||||
@@ -334,14 +328,14 @@ export class ServerlessFunctionService {
|
||||
to: { folderPath: newSourceFolderPath },
|
||||
});
|
||||
|
||||
const draftBuiltFolderPath = getServerlessFolderOrThrow({
|
||||
flatServerlessFunction: existingFlatServerlessFunction,
|
||||
const draftBuiltFolderPath = getLogicFunctionFolderOrThrow({
|
||||
flatLogicFunction: existingFlatLogicFunction,
|
||||
version: 'draft',
|
||||
fileFolder: FileFolder.BuiltFunction,
|
||||
});
|
||||
|
||||
const newBuiltFolderPath = getServerlessFolderOrThrow({
|
||||
flatServerlessFunction: existingFlatServerlessFunction,
|
||||
const newBuiltFolderPath = getLogicFunctionFolderOrThrow({
|
||||
flatLogicFunction: existingFlatLogicFunction,
|
||||
version: newVersion,
|
||||
fileFolder: FileFolder.BuiltFunction,
|
||||
});
|
||||
@@ -352,12 +346,12 @@ export class ServerlessFunctionService {
|
||||
});
|
||||
|
||||
const newPublishedVersions = [
|
||||
...existingFlatServerlessFunction.publishedVersions,
|
||||
...existingFlatLogicFunction.publishedVersions,
|
||||
newVersion,
|
||||
];
|
||||
|
||||
const updatedFlatServerlessFunction: FlatServerlessFunction = {
|
||||
...existingFlatServerlessFunction,
|
||||
const updatedFlatLogicFunction: FlatLogicFunction = {
|
||||
...existingFlatLogicFunction,
|
||||
latestVersion: newVersion,
|
||||
publishedVersions: newPublishedVersions,
|
||||
};
|
||||
@@ -366,10 +360,10 @@ export class ServerlessFunctionService {
|
||||
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
|
||||
{
|
||||
allFlatEntityOperationByMetadataName: {
|
||||
serverlessFunction: {
|
||||
logicFunction: {
|
||||
flatEntityToCreate: [],
|
||||
flatEntityToDelete: [],
|
||||
flatEntityToUpdate: [updatedFlatServerlessFunction],
|
||||
flatEntityToUpdate: [updatedFlatLogicFunction],
|
||||
},
|
||||
},
|
||||
workspaceId,
|
||||
@@ -380,35 +374,35 @@ export class ServerlessFunctionService {
|
||||
if (isDefined(validateAndBuildResult)) {
|
||||
throw new WorkspaceMigrationBuilderException(
|
||||
validateAndBuildResult,
|
||||
'Multiple validation errors occurred while publishing serverless function',
|
||||
'Multiple validation errors occurred while publishing logic function',
|
||||
);
|
||||
}
|
||||
|
||||
const { flatServerlessFunctionMaps: recomputedFlatServerlessFunctionMaps } =
|
||||
const { flatLogicFunctionMaps: recomputedFlatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatServerlessFunctionMaps'],
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const publishedFlatServerlessFunction =
|
||||
const publishedFlatLogicFunction =
|
||||
findFlatEntityByIdInFlatEntityMapsOrThrow({
|
||||
flatEntityId: id,
|
||||
flatEntityMaps: recomputedFlatServerlessFunctionMaps,
|
||||
flatEntityMaps: recomputedFlatLogicFunctionMaps,
|
||||
});
|
||||
|
||||
if (!isDefined(publishedFlatServerlessFunction.latestVersion)) {
|
||||
if (!isDefined(publishedFlatLogicFunction.latestVersion)) {
|
||||
throw new WorkflowVersionStepException(
|
||||
`Fail to publish serverlessFunction ${publishedFlatServerlessFunction.id}.Received latest version ${publishedFlatServerlessFunction.latestVersion}`,
|
||||
`Fail to publish logicFunction ${publishedFlatLogicFunction.id}.Received latest version ${publishedFlatLogicFunction.latestVersion}`,
|
||||
WorkflowVersionStepExceptionCode.CODE_STEP_FAILURE,
|
||||
);
|
||||
}
|
||||
|
||||
return publishedFlatServerlessFunction;
|
||||
return publishedFlatLogicFunction;
|
||||
}
|
||||
|
||||
async deleteOneServerlessFunction({
|
||||
async deleteOneLogicFunction({
|
||||
id,
|
||||
workspaceId,
|
||||
softDelete = false,
|
||||
@@ -416,41 +410,38 @@ export class ServerlessFunctionService {
|
||||
id: string;
|
||||
workspaceId: string;
|
||||
softDelete?: boolean;
|
||||
}): Promise<FlatServerlessFunction> {
|
||||
const { flatServerlessFunctionMaps } =
|
||||
}): Promise<FlatLogicFunction> {
|
||||
const { flatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatServerlessFunctionMaps'],
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const existingFlatServerlessFunction = flatServerlessFunctionMaps.byId[id];
|
||||
const existingFlatLogicFunction = flatLogicFunctionMaps.byId[id];
|
||||
|
||||
if (!isDefined(existingFlatServerlessFunction)) {
|
||||
throw new ServerlessFunctionException(
|
||||
'Serverless function to delete not found',
|
||||
ServerlessFunctionExceptionCode.SERVERLESS_FUNCTION_NOT_FOUND,
|
||||
if (!isDefined(existingFlatLogicFunction)) {
|
||||
throw new LogicFunctionException(
|
||||
'Logic function to delete not found',
|
||||
LogicFunctionExceptionCode.LOGIC_FUNCTION_NOT_FOUND,
|
||||
);
|
||||
}
|
||||
|
||||
if (softDelete) {
|
||||
const updatedFlatServerlessFunctionWithDeletedAt: FlatServerlessFunction =
|
||||
{
|
||||
...existingFlatServerlessFunction,
|
||||
deletedAt: new Date().toISOString(),
|
||||
};
|
||||
const updatedFlatLogicFunctionWithDeletedAt: FlatLogicFunction = {
|
||||
...existingFlatLogicFunction,
|
||||
deletedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
const validateAndBuildResult =
|
||||
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
|
||||
{
|
||||
allFlatEntityOperationByMetadataName: {
|
||||
serverlessFunction: {
|
||||
logicFunction: {
|
||||
flatEntityToCreate: [],
|
||||
flatEntityToDelete: [],
|
||||
flatEntityToUpdate: [
|
||||
updatedFlatServerlessFunctionWithDeletedAt,
|
||||
],
|
||||
flatEntityToUpdate: [updatedFlatLogicFunctionWithDeletedAt],
|
||||
},
|
||||
},
|
||||
workspaceId,
|
||||
@@ -461,19 +452,19 @@ export class ServerlessFunctionService {
|
||||
if (isDefined(validateAndBuildResult)) {
|
||||
throw new WorkspaceMigrationBuilderException(
|
||||
validateAndBuildResult,
|
||||
'Multiple validation errors occurred while deleting serverless function',
|
||||
'Multiple validation errors occurred while deleting logic function',
|
||||
);
|
||||
}
|
||||
|
||||
return updatedFlatServerlessFunctionWithDeletedAt;
|
||||
return updatedFlatLogicFunctionWithDeletedAt;
|
||||
} else {
|
||||
const validateAndBuildResult =
|
||||
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
|
||||
{
|
||||
allFlatEntityOperationByMetadataName: {
|
||||
serverlessFunction: {
|
||||
logicFunction: {
|
||||
flatEntityToCreate: [],
|
||||
flatEntityToDelete: [existingFlatServerlessFunction],
|
||||
flatEntityToDelete: [existingFlatLogicFunction],
|
||||
flatEntityToUpdate: [],
|
||||
},
|
||||
},
|
||||
@@ -485,37 +476,37 @@ export class ServerlessFunctionService {
|
||||
if (isDefined(validateAndBuildResult)) {
|
||||
throw new WorkspaceMigrationBuilderException(
|
||||
validateAndBuildResult,
|
||||
'Multiple validation errors occurred while destroying serverless function',
|
||||
'Multiple validation errors occurred while destroying logic function',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return existingFlatServerlessFunction;
|
||||
return existingFlatLogicFunction;
|
||||
}
|
||||
|
||||
async restoreOneServerlessFunction(
|
||||
async restoreOneLogicFunction(
|
||||
id: string,
|
||||
workspaceId: string,
|
||||
): Promise<FlatServerlessFunction> {
|
||||
const { flatServerlessFunctionMaps } =
|
||||
): Promise<FlatLogicFunction> {
|
||||
const { flatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatServerlessFunctionMaps'],
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const existingFlatServerlessFunction = flatServerlessFunctionMaps.byId[id];
|
||||
const existingFlatLogicFunction = flatLogicFunctionMaps.byId[id];
|
||||
|
||||
if (!isDefined(existingFlatServerlessFunction)) {
|
||||
throw new ServerlessFunctionException(
|
||||
'Serverless function to restore not found',
|
||||
ServerlessFunctionExceptionCode.SERVERLESS_FUNCTION_NOT_FOUND,
|
||||
if (!isDefined(existingFlatLogicFunction)) {
|
||||
throw new LogicFunctionException(
|
||||
'Logic function to restore not found',
|
||||
LogicFunctionExceptionCode.LOGIC_FUNCTION_NOT_FOUND,
|
||||
);
|
||||
}
|
||||
|
||||
const restoredFlatServerlessFunction: FlatServerlessFunction = {
|
||||
...existingFlatServerlessFunction,
|
||||
const restoredFlatLogicFunction: FlatLogicFunction = {
|
||||
...existingFlatLogicFunction,
|
||||
deletedAt: null,
|
||||
};
|
||||
|
||||
@@ -523,10 +514,10 @@ export class ServerlessFunctionService {
|
||||
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
|
||||
{
|
||||
allFlatEntityOperationByMetadataName: {
|
||||
serverlessFunction: {
|
||||
logicFunction: {
|
||||
flatEntityToCreate: [],
|
||||
flatEntityToDelete: [],
|
||||
flatEntityToUpdate: [restoredFlatServerlessFunction],
|
||||
flatEntityToUpdate: [restoredFlatLogicFunction],
|
||||
},
|
||||
},
|
||||
workspaceId,
|
||||
@@ -537,50 +528,50 @@ export class ServerlessFunctionService {
|
||||
if (isDefined(validateAndBuildResult)) {
|
||||
throw new WorkspaceMigrationBuilderException(
|
||||
validateAndBuildResult,
|
||||
'Multiple validation errors occurred while restoring serverless function',
|
||||
'Multiple validation errors occurred while restoring logic function',
|
||||
);
|
||||
}
|
||||
|
||||
const { flatServerlessFunctionMaps: recomputedFlatServerlessFunctionMaps } =
|
||||
const { flatLogicFunctionMaps: recomputedFlatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatServerlessFunctionMaps'],
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
return findFlatEntityByIdInFlatEntityMapsOrThrow({
|
||||
flatEntityId: id,
|
||||
flatEntityMaps: recomputedFlatServerlessFunctionMaps,
|
||||
flatEntityMaps: recomputedFlatLogicFunctionMaps,
|
||||
});
|
||||
}
|
||||
|
||||
async updateOneServerlessFunction(
|
||||
serverlessFunctionInput: UpdateServerlessFunctionInput,
|
||||
async updateOneLogicFunction(
|
||||
logicFunctionInput: UpdateLogicFunctionInput,
|
||||
workspaceId: string,
|
||||
): Promise<FlatServerlessFunction> {
|
||||
const { flatServerlessFunctionMaps } =
|
||||
): Promise<FlatLogicFunction> {
|
||||
const { flatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatServerlessFunctionMaps'],
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const updatedFlatServerlessFunction =
|
||||
fromUpdateServerlessFunctionInputToFlatServerlessFunctionToUpdateOrThrow({
|
||||
flatServerlessFunctionMaps,
|
||||
updateServerlessFunctionInput: serverlessFunctionInput,
|
||||
const updatedFlatLogicFunction =
|
||||
fromUpdateLogicFunctionInputToFlatLogicFunctionToUpdateOrThrow({
|
||||
flatLogicFunctionMaps,
|
||||
updateLogicFunctionInput: logicFunctionInput,
|
||||
});
|
||||
|
||||
const validateAndBuildResult =
|
||||
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
|
||||
{
|
||||
allFlatEntityOperationByMetadataName: {
|
||||
serverlessFunction: {
|
||||
logicFunction: {
|
||||
flatEntityToCreate: [],
|
||||
flatEntityToDelete: [],
|
||||
flatEntityToUpdate: [updatedFlatServerlessFunction],
|
||||
flatEntityToUpdate: [updatedFlatLogicFunction],
|
||||
},
|
||||
},
|
||||
workspaceId,
|
||||
@@ -591,34 +582,33 @@ export class ServerlessFunctionService {
|
||||
if (isDefined(validateAndBuildResult)) {
|
||||
throw new WorkspaceMigrationBuilderException(
|
||||
validateAndBuildResult,
|
||||
'Multiple validation errors occurred while updating serverless function',
|
||||
'Multiple validation errors occurred while updating logic function',
|
||||
);
|
||||
}
|
||||
|
||||
const { flatServerlessFunctionMaps: recomputedFlatServerlessFunctionMaps } =
|
||||
const { flatLogicFunctionMaps: recomputedFlatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatServerlessFunctionMaps'],
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
return findFlatEntityByIdInFlatEntityMapsOrThrow({
|
||||
flatEntityId: updatedFlatServerlessFunction.id,
|
||||
flatEntityMaps: recomputedFlatServerlessFunctionMaps,
|
||||
flatEntityId: updatedFlatLogicFunction.id,
|
||||
flatEntityMaps: recomputedFlatLogicFunctionMaps,
|
||||
});
|
||||
}
|
||||
|
||||
async getAvailablePackages(serverlessFunctionId: string) {
|
||||
const serverlessFunction =
|
||||
await this.serverlessFunctionRepository.findOneOrFail({
|
||||
where: { id: serverlessFunctionId },
|
||||
relations: ['serverlessFunctionLayer'],
|
||||
});
|
||||
async getAvailablePackages(logicFunctionId: string) {
|
||||
const logicFunction = await this.logicFunctionRepository.findOneOrFail({
|
||||
where: { id: logicFunctionId },
|
||||
relations: ['logicFunctionLayer'],
|
||||
});
|
||||
|
||||
const packageJson = serverlessFunction.serverlessFunctionLayer.packageJson;
|
||||
const packageJson = logicFunction.logicFunctionLayer.packageJson;
|
||||
|
||||
const yarnLock = serverlessFunction.serverlessFunctionLayer.yarnLock;
|
||||
const yarnLock = logicFunction.logicFunctionLayer.yarnLock;
|
||||
|
||||
const packageVersionRegex = /^"([^@]+)@.*?":\n\s+version: (.+)$/gm;
|
||||
|
||||
@@ -639,22 +629,21 @@ export class ServerlessFunctionService {
|
||||
return versions;
|
||||
}
|
||||
|
||||
async createOneServerlessFunction(
|
||||
serverlessFunctionInput: CreateServerlessFunctionInput & {
|
||||
serverlessFunctionLayerId?: string;
|
||||
async createOneLogicFunction(
|
||||
logicFunctionInput: CreateLogicFunctionInput & {
|
||||
logicFunctionLayerId?: string;
|
||||
},
|
||||
workspaceId: string,
|
||||
): Promise<FlatServerlessFunction> {
|
||||
let serverlessFunctionToCreateLayerId =
|
||||
serverlessFunctionInput.serverlessFunctionLayerId;
|
||||
): Promise<FlatLogicFunction> {
|
||||
let logicFunctionToCreateLayerId = logicFunctionInput.logicFunctionLayerId;
|
||||
|
||||
if (!isDefined(serverlessFunctionToCreateLayerId)) {
|
||||
const { id: commonServerlessFunctionLayerId } =
|
||||
await this.serverlessFunctionLayerService.createCommonLayerIfNotExist(
|
||||
if (!isDefined(logicFunctionToCreateLayerId)) {
|
||||
const { id: commonLogicFunctionLayerId } =
|
||||
await this.logicFunctionLayerService.createCommonLayerIfNotExist(
|
||||
workspaceId,
|
||||
);
|
||||
|
||||
serverlessFunctionToCreateLayerId = commonServerlessFunctionLayerId;
|
||||
logicFunctionToCreateLayerId = commonLogicFunctionLayerId;
|
||||
}
|
||||
|
||||
const { workspaceCustomFlatApplication } =
|
||||
@@ -664,24 +653,23 @@ export class ServerlessFunctionService {
|
||||
},
|
||||
);
|
||||
|
||||
const flatServerlessFunctionToCreate =
|
||||
fromCreateServerlessFunctionInputToFlatServerlessFunction({
|
||||
createServerlessFunctionInput: {
|
||||
...serverlessFunctionInput,
|
||||
serverlessFunctionLayerId: serverlessFunctionToCreateLayerId,
|
||||
const flatLogicFunctionToCreate =
|
||||
fromCreateLogicFunctionInputToFlatLogicFunction({
|
||||
createLogicFunctionInput: {
|
||||
...logicFunctionInput,
|
||||
logicFunctionLayerId: logicFunctionToCreateLayerId,
|
||||
},
|
||||
workspaceId,
|
||||
workspaceCustomApplicationId:
|
||||
serverlessFunctionInput.applicationId ??
|
||||
workspaceCustomFlatApplication.id,
|
||||
logicFunctionInput.applicationId ?? workspaceCustomFlatApplication.id,
|
||||
});
|
||||
|
||||
const validateAndBuildResult =
|
||||
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
|
||||
{
|
||||
allFlatEntityOperationByMetadataName: {
|
||||
serverlessFunction: {
|
||||
flatEntityToCreate: [flatServerlessFunctionToCreate],
|
||||
logicFunction: {
|
||||
flatEntityToCreate: [flatLogicFunctionToCreate],
|
||||
flatEntityToDelete: [],
|
||||
flatEntityToUpdate: [],
|
||||
},
|
||||
@@ -694,21 +682,21 @@ export class ServerlessFunctionService {
|
||||
if (isDefined(validateAndBuildResult)) {
|
||||
throw new WorkspaceMigrationBuilderException(
|
||||
validateAndBuildResult,
|
||||
'Multiple validation errors occurred while creating serverless function',
|
||||
'Multiple validation errors occurred while creating logic function',
|
||||
);
|
||||
}
|
||||
|
||||
const { flatServerlessFunctionMaps: recomputedFlatServerlessFunctionMaps } =
|
||||
const { flatLogicFunctionMaps: recomputedFlatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatServerlessFunctionMaps'],
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
return findFlatEntityByIdInFlatEntityMapsOrThrow({
|
||||
flatEntityId: flatServerlessFunctionToCreate.id,
|
||||
flatEntityMaps: recomputedFlatServerlessFunctionMaps,
|
||||
flatEntityId: flatLogicFunctionToCreate.id,
|
||||
flatEntityMaps: recomputedFlatLogicFunctionMaps,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -725,36 +713,36 @@ export class ServerlessFunctionService {
|
||||
return;
|
||||
}
|
||||
|
||||
const { flatServerlessFunctionMaps } =
|
||||
const { flatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatServerlessFunctionMaps'],
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const flatServerlessFunction = findFlatServerlessFunctionOrThrow({
|
||||
const flatLogicFunction = findFlatLogicFunctionOrThrow({
|
||||
id,
|
||||
flatServerlessFunctionMaps,
|
||||
flatLogicFunctionMaps,
|
||||
});
|
||||
|
||||
await this.fileStorageService.copy({
|
||||
from: {
|
||||
folderPath: getServerlessFolderOrThrow({
|
||||
flatServerlessFunction,
|
||||
folderPath: getLogicFunctionFolderOrThrow({
|
||||
flatLogicFunction,
|
||||
version,
|
||||
}),
|
||||
},
|
||||
to: {
|
||||
folderPath: getServerlessFolderOrThrow({
|
||||
flatServerlessFunction,
|
||||
folderPath: getLogicFunctionFolderOrThrow({
|
||||
flatLogicFunction,
|
||||
version: 'draft',
|
||||
}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async duplicateServerlessFunction({
|
||||
async duplicateLogicFunction({
|
||||
id,
|
||||
version,
|
||||
workspaceId,
|
||||
@@ -762,65 +750,61 @@ export class ServerlessFunctionService {
|
||||
id: string;
|
||||
version: string;
|
||||
workspaceId: string;
|
||||
}): Promise<FlatServerlessFunction> {
|
||||
const { flatServerlessFunctionMaps } =
|
||||
}): Promise<FlatLogicFunction> {
|
||||
const { flatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatServerlessFunctionMaps'],
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const flatServerlessFunctionToDuplicate = findFlatServerlessFunctionOrThrow(
|
||||
{
|
||||
id,
|
||||
flatServerlessFunctionMaps,
|
||||
},
|
||||
);
|
||||
const flatLogicFunctionToDuplicate = findFlatLogicFunctionOrThrow({
|
||||
id,
|
||||
flatLogicFunctionMaps,
|
||||
});
|
||||
|
||||
const newFlatServerlessFunction = await this.createOneServerlessFunction(
|
||||
const newFlatLogicFunction = await this.createOneLogicFunction(
|
||||
{
|
||||
name: flatServerlessFunctionToDuplicate.name,
|
||||
description: flatServerlessFunctionToDuplicate.description ?? undefined,
|
||||
timeoutSeconds: flatServerlessFunctionToDuplicate.timeoutSeconds,
|
||||
applicationId:
|
||||
flatServerlessFunctionToDuplicate.applicationId ?? undefined,
|
||||
serverlessFunctionLayerId:
|
||||
flatServerlessFunctionToDuplicate.serverlessFunctionLayerId,
|
||||
name: flatLogicFunctionToDuplicate.name,
|
||||
description: flatLogicFunctionToDuplicate.description ?? undefined,
|
||||
timeoutSeconds: flatLogicFunctionToDuplicate.timeoutSeconds,
|
||||
applicationId: flatLogicFunctionToDuplicate.applicationId ?? undefined,
|
||||
logicFunctionLayerId: flatLogicFunctionToDuplicate.logicFunctionLayerId,
|
||||
},
|
||||
workspaceId,
|
||||
);
|
||||
|
||||
await this.fileStorageService.copy({
|
||||
from: {
|
||||
folderPath: getServerlessFolderOrThrow({
|
||||
flatServerlessFunction: flatServerlessFunctionToDuplicate,
|
||||
folderPath: getLogicFunctionFolderOrThrow({
|
||||
flatLogicFunction: flatLogicFunctionToDuplicate,
|
||||
version,
|
||||
}),
|
||||
},
|
||||
to: {
|
||||
folderPath: getServerlessFolderOrThrow({
|
||||
flatServerlessFunction: newFlatServerlessFunction,
|
||||
folderPath: getLogicFunctionFolderOrThrow({
|
||||
flatLogicFunction: newFlatLogicFunction,
|
||||
version: 'draft',
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
return newFlatServerlessFunction;
|
||||
return newFlatLogicFunction;
|
||||
}
|
||||
|
||||
private async throttleExecution(workspaceId: string) {
|
||||
try {
|
||||
await this.throttlerService.tokenBucketThrottleOrThrow(
|
||||
`${workspaceId}-serverless-function-execution`,
|
||||
`${workspaceId}-logic-function-execution`,
|
||||
1,
|
||||
this.twentyConfigService.get('SERVERLESS_FUNCTION_EXEC_THROTTLE_LIMIT'),
|
||||
this.twentyConfigService.get('SERVERLESS_FUNCTION_EXEC_THROTTLE_TTL'),
|
||||
this.twentyConfigService.get('LOGIC_FUNCTION_EXEC_THROTTLE_LIMIT'),
|
||||
this.twentyConfigService.get('LOGIC_FUNCTION_EXEC_THROTTLE_TTL'),
|
||||
);
|
||||
} catch {
|
||||
throw new ServerlessFunctionException(
|
||||
'Serverless function execution rate limit exceeded',
|
||||
ServerlessFunctionExceptionCode.SERVERLESS_FUNCTION_EXECUTION_LIMIT_REACHED,
|
||||
throw new LogicFunctionException(
|
||||
'Logic function execution rate limit exceeded',
|
||||
LogicFunctionExceptionCode.LOGIC_FUNCTION_EXECUTION_LIMIT_REACHED,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -838,9 +822,9 @@ export class ServerlessFunctionService {
|
||||
timeoutId = setTimeout(
|
||||
() =>
|
||||
reject(
|
||||
new ServerlessFunctionException(
|
||||
new LogicFunctionException(
|
||||
`Execution timeout: ${timeoutMs / 1000}s`,
|
||||
ServerlessFunctionExceptionCode.SERVERLESS_FUNCTION_EXECUTION_TIMEOUT,
|
||||
LogicFunctionExceptionCode.LOGIC_FUNCTION_EXECUTION_TIMEOUT,
|
||||
),
|
||||
),
|
||||
timeoutMs,
|
||||
+72
-80
@@ -5,21 +5,21 @@ 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 { CreateServerlessFunctionInput } from 'src/engine/metadata-modules/serverless-function/dtos/create-serverless-function.input';
|
||||
import { ServerlessFunctionIdInput } from 'src/engine/metadata-modules/serverless-function/dtos/serverless-function-id.input';
|
||||
import { UpdateServerlessFunctionInput } from 'src/engine/metadata-modules/serverless-function/dtos/update-serverless-function.input';
|
||||
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 {
|
||||
ServerlessFunctionException,
|
||||
ServerlessFunctionExceptionCode,
|
||||
} from 'src/engine/metadata-modules/serverless-function/serverless-function.exception';
|
||||
import { FlatServerlessFunction } from 'src/engine/metadata-modules/serverless-function/types/flat-serverless-function.type';
|
||||
import { fromCreateServerlessFunctionInputToFlatServerlessFunction } from 'src/engine/metadata-modules/serverless-function/utils/from-create-serverless-function-input-to-flat-serverless-function.util';
|
||||
import { fromUpdateServerlessFunctionInputToFlatServerlessFunctionToUpdateOrThrow } from 'src/engine/metadata-modules/serverless-function/utils/from-update-serverless-function-input-to-flat-serverless-function-to-update-or-throw.util';
|
||||
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 ServerlessFunctionV2Service {
|
||||
export class LogicFunctionV2Service {
|
||||
constructor(
|
||||
private readonly flatEntityMapsCacheService: WorkspaceManyOrAllFlatEntityMapsCacheService,
|
||||
private readonly workspaceMigrationValidateBuildAndRunService: WorkspaceMigrationValidateBuildAndRunService,
|
||||
@@ -27,12 +27,12 @@ export class ServerlessFunctionV2Service {
|
||||
) {}
|
||||
|
||||
async createOne({
|
||||
createServerlessFunctionInput,
|
||||
createLogicFunctionInput,
|
||||
workspaceId,
|
||||
applicationId,
|
||||
}: {
|
||||
createServerlessFunctionInput: CreateServerlessFunctionInput & {
|
||||
serverlessFunctionLayerId: string;
|
||||
createLogicFunctionInput: CreateLogicFunctionInput & {
|
||||
logicFunctionLayerId: string;
|
||||
};
|
||||
/**
|
||||
* @deprecated do not use call validateBuildAndRunWorkspaceMigration contextually
|
||||
@@ -48,9 +48,9 @@ export class ServerlessFunctionV2Service {
|
||||
},
|
||||
);
|
||||
|
||||
const flatServerlessFunctionToCreate =
|
||||
fromCreateServerlessFunctionInputToFlatServerlessFunction({
|
||||
createServerlessFunctionInput,
|
||||
const flatLogicFunctionToCreate =
|
||||
fromCreateLogicFunctionInputToFlatLogicFunction({
|
||||
createLogicFunctionInput,
|
||||
workspaceId,
|
||||
workspaceCustomApplicationId:
|
||||
applicationId ?? workspaceCustomFlatApplication.id,
|
||||
@@ -60,8 +60,8 @@ export class ServerlessFunctionV2Service {
|
||||
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
|
||||
{
|
||||
allFlatEntityOperationByMetadataName: {
|
||||
serverlessFunction: {
|
||||
flatEntityToCreate: [flatServerlessFunctionToCreate],
|
||||
logicFunction: {
|
||||
flatEntityToCreate: [flatLogicFunctionToCreate],
|
||||
flatEntityToDelete: [],
|
||||
flatEntityToUpdate: [],
|
||||
},
|
||||
@@ -74,52 +74,50 @@ export class ServerlessFunctionV2Service {
|
||||
if (isDefined(validateAndBuildResult)) {
|
||||
throw new WorkspaceMigrationBuilderException(
|
||||
validateAndBuildResult,
|
||||
'Multiple validation errors occurred while creating serverless function',
|
||||
'Multiple validation errors occurred while creating logic function',
|
||||
);
|
||||
}
|
||||
|
||||
const {
|
||||
flatServerlessFunctionMaps: recomputedExistingFlatServerlessFunctionMaps,
|
||||
} =
|
||||
const { flatLogicFunctionMaps: recomputedExistingFlatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatServerlessFunctionMaps'],
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
return findFlatEntityByIdInFlatEntityMapsOrThrow({
|
||||
flatEntityId: flatServerlessFunctionToCreate.id,
|
||||
flatEntityMaps: recomputedExistingFlatServerlessFunctionMaps,
|
||||
flatEntityId: flatLogicFunctionToCreate.id,
|
||||
flatEntityMaps: recomputedExistingFlatLogicFunctionMaps,
|
||||
});
|
||||
}
|
||||
|
||||
async updateOne(
|
||||
serverlessFunctionInput: UpdateServerlessFunctionInput,
|
||||
logicFunctionInput: UpdateLogicFunctionInput,
|
||||
workspaceId: string,
|
||||
) {
|
||||
const { flatServerlessFunctionMaps } =
|
||||
const { flatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatServerlessFunctionMaps'],
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const optimisticallyUpdatedFlatServerlessFunction =
|
||||
fromUpdateServerlessFunctionInputToFlatServerlessFunctionToUpdateOrThrow({
|
||||
flatServerlessFunctionMaps,
|
||||
updateServerlessFunctionInput: serverlessFunctionInput,
|
||||
const optimisticallyUpdatedFlatLogicFunction =
|
||||
fromUpdateLogicFunctionInputToFlatLogicFunctionToUpdateOrThrow({
|
||||
flatLogicFunctionMaps,
|
||||
updateLogicFunctionInput: logicFunctionInput,
|
||||
});
|
||||
|
||||
const validateAndBuildResult =
|
||||
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
|
||||
{
|
||||
allFlatEntityOperationByMetadataName: {
|
||||
serverlessFunction: {
|
||||
logicFunction: {
|
||||
flatEntityToCreate: [],
|
||||
flatEntityToDelete: [],
|
||||
flatEntityToUpdate: [optimisticallyUpdatedFlatServerlessFunction],
|
||||
flatEntityToUpdate: [optimisticallyUpdatedFlatLogicFunction],
|
||||
},
|
||||
},
|
||||
workspaceId,
|
||||
@@ -130,55 +128,53 @@ export class ServerlessFunctionV2Service {
|
||||
if (isDefined(validateAndBuildResult)) {
|
||||
throw new WorkspaceMigrationBuilderException(
|
||||
validateAndBuildResult,
|
||||
'Multiple validation errors occurred while updating serverless function',
|
||||
'Multiple validation errors occurred while updating logic function',
|
||||
);
|
||||
}
|
||||
|
||||
const {
|
||||
flatServerlessFunctionMaps: recomputedExistingFlatServerlessFunctionMaps,
|
||||
} =
|
||||
const { flatLogicFunctionMaps: recomputedExistingFlatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatServerlessFunctionMaps'],
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
return findFlatEntityByIdInFlatEntityMapsOrThrow({
|
||||
flatEntityId: optimisticallyUpdatedFlatServerlessFunction.id,
|
||||
flatEntityMaps: recomputedExistingFlatServerlessFunctionMaps,
|
||||
flatEntityId: optimisticallyUpdatedFlatLogicFunction.id,
|
||||
flatEntityMaps: recomputedExistingFlatLogicFunctionMaps,
|
||||
});
|
||||
}
|
||||
|
||||
async deleteOne({
|
||||
deleteServerlessFunctionInput,
|
||||
deleteLogicFunctionInput,
|
||||
workspaceId,
|
||||
isSystemBuild = false,
|
||||
}: {
|
||||
deleteServerlessFunctionInput: ServerlessFunctionIdInput;
|
||||
deleteLogicFunctionInput: LogicFunctionIdInput;
|
||||
workspaceId: string;
|
||||
isSystemBuild?: boolean;
|
||||
}): Promise<FlatServerlessFunction> {
|
||||
const { flatServerlessFunctionMaps: existingFlatServerlessFunctionMaps } =
|
||||
}): Promise<FlatLogicFunction> {
|
||||
const { flatLogicFunctionMaps: existingFlatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatServerlessFunctionMaps'],
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const existingFlatServerlessFunction =
|
||||
existingFlatServerlessFunctionMaps.byId[deleteServerlessFunctionInput.id];
|
||||
const existingFlatLogicFunction =
|
||||
existingFlatLogicFunctionMaps.byId[deleteLogicFunctionInput.id];
|
||||
|
||||
if (!isDefined(existingFlatServerlessFunction)) {
|
||||
throw new ServerlessFunctionException(
|
||||
'Serverless function to delete not found',
|
||||
ServerlessFunctionExceptionCode.SERVERLESS_FUNCTION_NOT_FOUND,
|
||||
if (!isDefined(existingFlatLogicFunction)) {
|
||||
throw new LogicFunctionException(
|
||||
'Logic function to delete not found',
|
||||
LogicFunctionExceptionCode.LOGIC_FUNCTION_NOT_FOUND,
|
||||
);
|
||||
}
|
||||
|
||||
const optimisticallyUpdatedFlatServerlessFunctionWithDeletedAt = {
|
||||
...existingFlatServerlessFunction,
|
||||
const optimisticallyUpdatedFlatLogicFunctionWithDeletedAt = {
|
||||
...existingFlatLogicFunction,
|
||||
deletedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
@@ -186,11 +182,11 @@ export class ServerlessFunctionV2Service {
|
||||
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
|
||||
{
|
||||
allFlatEntityOperationByMetadataName: {
|
||||
serverlessFunction: {
|
||||
logicFunction: {
|
||||
flatEntityToCreate: [],
|
||||
flatEntityToDelete: [],
|
||||
flatEntityToUpdate: [
|
||||
optimisticallyUpdatedFlatServerlessFunctionWithDeletedAt,
|
||||
optimisticallyUpdatedFlatLogicFunctionWithDeletedAt,
|
||||
],
|
||||
},
|
||||
},
|
||||
@@ -202,52 +198,48 @@ export class ServerlessFunctionV2Service {
|
||||
if (isDefined(validateAndBuildResult)) {
|
||||
throw new WorkspaceMigrationBuilderException(
|
||||
validateAndBuildResult,
|
||||
'Multiple validation errors occurred while deleting serverless function',
|
||||
'Multiple validation errors occurred while deleting logic function',
|
||||
);
|
||||
}
|
||||
|
||||
const {
|
||||
flatServerlessFunctionMaps: recomputedExistingFlatServerlessFunctionMaps,
|
||||
} =
|
||||
const { flatLogicFunctionMaps: recomputedExistingFlatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatServerlessFunctionMaps'],
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
return findFlatEntityByIdInFlatEntityMapsOrThrow({
|
||||
flatEntityId: optimisticallyUpdatedFlatServerlessFunctionWithDeletedAt.id,
|
||||
flatEntityMaps: recomputedExistingFlatServerlessFunctionMaps,
|
||||
flatEntityId: optimisticallyUpdatedFlatLogicFunctionWithDeletedAt.id,
|
||||
flatEntityMaps: recomputedExistingFlatLogicFunctionMaps,
|
||||
});
|
||||
}
|
||||
|
||||
async destroyOne({
|
||||
destroyServerlessFunctionInput,
|
||||
destroyLogicFunctionInput,
|
||||
workspaceId,
|
||||
isSystemBuild = false,
|
||||
}: {
|
||||
destroyServerlessFunctionInput: ServerlessFunctionIdInput;
|
||||
destroyLogicFunctionInput: LogicFunctionIdInput;
|
||||
workspaceId: string;
|
||||
isSystemBuild?: boolean;
|
||||
}): Promise<FlatServerlessFunction> {
|
||||
const { flatServerlessFunctionMaps: existingFlatServerlessFunctionMaps } =
|
||||
}): Promise<FlatLogicFunction> {
|
||||
const { flatLogicFunctionMaps: existingFlatLogicFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatServerlessFunctionMaps'],
|
||||
flatMapsKeys: ['flatLogicFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const existingFlatServerlessFunction =
|
||||
existingFlatServerlessFunctionMaps.byId[
|
||||
destroyServerlessFunctionInput.id
|
||||
];
|
||||
const existingFlatLogicFunction =
|
||||
existingFlatLogicFunctionMaps.byId[destroyLogicFunctionInput.id];
|
||||
|
||||
if (!isDefined(existingFlatServerlessFunction)) {
|
||||
throw new ServerlessFunctionException(
|
||||
'Serverless function to destroy not found',
|
||||
ServerlessFunctionExceptionCode.SERVERLESS_FUNCTION_NOT_FOUND,
|
||||
if (!isDefined(existingFlatLogicFunction)) {
|
||||
throw new LogicFunctionException(
|
||||
'Logic function to destroy not found',
|
||||
LogicFunctionExceptionCode.LOGIC_FUNCTION_NOT_FOUND,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -255,9 +247,9 @@ export class ServerlessFunctionV2Service {
|
||||
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
|
||||
{
|
||||
allFlatEntityOperationByMetadataName: {
|
||||
serverlessFunction: {
|
||||
logicFunction: {
|
||||
flatEntityToCreate: [],
|
||||
flatEntityToDelete: [existingFlatServerlessFunction],
|
||||
flatEntityToDelete: [existingFlatLogicFunction],
|
||||
flatEntityToUpdate: [],
|
||||
},
|
||||
},
|
||||
@@ -269,10 +261,10 @@ export class ServerlessFunctionV2Service {
|
||||
if (isDefined(validateAndBuildResult)) {
|
||||
throw new WorkspaceMigrationBuilderException(
|
||||
validateAndBuildResult,
|
||||
'Multiple validation errors occurred while destroying serverless function',
|
||||
'Multiple validation errors occurred while destroying logic function',
|
||||
);
|
||||
}
|
||||
|
||||
return existingFlatServerlessFunction;
|
||||
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,
|
||||
});
|
||||
};
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import { createHash } from 'crypto';
|
||||
|
||||
export const serverlessFunctionCreateHash = (fileContent: string) => {
|
||||
export const logicFunctionCreateHash = (fileContent: string) => {
|
||||
return createHash('sha512')
|
||||
.update(fileContent)
|
||||
.digest('hex')
|
||||
+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;
|
||||
};
|
||||
@@ -14,8 +14,8 @@ import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permi
|
||||
import { RoleModule } from 'src/engine/metadata-modules/role/role.module';
|
||||
import { RouteTriggerModule } from 'src/engine/metadata-modules/route-trigger/route-trigger.module';
|
||||
import { SearchFieldMetadataModule } from 'src/engine/metadata-modules/search-field-metadata/search-field-metadata.module';
|
||||
import { ServerlessFunctionLayerModule } from 'src/engine/metadata-modules/serverless-function-layer/serverless-function-layer.module';
|
||||
import { ServerlessFunctionModule } from 'src/engine/metadata-modules/serverless-function/serverless-function.module';
|
||||
import { LogicFunctionLayerModule } from 'src/engine/metadata-modules/logic-function-layer/logic-function-layer.module';
|
||||
import { LogicFunctionModule } from 'src/engine/metadata-modules/logic-function/logic-function.module';
|
||||
import { SkillModule } from 'src/engine/metadata-modules/skill/skill.module';
|
||||
import { ViewModule } from 'src/engine/metadata-modules/view/view.module';
|
||||
import { WorkspaceMetadataVersionModule } from 'src/engine/metadata-modules/workspace-metadata-version/workspace-metadata-version.module';
|
||||
@@ -27,8 +27,8 @@ import { WorkspaceMetadataVersionModule } from 'src/engine/metadata-modules/work
|
||||
FrontComponentModule,
|
||||
ObjectMetadataModule,
|
||||
SearchFieldMetadataModule,
|
||||
ServerlessFunctionModule,
|
||||
ServerlessFunctionLayerModule,
|
||||
LogicFunctionModule,
|
||||
LogicFunctionLayerModule,
|
||||
SkillModule,
|
||||
CommandMenuItemModule,
|
||||
NavigationMenuItemModule,
|
||||
@@ -49,7 +49,7 @@ import { WorkspaceMetadataVersionModule } from 'src/engine/metadata-modules/work
|
||||
FrontComponentModule,
|
||||
ObjectMetadataModule,
|
||||
SearchFieldMetadataModule,
|
||||
ServerlessFunctionModule,
|
||||
LogicFunctionModule,
|
||||
SkillModule,
|
||||
CommandMenuItemModule,
|
||||
NavigationMenuItemModule,
|
||||
|
||||
+2
-2
@@ -363,8 +363,8 @@ export class NavigationMenuItemService {
|
||||
);
|
||||
}
|
||||
|
||||
if (isDefined(authContext.application?.defaultServerlessFunctionRoleId)) {
|
||||
return authContext.application.defaultServerlessFunctionRoleId;
|
||||
if (isDefined(authContext.application?.defaultLogicFunctionRoleId)) {
|
||||
return authContext.application.defaultLogicFunctionRoleId;
|
||||
}
|
||||
|
||||
if (isDefined(authContext.userWorkspaceId)) {
|
||||
|
||||
+2
-2
@@ -27,7 +27,7 @@ export class RouteTriggerRestApiExceptionFilter implements ExceptionFilter {
|
||||
case RouteTriggerExceptionCode.WORKSPACE_NOT_FOUND:
|
||||
case RouteTriggerExceptionCode.ROUTE_NOT_FOUND:
|
||||
case RouteTriggerExceptionCode.TRIGGER_NOT_FOUND:
|
||||
case RouteTriggerExceptionCode.SERVERLESS_FUNCTION_NOT_FOUND:
|
||||
case RouteTriggerExceptionCode.LOGIC_FUNCTION_NOT_FOUND:
|
||||
return this.httpExceptionHandlerService.handleError(
|
||||
exception as CustomException,
|
||||
response,
|
||||
@@ -39,7 +39,7 @@ export class RouteTriggerRestApiExceptionFilter implements ExceptionFilter {
|
||||
response,
|
||||
403,
|
||||
);
|
||||
case RouteTriggerExceptionCode.SERVERLESS_FUNCTION_EXECUTION_ERROR:
|
||||
case RouteTriggerExceptionCode.LOGIC_FUNCTION_EXECUTION_ERROR:
|
||||
return this.httpExceptionHandlerService.handleError(
|
||||
exception as CustomException,
|
||||
response,
|
||||
|
||||
+6
-6
@@ -8,11 +8,11 @@ export enum RouteTriggerExceptionCode {
|
||||
WORKSPACE_NOT_FOUND = 'WORKSPACE_NOT_FOUND',
|
||||
ROUTE_NOT_FOUND = 'ROUTE_NOT_FOUND',
|
||||
TRIGGER_NOT_FOUND = 'TRIGGER_NOT_FOUND',
|
||||
SERVERLESS_FUNCTION_NOT_FOUND = 'SERVERLESS_FUNCTION_NOT_FOUND',
|
||||
LOGIC_FUNCTION_NOT_FOUND = 'LOGIC_FUNCTION_NOT_FOUND',
|
||||
ROUTE_ALREADY_EXIST = 'ROUTE_ALREADY_EXIST',
|
||||
ROUTE_PATH_ALREADY_EXIST = 'ROUTE_PATH_ALREADY_EXIST',
|
||||
FORBIDDEN_EXCEPTION = 'FORBIDDEN_EXCEPTION',
|
||||
SERVERLESS_FUNCTION_EXECUTION_ERROR = 'SERVERLESS_FUNCTION_EXECUTION_ERROR',
|
||||
LOGIC_FUNCTION_EXECUTION_ERROR = 'LOGIC_FUNCTION_EXECUTION_ERROR',
|
||||
}
|
||||
|
||||
const getRouteTriggerExceptionUserFriendlyMessage = (
|
||||
@@ -25,16 +25,16 @@ const getRouteTriggerExceptionUserFriendlyMessage = (
|
||||
return msg`Route not found.`;
|
||||
case RouteTriggerExceptionCode.TRIGGER_NOT_FOUND:
|
||||
return msg`Trigger not found.`;
|
||||
case RouteTriggerExceptionCode.SERVERLESS_FUNCTION_NOT_FOUND:
|
||||
return msg`Serverless function not found.`;
|
||||
case RouteTriggerExceptionCode.LOGIC_FUNCTION_NOT_FOUND:
|
||||
return msg`Logic function not found.`;
|
||||
case RouteTriggerExceptionCode.ROUTE_ALREADY_EXIST:
|
||||
return msg`Route already exists.`;
|
||||
case RouteTriggerExceptionCode.ROUTE_PATH_ALREADY_EXIST:
|
||||
return msg`Route path already exists.`;
|
||||
case RouteTriggerExceptionCode.FORBIDDEN_EXCEPTION:
|
||||
return msg`You do not have permission to perform this action.`;
|
||||
case RouteTriggerExceptionCode.SERVERLESS_FUNCTION_EXECUTION_ERROR:
|
||||
return msg`Serverless function execution failed.`;
|
||||
case RouteTriggerExceptionCode.LOGIC_FUNCTION_EXECUTION_ERROR:
|
||||
return msg`Logic function execution failed.`;
|
||||
default:
|
||||
assertUnreachable(code);
|
||||
}
|
||||
|
||||
+4
-4
@@ -5,15 +5,15 @@ import { TokenModule } from 'src/engine/core-modules/auth/token/token.module';
|
||||
import { WorkspaceDomainsModule } from 'src/engine/core-modules/domain/workspace-domains/workspace-domains.module';
|
||||
import { RouteTriggerController } from 'src/engine/metadata-modules/route-trigger/route-trigger.controller';
|
||||
import { RouteTriggerService } from 'src/engine/metadata-modules/route-trigger/route-trigger.service';
|
||||
import { ServerlessFunctionEntity } from 'src/engine/metadata-modules/serverless-function/serverless-function.entity';
|
||||
import { ServerlessFunctionModule } from 'src/engine/metadata-modules/serverless-function/serverless-function.module';
|
||||
import { LogicFunctionEntity } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
|
||||
import { LogicFunctionModule } from 'src/engine/metadata-modules/logic-function/logic-function.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([ServerlessFunctionEntity]),
|
||||
TypeOrmModule.forFeature([LogicFunctionEntity]),
|
||||
TokenModule,
|
||||
WorkspaceDomainsModule,
|
||||
ServerlessFunctionModule,
|
||||
LogicFunctionModule,
|
||||
],
|
||||
controllers: [RouteTriggerController],
|
||||
providers: [RouteTriggerService],
|
||||
|
||||
+25
-26
@@ -13,28 +13,28 @@ import {
|
||||
RouteTriggerException,
|
||||
RouteTriggerExceptionCode,
|
||||
} from 'src/engine/metadata-modules/route-trigger/exceptions/route-trigger.exception';
|
||||
import { buildServerlessFunctionEvent } from 'src/engine/metadata-modules/route-trigger/utils/build-serverless-function-event.util';
|
||||
import { ServerlessFunctionEntity } from 'src/engine/metadata-modules/serverless-function/serverless-function.entity';
|
||||
import { ServerlessFunctionService } from 'src/engine/metadata-modules/serverless-function/serverless-function.service';
|
||||
import { buildLogicFunctionEvent } from 'src/engine/metadata-modules/route-trigger/utils/build-logic-function-event.util';
|
||||
import { LogicFunctionEntity } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
|
||||
import { LogicFunctionService } from 'src/engine/metadata-modules/logic-function/logic-function.service';
|
||||
|
||||
@Injectable()
|
||||
export class RouteTriggerService {
|
||||
constructor(
|
||||
private readonly accessTokenService: AccessTokenService,
|
||||
private readonly serverlessFunctionService: ServerlessFunctionService,
|
||||
private readonly logicFunctionService: LogicFunctionService,
|
||||
private readonly workspaceDomainsService: WorkspaceDomainsService,
|
||||
@InjectRepository(ServerlessFunctionEntity)
|
||||
private readonly serverlessFunctionRepository: Repository<ServerlessFunctionEntity>,
|
||||
@InjectRepository(LogicFunctionEntity)
|
||||
private readonly logicFunctionRepository: Repository<LogicFunctionEntity>,
|
||||
) {}
|
||||
|
||||
private async getServerlessFunctionWithPathParamsOrFail({
|
||||
private async getLogicFunctionWithPathParamsOrFail({
|
||||
request,
|
||||
httpMethod,
|
||||
}: {
|
||||
request: Request;
|
||||
httpMethod: HTTPMethod;
|
||||
}): Promise<{
|
||||
serverlessFunction: ServerlessFunctionEntity;
|
||||
logicFunction: LogicFunctionEntity;
|
||||
pathParams: Partial<Record<string, string | string[]>>;
|
||||
}> {
|
||||
const host = `${request.protocol}://${request.get('host')}`;
|
||||
@@ -52,8 +52,8 @@ export class RouteTriggerService {
|
||||
),
|
||||
);
|
||||
|
||||
const serverlessFunctionsWithHttpRouteTrigger =
|
||||
await this.serverlessFunctionRepository.find({
|
||||
const logicFunctionsWithHttpRouteTrigger =
|
||||
await this.logicFunctionRepository.find({
|
||||
where: {
|
||||
workspaceId: workspace.id,
|
||||
httpRouteTriggerSettings: Not(IsNull()),
|
||||
@@ -62,8 +62,8 @@ export class RouteTriggerService {
|
||||
|
||||
const requestPath = request.path.replace(/^\/s\//, '/');
|
||||
|
||||
for (const serverlessFunction of serverlessFunctionsWithHttpRouteTrigger) {
|
||||
const httpRouteSettings = serverlessFunction.httpRouteTriggerSettings;
|
||||
for (const logicFunction of logicFunctionsWithHttpRouteTrigger) {
|
||||
const httpRouteSettings = logicFunction.httpRouteTriggerSettings;
|
||||
|
||||
if (
|
||||
!isDefined(httpRouteSettings) ||
|
||||
@@ -79,7 +79,7 @@ export class RouteTriggerService {
|
||||
|
||||
if (routeMatched) {
|
||||
return {
|
||||
serverlessFunction,
|
||||
logicFunction,
|
||||
pathParams: routeMatched.params,
|
||||
};
|
||||
}
|
||||
@@ -125,34 +125,33 @@ export class RouteTriggerService {
|
||||
request: Request;
|
||||
httpMethod: HTTPMethod;
|
||||
}) {
|
||||
const { serverlessFunction, pathParams } =
|
||||
await this.getServerlessFunctionWithPathParamsOrFail({
|
||||
const { logicFunction, pathParams } =
|
||||
await this.getLogicFunctionWithPathParamsOrFail({
|
||||
request,
|
||||
httpMethod,
|
||||
});
|
||||
|
||||
const httpRouteSettings = serverlessFunction.httpRouteTriggerSettings;
|
||||
const httpRouteSettings = logicFunction.httpRouteTriggerSettings;
|
||||
|
||||
if (httpRouteSettings?.isAuthRequired) {
|
||||
await this.validateWorkspaceFromRequest({
|
||||
request,
|
||||
workspaceId: serverlessFunction.workspaceId,
|
||||
workspaceId: logicFunction.workspaceId,
|
||||
});
|
||||
}
|
||||
|
||||
const event = buildServerlessFunctionEvent({
|
||||
const event = buildLogicFunctionEvent({
|
||||
request,
|
||||
pathParameters: pathParams,
|
||||
forwardedRequestHeaders: httpRouteSettings?.forwardedRequestHeaders ?? [],
|
||||
});
|
||||
|
||||
const result =
|
||||
await this.serverlessFunctionService.executeOneServerlessFunction({
|
||||
id: serverlessFunction.id,
|
||||
workspaceId: serverlessFunction.workspaceId,
|
||||
payload: event,
|
||||
version: 'draft',
|
||||
});
|
||||
const result = await this.logicFunctionService.executeOneLogicFunction({
|
||||
id: logicFunction.id,
|
||||
workspaceId: logicFunction.workspaceId,
|
||||
payload: event,
|
||||
version: 'draft',
|
||||
});
|
||||
|
||||
if (!isDefined(result)) {
|
||||
return result;
|
||||
@@ -161,7 +160,7 @@ export class RouteTriggerService {
|
||||
if (result.error) {
|
||||
throw new RouteTriggerException(
|
||||
result.error.errorMessage,
|
||||
RouteTriggerExceptionCode.SERVERLESS_FUNCTION_EXECUTION_ERROR,
|
||||
RouteTriggerExceptionCode.LOGIC_FUNCTION_EXECUTION_ERROR,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+11
-11
@@ -1,12 +1,12 @@
|
||||
import { type Request } from 'express';
|
||||
|
||||
import {
|
||||
buildServerlessFunctionEvent,
|
||||
buildLogicFunctionEvent,
|
||||
extractBody,
|
||||
filterRequestHeaders,
|
||||
normalizePathParameters,
|
||||
normalizeQueryStringParameters,
|
||||
} from 'src/engine/metadata-modules/route-trigger/utils/build-serverless-function-event.util';
|
||||
} from 'src/engine/metadata-modules/route-trigger/utils/build-logic-function-event.util';
|
||||
|
||||
describe('filterRequestHeaders', () => {
|
||||
it('should filter headers based on allowed names', () => {
|
||||
@@ -272,7 +272,7 @@ describe('normalizePathParameters', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildServerlessFunctionEvent', () => {
|
||||
describe('buildLogicFunctionEvent', () => {
|
||||
const createMockRequest = (overrides: Partial<Request> = {}): Request =>
|
||||
({
|
||||
headers: {},
|
||||
@@ -296,7 +296,7 @@ describe('buildServerlessFunctionEvent', () => {
|
||||
path: '/s/users/123',
|
||||
});
|
||||
|
||||
const result = buildServerlessFunctionEvent({
|
||||
const result = buildLogicFunctionEvent({
|
||||
request,
|
||||
pathParameters: { id: '123' },
|
||||
forwardedRequestHeaders: ['content-type', 'authorization'],
|
||||
@@ -325,7 +325,7 @@ describe('buildServerlessFunctionEvent', () => {
|
||||
path: '/s/api/users',
|
||||
});
|
||||
|
||||
const result = buildServerlessFunctionEvent({
|
||||
const result = buildLogicFunctionEvent({
|
||||
request,
|
||||
pathParameters: {},
|
||||
forwardedRequestHeaders: [],
|
||||
@@ -339,7 +339,7 @@ describe('buildServerlessFunctionEvent', () => {
|
||||
path: '/api/users',
|
||||
});
|
||||
|
||||
const result = buildServerlessFunctionEvent({
|
||||
const result = buildLogicFunctionEvent({
|
||||
request,
|
||||
pathParameters: {},
|
||||
forwardedRequestHeaders: [],
|
||||
@@ -355,7 +355,7 @@ describe('buildServerlessFunctionEvent', () => {
|
||||
body: undefined,
|
||||
});
|
||||
|
||||
const result = buildServerlessFunctionEvent({
|
||||
const result = buildLogicFunctionEvent({
|
||||
request,
|
||||
pathParameters: {},
|
||||
forwardedRequestHeaders: [],
|
||||
@@ -371,7 +371,7 @@ describe('buildServerlessFunctionEvent', () => {
|
||||
path: '/s/users/456',
|
||||
});
|
||||
|
||||
const result = buildServerlessFunctionEvent({
|
||||
const result = buildLogicFunctionEvent({
|
||||
request,
|
||||
pathParameters: { userId: '456' },
|
||||
forwardedRequestHeaders: [],
|
||||
@@ -391,7 +391,7 @@ describe('buildServerlessFunctionEvent', () => {
|
||||
},
|
||||
});
|
||||
|
||||
const result = buildServerlessFunctionEvent({
|
||||
const result = buildLogicFunctionEvent({
|
||||
request,
|
||||
pathParameters: {},
|
||||
forwardedRequestHeaders: ['x-api-key'],
|
||||
@@ -407,7 +407,7 @@ describe('buildServerlessFunctionEvent', () => {
|
||||
it('should set isBase64Encoded to false', () => {
|
||||
const request = createMockRequest();
|
||||
|
||||
const result = buildServerlessFunctionEvent({
|
||||
const result = buildLogicFunctionEvent({
|
||||
request,
|
||||
pathParameters: {},
|
||||
forwardedRequestHeaders: [],
|
||||
@@ -421,7 +421,7 @@ describe('buildServerlessFunctionEvent', () => {
|
||||
path: '/s/organizations/org1/users/user1/posts',
|
||||
});
|
||||
|
||||
const result = buildServerlessFunctionEvent({
|
||||
const result = buildLogicFunctionEvent({
|
||||
request,
|
||||
pathParameters: {
|
||||
orgId: 'org1',
|
||||
+3
-3
@@ -1,5 +1,5 @@
|
||||
import { type Request } from 'express';
|
||||
import { type ServerlessFunctionEvent } from 'twenty-shared/types';
|
||||
import { type LogicFunctionEvent } from 'twenty-shared/types';
|
||||
|
||||
/**
|
||||
* Filters HTTP headers from Express request based on allowed header names
|
||||
@@ -130,7 +130,7 @@ export const normalizePathParameters = (
|
||||
* Builds an AWS HTTP API v2 compatible event from an Express request
|
||||
* @see https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html
|
||||
*/
|
||||
export const buildServerlessFunctionEvent = ({
|
||||
export const buildLogicFunctionEvent = ({
|
||||
request,
|
||||
pathParameters,
|
||||
forwardedRequestHeaders,
|
||||
@@ -138,7 +138,7 @@ export const buildServerlessFunctionEvent = ({
|
||||
request: Request;
|
||||
pathParameters: Record<string, string | string[] | undefined>;
|
||||
forwardedRequestHeaders: string[];
|
||||
}): ServerlessFunctionEvent => {
|
||||
}): LogicFunctionEvent => {
|
||||
return {
|
||||
headers: filterRequestHeaders({
|
||||
requestHeaders: request.headers,
|
||||
-27
@@ -1,27 +0,0 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
|
||||
import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permissions.module';
|
||||
import { ServerlessFunctionLayerEntity } from 'src/engine/metadata-modules/serverless-function-layer/serverless-function-layer.entity';
|
||||
import { ServerlessFunctionLayerResolver } from 'src/engine/metadata-modules/serverless-function-layer/serverless-function-layer.resolver';
|
||||
import { ServerlessFunctionLayerService } from 'src/engine/metadata-modules/serverless-function-layer/serverless-function-layer.service';
|
||||
import { WorkspaceServerlessFunctionLayerMapCacheService } from 'src/engine/metadata-modules/serverless-function-layer/services/workspace-serverless-function-layer-map-cache.service';
|
||||
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
PermissionsModule,
|
||||
TypeOrmModule.forFeature([ServerlessFunctionLayerEntity]),
|
||||
WorkspaceCacheModule,
|
||||
],
|
||||
providers: [
|
||||
ServerlessFunctionLayerService,
|
||||
ServerlessFunctionLayerResolver,
|
||||
WorkspaceServerlessFunctionLayerMapCacheService,
|
||||
],
|
||||
exports: [
|
||||
ServerlessFunctionLayerService,
|
||||
WorkspaceServerlessFunctionLayerMapCacheService,
|
||||
],
|
||||
})
|
||||
export class ServerlessFunctionLayerModule {}
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
import { UseGuards } from '@nestjs/common';
|
||||
import { Args, Mutation, Resolver } from '@nestjs/graphql';
|
||||
|
||||
import { PermissionFlagType } from 'twenty-shared/constants';
|
||||
|
||||
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
|
||||
import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
|
||||
import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';
|
||||
import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
|
||||
import { CreateServerlessFunctionLayerInput } from 'src/engine/metadata-modules/serverless-function-layer/dtos/create-serverless-function-layer.input';
|
||||
import { ServerlessFunctionLayerDTO } from 'src/engine/metadata-modules/serverless-function-layer/dtos/serverless-function-layer.dto';
|
||||
import { ServerlessFunctionLayerService } from 'src/engine/metadata-modules/serverless-function-layer/serverless-function-layer.service';
|
||||
|
||||
@UseGuards(WorkspaceAuthGuard)
|
||||
@Resolver()
|
||||
export class ServerlessFunctionLayerResolver {
|
||||
constructor(
|
||||
private readonly serverlessFunctionLayerService: ServerlessFunctionLayerService,
|
||||
) {}
|
||||
|
||||
@Mutation(() => ServerlessFunctionLayerDTO)
|
||||
@UseGuards(SettingsPermissionGuard(PermissionFlagType.WORKFLOWS))
|
||||
async createOneServerlessFunctionLayer(
|
||||
@Args()
|
||||
createServerlessFunctionLayerInput: CreateServerlessFunctionLayerInput,
|
||||
@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
|
||||
) {
|
||||
return this.serverlessFunctionLayerService.create(
|
||||
createServerlessFunctionLayerInput,
|
||||
workspaceId,
|
||||
);
|
||||
}
|
||||
}
|
||||
-87
@@ -1,87 +0,0 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
|
||||
import { Repository } from 'typeorm';
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
|
||||
import type { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
|
||||
|
||||
import { ServerlessFunctionLayerEntity } from 'src/engine/metadata-modules/serverless-function-layer/serverless-function-layer.entity';
|
||||
import { CreateServerlessFunctionLayerInput } from 'src/engine/metadata-modules/serverless-function-layer/dtos/create-serverless-function-layer.input';
|
||||
import { getLastCommonLayerDependencies } from 'src/engine/core-modules/serverless/drivers/utils/get-last-common-layer-dependencies';
|
||||
import { serverlessFunctionCreateHash } from 'src/engine/metadata-modules/serverless-function/utils/serverless-function-create-hash.utils';
|
||||
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
|
||||
|
||||
@Injectable()
|
||||
export class ServerlessFunctionLayerService {
|
||||
constructor(
|
||||
@InjectRepository(ServerlessFunctionLayerEntity)
|
||||
private readonly serverlessFunctionLayerRepository: Repository<ServerlessFunctionLayerEntity>,
|
||||
private readonly workspaceCacheService: WorkspaceCacheService,
|
||||
) {}
|
||||
|
||||
async create(
|
||||
{ packageJson, yarnLock }: CreateServerlessFunctionLayerInput,
|
||||
workspaceId: string,
|
||||
) {
|
||||
const checksum = serverlessFunctionCreateHash(yarnLock);
|
||||
|
||||
const serverlessFunctionLayer =
|
||||
this.serverlessFunctionLayerRepository.create({
|
||||
packageJson,
|
||||
yarnLock,
|
||||
checksum,
|
||||
workspaceId,
|
||||
});
|
||||
|
||||
const savedLayer = await this.serverlessFunctionLayerRepository.save(
|
||||
serverlessFunctionLayer,
|
||||
);
|
||||
|
||||
await this.workspaceCacheService.invalidateAndRecompute(workspaceId, [
|
||||
'serverlessFunctionLayerMaps',
|
||||
]);
|
||||
|
||||
return savedLayer;
|
||||
}
|
||||
|
||||
async update(
|
||||
id: string,
|
||||
data: QueryDeepPartialEntity<ServerlessFunctionLayerEntity>,
|
||||
workspaceId: string,
|
||||
) {
|
||||
const checksum = data.yarnLock
|
||||
? serverlessFunctionCreateHash(data.yarnLock as string)
|
||||
: undefined;
|
||||
|
||||
const updateData = { ...data, ...(checksum && { checksum }) };
|
||||
|
||||
const result = await this.serverlessFunctionLayerRepository.update(
|
||||
id,
|
||||
updateData,
|
||||
);
|
||||
|
||||
await this.workspaceCacheService.invalidateAndRecompute(workspaceId, [
|
||||
'serverlessFunctionLayerMaps',
|
||||
]);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async createCommonLayerIfNotExist(workspaceId: string) {
|
||||
const { packageJson, yarnLock } = await getLastCommonLayerDependencies();
|
||||
const checksum = serverlessFunctionCreateHash(yarnLock);
|
||||
const commonLayer = await this.serverlessFunctionLayerRepository.findOne({
|
||||
where: {
|
||||
checksum,
|
||||
workspaceId,
|
||||
},
|
||||
});
|
||||
|
||||
if (isDefined(commonLayer)) {
|
||||
return commonLayer;
|
||||
}
|
||||
|
||||
return this.create({ packageJson, yarnLock }, workspaceId);
|
||||
}
|
||||
}
|
||||
-47
@@ -1,47 +0,0 @@
|
||||
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 { ServerlessFunctionLayerEntity } from 'src/engine/metadata-modules/serverless-function-layer/serverless-function-layer.entity';
|
||||
import { type ServerlessFunctionLayerCacheMaps } from 'src/engine/metadata-modules/serverless-function-layer/types/serverless-function-layer-cache-maps.type';
|
||||
import { fromServerlessFunctionLayerEntityToFlatServerlessFunctionLayer } from 'src/engine/metadata-modules/serverless-function-layer/utils/from-serverless-function-layer-entity-to-flat-serverless-function-layer.util';
|
||||
import { WorkspaceCache } from 'src/engine/workspace-cache/decorators/workspace-cache.decorator';
|
||||
|
||||
@Injectable()
|
||||
@WorkspaceCache('serverlessFunctionLayerMaps')
|
||||
export class WorkspaceServerlessFunctionLayerMapCacheService extends WorkspaceCacheProvider<ServerlessFunctionLayerCacheMaps> {
|
||||
constructor(
|
||||
@InjectRepository(ServerlessFunctionLayerEntity)
|
||||
private readonly serverlessFunctionLayerRepository: Repository<ServerlessFunctionLayerEntity>,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async computeForCache(
|
||||
workspaceId: string,
|
||||
): Promise<ServerlessFunctionLayerCacheMaps> {
|
||||
const serverlessFunctionLayerEntities =
|
||||
await this.serverlessFunctionLayerRepository.find({
|
||||
where: {
|
||||
workspaceId,
|
||||
},
|
||||
});
|
||||
|
||||
const serverlessFunctionLayerMaps: ServerlessFunctionLayerCacheMaps = {
|
||||
byId: {},
|
||||
};
|
||||
|
||||
for (const entity of serverlessFunctionLayerEntities) {
|
||||
const flatServerlessFunctionLayer =
|
||||
fromServerlessFunctionLayerEntityToFlatServerlessFunctionLayer(entity);
|
||||
|
||||
serverlessFunctionLayerMaps.byId[flatServerlessFunctionLayer.id] =
|
||||
flatServerlessFunctionLayer;
|
||||
}
|
||||
|
||||
return serverlessFunctionLayerMaps;
|
||||
}
|
||||
}
|
||||
-5
@@ -1,5 +0,0 @@
|
||||
import { type FlatEntityFrom } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-from.type';
|
||||
import { type ServerlessFunctionLayerEntity } from 'src/engine/metadata-modules/serverless-function-layer/serverless-function-layer.entity';
|
||||
|
||||
export type FlatServerlessFunctionLayer =
|
||||
FlatEntityFrom<ServerlessFunctionLayerEntity>;
|
||||
-5
@@ -1,5 +0,0 @@
|
||||
import { type FlatServerlessFunctionLayer } from 'src/engine/metadata-modules/serverless-function-layer/types/flat-serverless-function-layer.type';
|
||||
|
||||
export type ServerlessFunctionLayerCacheMaps = {
|
||||
byId: Partial<Record<string, FlatServerlessFunctionLayer>>;
|
||||
};
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
import { type ServerlessFunctionLayerEntity } from 'src/engine/metadata-modules/serverless-function-layer/serverless-function-layer.entity';
|
||||
import { type FlatServerlessFunctionLayer } from 'src/engine/metadata-modules/serverless-function-layer/types/flat-serverless-function-layer.type';
|
||||
|
||||
export const fromServerlessFunctionLayerEntityToFlatServerlessFunctionLayer = (
|
||||
entity: ServerlessFunctionLayerEntity,
|
||||
): FlatServerlessFunctionLayer => ({
|
||||
id: entity.id,
|
||||
packageJson: entity.packageJson,
|
||||
yarnLock: entity.yarnLock,
|
||||
checksum: entity.checksum,
|
||||
workspaceId: entity.workspaceId,
|
||||
createdAt: entity.createdAt.toISOString(),
|
||||
updatedAt: entity.updatedAt.toISOString(),
|
||||
serverlessFunctionIds: entity.serverlessFunctions?.map((sf) => sf.id) ?? [],
|
||||
});
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
import { type FlatServerlessFunction } from 'src/engine/metadata-modules/serverless-function/types/flat-serverless-function.type';
|
||||
|
||||
export const FLAT_SERVERLESS_FUNCTION_EDITABLE_PROPERTIES = [
|
||||
'name',
|
||||
'description',
|
||||
'timeoutSeconds',
|
||||
'checksum',
|
||||
'code',
|
||||
'sourceHandlerPath',
|
||||
'handlerName',
|
||||
'toolInputSchema',
|
||||
'isTool',
|
||||
] as const satisfies (keyof FlatServerlessFunction)[];
|
||||
-1
@@ -1 +0,0 @@
|
||||
export const SERVERLESS_FUNCTION_PUBLISHED = 'serverless_function_published';
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
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 { ServerlessFunctionService } from 'src/engine/metadata-modules/serverless-function/serverless-function.service';
|
||||
|
||||
export type ServerlessFunctionTriggerJobData = {
|
||||
serverlessFunctionId: string;
|
||||
workspaceId: string;
|
||||
payload?: object;
|
||||
};
|
||||
|
||||
@Processor({
|
||||
queueName: MessageQueue.serverlessFunctionQueue,
|
||||
scope: Scope.REQUEST,
|
||||
})
|
||||
export class ServerlessFunctionTriggerJob {
|
||||
constructor(
|
||||
private readonly serverlessFunctionService: ServerlessFunctionService,
|
||||
) {}
|
||||
|
||||
@Process(ServerlessFunctionTriggerJob.name)
|
||||
async handle(serverlessFunctionPayloads: ServerlessFunctionTriggerJobData[]) {
|
||||
await Promise.all(
|
||||
serverlessFunctionPayloads.map(
|
||||
async (serverlessFunctionPayload) =>
|
||||
await this.serverlessFunctionService.executeOneServerlessFunction({
|
||||
id: serverlessFunctionPayload.serverlessFunctionId,
|
||||
workspaceId: serverlessFunctionPayload.workspaceId,
|
||||
payload: serverlessFunctionPayload.payload || {},
|
||||
version: 'draft',
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
-61
@@ -1,61 +0,0 @@
|
||||
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 ServerlessFunctionExceptionCode {
|
||||
SERVERLESS_FUNCTION_NOT_FOUND = 'SERVERLESS_FUNCTION_NOT_FOUND',
|
||||
SERVERLESS_FUNCTION_VERSION_NOT_FOUND = 'SERVERLESS_FUNCTION_VERSION_NOT_FOUND',
|
||||
SERVERLESS_FUNCTION_ALREADY_EXIST = 'SERVERLESS_FUNCTION_ALREADY_EXIST',
|
||||
SERVERLESS_FUNCTION_NOT_READY = 'SERVERLESS_FUNCTION_NOT_READY',
|
||||
SERVERLESS_FUNCTION_BUILDING = 'SERVERLESS_FUNCTION_BUILDING',
|
||||
SERVERLESS_FUNCTION_CODE_UNCHANGED = 'SERVERLESS_FUNCTION_CODE_UNCHANGED',
|
||||
SERVERLESS_FUNCTION_EXECUTION_LIMIT_REACHED = 'SERVERLESS_FUNCTION_EXECUTION_LIMIT_REACHED',
|
||||
SERVERLESS_FUNCTION_CREATE_FAILED = 'SERVERLESS_FUNCTION_CREATE_FAILED',
|
||||
SERVERLESS_FUNCTION_EXECUTION_TIMEOUT = 'SERVERLESS_FUNCTION_EXECUTION_TIMEOUT',
|
||||
SERVERLESS_FUNCTION_DISABLED = 'SERVERLESS_FUNCTION_DISABLED',
|
||||
}
|
||||
|
||||
const getServerlessFunctionExceptionUserFriendlyMessage = (
|
||||
code: ServerlessFunctionExceptionCode,
|
||||
) => {
|
||||
switch (code) {
|
||||
case ServerlessFunctionExceptionCode.SERVERLESS_FUNCTION_NOT_FOUND:
|
||||
return msg`Function not found.`;
|
||||
case ServerlessFunctionExceptionCode.SERVERLESS_FUNCTION_VERSION_NOT_FOUND:
|
||||
return msg`Function version not found.`;
|
||||
case ServerlessFunctionExceptionCode.SERVERLESS_FUNCTION_ALREADY_EXIST:
|
||||
return msg`A function with this name already exists.`;
|
||||
case ServerlessFunctionExceptionCode.SERVERLESS_FUNCTION_NOT_READY:
|
||||
return msg`Function is not ready.`;
|
||||
case ServerlessFunctionExceptionCode.SERVERLESS_FUNCTION_BUILDING:
|
||||
return msg`Function is currently building.`;
|
||||
case ServerlessFunctionExceptionCode.SERVERLESS_FUNCTION_CODE_UNCHANGED:
|
||||
return msg`Function code is unchanged.`;
|
||||
case ServerlessFunctionExceptionCode.SERVERLESS_FUNCTION_EXECUTION_LIMIT_REACHED:
|
||||
return msg`Function execution limit reached.`;
|
||||
case ServerlessFunctionExceptionCode.SERVERLESS_FUNCTION_CREATE_FAILED:
|
||||
return msg`Failed to create function.`;
|
||||
case ServerlessFunctionExceptionCode.SERVERLESS_FUNCTION_EXECUTION_TIMEOUT:
|
||||
return msg`Function execution timed out.`;
|
||||
case ServerlessFunctionExceptionCode.SERVERLESS_FUNCTION_DISABLED:
|
||||
return msg`Serverless function execution is disabled.`;
|
||||
default:
|
||||
assertUnreachable(code);
|
||||
}
|
||||
};
|
||||
|
||||
export class ServerlessFunctionException extends CustomException<ServerlessFunctionExceptionCode> {
|
||||
constructor(
|
||||
message: string,
|
||||
code: ServerlessFunctionExceptionCode,
|
||||
{ userFriendlyMessage }: { userFriendlyMessage?: MessageDescriptor } = {},
|
||||
) {
|
||||
super(message, code, {
|
||||
userFriendlyMessage:
|
||||
userFriendlyMessage ??
|
||||
getServerlessFunctionExceptionUserFriendlyMessage(code),
|
||||
});
|
||||
}
|
||||
}
|
||||
-283
@@ -1,283 +0,0 @@
|
||||
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 { CreateServerlessFunctionInput } from 'src/engine/metadata-modules/serverless-function/dtos/create-serverless-function.input';
|
||||
import { ExecuteServerlessFunctionInput } from 'src/engine/metadata-modules/serverless-function/dtos/execute-serverless-function.input';
|
||||
import { GetServerlessFunctionSourceCodeInput } from 'src/engine/metadata-modules/serverless-function/dtos/get-serverless-function-source-code.input';
|
||||
import { PublishServerlessFunctionInput } from 'src/engine/metadata-modules/serverless-function/dtos/publish-serverless-function.input';
|
||||
import { ServerlessFunctionExecutionResultDTO } from 'src/engine/metadata-modules/serverless-function/dtos/serverless-function-execution-result.dto';
|
||||
import { ServerlessFunctionIdInput } from 'src/engine/metadata-modules/serverless-function/dtos/serverless-function-id.input';
|
||||
import { ServerlessFunctionLogsDTO } from 'src/engine/metadata-modules/serverless-function/dtos/serverless-function-logs.dto';
|
||||
import { ServerlessFunctionLogsInput } from 'src/engine/metadata-modules/serverless-function/dtos/serverless-function-logs.input';
|
||||
import { ServerlessFunctionDTO } from 'src/engine/metadata-modules/serverless-function/dtos/serverless-function.dto';
|
||||
import { UpdateServerlessFunctionInput } from 'src/engine/metadata-modules/serverless-function/dtos/update-serverless-function.input';
|
||||
import { ServerlessFunctionService } from 'src/engine/metadata-modules/serverless-function/serverless-function.service';
|
||||
import { FlatServerlessFunction } from 'src/engine/metadata-modules/serverless-function/types/flat-serverless-function.type';
|
||||
import { findFlatServerlessFunctionOrThrow } from 'src/engine/metadata-modules/serverless-function/utils/find-flat-serverless-function-or-throw.util';
|
||||
import { fromFlatServerlessFunctionToServerlessFunctionDto } from 'src/engine/metadata-modules/serverless-function/utils/from-flat-serverless-function-to-serverless-function-dto.util';
|
||||
import { serverlessFunctionGraphQLApiExceptionHandler } from 'src/engine/metadata-modules/serverless-function/utils/serverless-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 ServerlessFunctionResolver {
|
||||
constructor(
|
||||
private readonly serverlessFunctionService: ServerlessFunctionService,
|
||||
private readonly subscriptionService: SubscriptionService,
|
||||
private readonly flatEntityMapsCacheService: WorkspaceManyOrAllFlatEntityMapsCacheService,
|
||||
) {}
|
||||
|
||||
@Query(() => ServerlessFunctionDTO)
|
||||
async findOneServerlessFunction(
|
||||
@Args('input') { id }: ServerlessFunctionIdInput,
|
||||
@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
|
||||
): Promise<ServerlessFunctionDTO> {
|
||||
try {
|
||||
const { flatServerlessFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatServerlessFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
const flatServerlessFunction = findFlatServerlessFunctionOrThrow({
|
||||
id,
|
||||
flatServerlessFunctionMaps,
|
||||
});
|
||||
|
||||
return fromFlatServerlessFunctionToServerlessFunctionDto({
|
||||
flatServerlessFunction,
|
||||
});
|
||||
} catch (error) {
|
||||
return serverlessFunctionGraphQLApiExceptionHandler(error);
|
||||
}
|
||||
}
|
||||
|
||||
@Query(() => [ServerlessFunctionDTO])
|
||||
async findManyServerlessFunctions(
|
||||
@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
|
||||
): Promise<ServerlessFunctionDTO[]> {
|
||||
try {
|
||||
const { flatServerlessFunctionMaps } =
|
||||
await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
|
||||
{
|
||||
workspaceId,
|
||||
flatMapsKeys: ['flatServerlessFunctionMaps'],
|
||||
},
|
||||
);
|
||||
|
||||
return Object.values(flatServerlessFunctionMaps.byId)
|
||||
.filter(
|
||||
(
|
||||
flatServerlessFunction,
|
||||
): flatServerlessFunction is FlatServerlessFunction =>
|
||||
isDefined(flatServerlessFunction) &&
|
||||
!isDefined(flatServerlessFunction.deletedAt),
|
||||
)
|
||||
.map((flatServerlessFunction) =>
|
||||
fromFlatServerlessFunctionToServerlessFunctionDto({
|
||||
flatServerlessFunction,
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
return serverlessFunctionGraphQLApiExceptionHandler(error);
|
||||
}
|
||||
}
|
||||
|
||||
@Query(() => graphqlTypeJson)
|
||||
async getAvailablePackages(@Args('input') { id }: ServerlessFunctionIdInput) {
|
||||
try {
|
||||
return await this.serverlessFunctionService.getAvailablePackages(id);
|
||||
} catch (error) {
|
||||
return serverlessFunctionGraphQLApiExceptionHandler(error);
|
||||
}
|
||||
}
|
||||
|
||||
@Query(() => graphqlTypeJson, { nullable: true })
|
||||
async getServerlessFunctionSourceCode(
|
||||
@Args('input') input: GetServerlessFunctionSourceCodeInput,
|
||||
@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
|
||||
) {
|
||||
try {
|
||||
return await this.serverlessFunctionService.getServerlessFunctionSourceCode(
|
||||
workspaceId,
|
||||
input.id,
|
||||
input.version,
|
||||
);
|
||||
} catch (error) {
|
||||
return serverlessFunctionGraphQLApiExceptionHandler(error);
|
||||
}
|
||||
}
|
||||
|
||||
@Mutation(() => ServerlessFunctionDTO)
|
||||
@UseGuards(SettingsPermissionGuard(PermissionFlagType.WORKFLOWS))
|
||||
async deleteOneServerlessFunction(
|
||||
@Args('input') input: ServerlessFunctionIdInput,
|
||||
@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
|
||||
): Promise<ServerlessFunctionDTO> {
|
||||
try {
|
||||
const flatServerlessFunction =
|
||||
await this.serverlessFunctionService.deleteOneServerlessFunction({
|
||||
id: input.id,
|
||||
workspaceId,
|
||||
});
|
||||
|
||||
return fromFlatServerlessFunctionToServerlessFunctionDto({
|
||||
flatServerlessFunction,
|
||||
});
|
||||
} catch (error) {
|
||||
return serverlessFunctionGraphQLApiExceptionHandler(error);
|
||||
}
|
||||
}
|
||||
|
||||
@Mutation(() => ServerlessFunctionDTO)
|
||||
@UseGuards(SettingsPermissionGuard(PermissionFlagType.WORKFLOWS))
|
||||
async updateOneServerlessFunction(
|
||||
@Args('input')
|
||||
input: UpdateServerlessFunctionInput,
|
||||
@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
|
||||
): Promise<ServerlessFunctionDTO> {
|
||||
try {
|
||||
const flatServerlessFunction =
|
||||
await this.serverlessFunctionService.updateOneServerlessFunction(
|
||||
input,
|
||||
workspaceId,
|
||||
);
|
||||
|
||||
return fromFlatServerlessFunctionToServerlessFunctionDto({
|
||||
flatServerlessFunction,
|
||||
});
|
||||
} catch (error) {
|
||||
return serverlessFunctionGraphQLApiExceptionHandler(error);
|
||||
}
|
||||
}
|
||||
|
||||
@Mutation(() => ServerlessFunctionDTO)
|
||||
@UseGuards(SettingsPermissionGuard(PermissionFlagType.WORKFLOWS))
|
||||
async createOneServerlessFunction(
|
||||
@Args('input')
|
||||
input: CreateServerlessFunctionInput,
|
||||
@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
|
||||
): Promise<ServerlessFunctionDTO> {
|
||||
try {
|
||||
const flatServerlessFunction =
|
||||
await this.serverlessFunctionService.createOneServerlessFunction(
|
||||
input,
|
||||
workspaceId,
|
||||
);
|
||||
|
||||
return fromFlatServerlessFunctionToServerlessFunctionDto({
|
||||
flatServerlessFunction,
|
||||
});
|
||||
} catch (error) {
|
||||
return serverlessFunctionGraphQLApiExceptionHandler(error);
|
||||
}
|
||||
}
|
||||
|
||||
@Mutation(() => ServerlessFunctionExecutionResultDTO)
|
||||
@UseGuards(SettingsPermissionGuard(PermissionFlagType.WORKFLOWS))
|
||||
async executeOneServerlessFunction(
|
||||
@Args('input') input: ExecuteServerlessFunctionInput,
|
||||
@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
|
||||
) {
|
||||
try {
|
||||
const { id, payload, version } = input;
|
||||
|
||||
return await this.serverlessFunctionService.executeOneServerlessFunction({
|
||||
id,
|
||||
workspaceId,
|
||||
payload,
|
||||
version,
|
||||
});
|
||||
} catch (error) {
|
||||
return serverlessFunctionGraphQLApiExceptionHandler(error);
|
||||
}
|
||||
}
|
||||
|
||||
@Mutation(() => ServerlessFunctionDTO)
|
||||
@UseGuards(SettingsPermissionGuard(PermissionFlagType.WORKFLOWS))
|
||||
async publishServerlessFunction(
|
||||
@Args('input') input: PublishServerlessFunctionInput,
|
||||
@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
|
||||
): Promise<ServerlessFunctionDTO> {
|
||||
try {
|
||||
const { id } = input;
|
||||
|
||||
const flatServerlessFunction =
|
||||
await this.serverlessFunctionService.publishOneServerlessFunctionOrFail(
|
||||
id,
|
||||
workspaceId,
|
||||
);
|
||||
|
||||
return fromFlatServerlessFunctionToServerlessFunctionDto({
|
||||
flatServerlessFunction,
|
||||
});
|
||||
} catch (error) {
|
||||
return serverlessFunctionGraphQLApiExceptionHandler(error);
|
||||
}
|
||||
}
|
||||
|
||||
@Subscription(() => ServerlessFunctionLogsDTO, {
|
||||
filter: (
|
||||
payload: { serverlessFunctionLogs: ServerlessFunctionLogsDTO },
|
||||
variables: { input: ServerlessFunctionLogsInput },
|
||||
) => {
|
||||
const { serverlessFunctionLogs } = payload;
|
||||
const {
|
||||
id,
|
||||
universalIdentifier,
|
||||
applicationId,
|
||||
applicationUniversalIdentifier,
|
||||
name,
|
||||
} = serverlessFunctionLogs;
|
||||
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)
|
||||
);
|
||||
},
|
||||
})
|
||||
serverlessFunctionLogs(
|
||||
@Args('input') _: ServerlessFunctionLogsInput,
|
||||
@AuthWorkspace() workspace: WorkspaceEntity,
|
||||
) {
|
||||
return this.subscriptionService.subscribe({
|
||||
channel: SubscriptionChannel.SERVERLESS_FUNCTION_LOGS_CHANNEL,
|
||||
workspaceId: workspace.id,
|
||||
});
|
||||
}
|
||||
}
|
||||
-52
@@ -1,52 +0,0 @@
|
||||
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 { ServerlessFunctionEntity } from 'src/engine/metadata-modules/serverless-function/serverless-function.entity';
|
||||
import { FlatServerlessFunction } from 'src/engine/metadata-modules/serverless-function/types/flat-serverless-function.type';
|
||||
import { fromServerlessFunctionEntityToFlatServerlessFunction } from 'src/engine/metadata-modules/serverless-function/utils/from-serverless-function-entity-to-flat-serverless-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('flatServerlessFunctionMaps')
|
||||
export class WorkspaceFlatServerlessFunctionMapCacheService extends WorkspaceCacheProvider<
|
||||
FlatEntityMaps<FlatServerlessFunction>
|
||||
> {
|
||||
constructor(
|
||||
@InjectRepository(ServerlessFunctionEntity)
|
||||
private readonly serverlessFunctionRepository: Repository<ServerlessFunctionEntity>,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async computeForCache(
|
||||
workspaceId: string,
|
||||
): Promise<FlatEntityMaps<FlatServerlessFunction>> {
|
||||
const serverlessFunctions = await this.serverlessFunctionRepository.find({
|
||||
where: { workspaceId },
|
||||
withDeleted: true,
|
||||
});
|
||||
|
||||
const flatServerlessFunctionMaps = createEmptyFlatEntityMaps();
|
||||
|
||||
for (const serverlessFunctionEntity of serverlessFunctions) {
|
||||
const flatServerlessFunction =
|
||||
fromServerlessFunctionEntityToFlatServerlessFunction(
|
||||
serverlessFunctionEntity,
|
||||
);
|
||||
|
||||
addFlatEntityToFlatEntityMapsThroughMutationOrThrow({
|
||||
flatEntity: flatServerlessFunction,
|
||||
flatEntityMapsToMutate: flatServerlessFunctionMaps,
|
||||
});
|
||||
}
|
||||
|
||||
return flatServerlessFunctionMaps;
|
||||
}
|
||||
}
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
import { type Sources } from 'twenty-shared/types';
|
||||
|
||||
import { type FlatEntityFrom } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-from.type';
|
||||
import { type ServerlessFunctionEntity } from 'src/engine/metadata-modules/serverless-function/serverless-function.entity';
|
||||
|
||||
export type FlatServerlessFunction =
|
||||
FlatEntityFrom<ServerlessFunctionEntity> & {
|
||||
code?: Sources;
|
||||
};
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
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 {
|
||||
ServerlessFunctionException,
|
||||
ServerlessFunctionExceptionCode,
|
||||
} from 'src/engine/metadata-modules/serverless-function/serverless-function.exception';
|
||||
|
||||
export const findFlatServerlessFunctionOrThrow = ({
|
||||
flatServerlessFunctionMaps,
|
||||
id,
|
||||
}: {
|
||||
flatServerlessFunctionMaps: MetadataFlatEntityMaps<'serverlessFunction'>;
|
||||
id: string;
|
||||
}) => {
|
||||
const flatServerlessFunction = findFlatEntityByIdInFlatEntityMaps({
|
||||
flatEntityId: id,
|
||||
flatEntityMaps: flatServerlessFunctionMaps,
|
||||
});
|
||||
|
||||
if (
|
||||
!isDefined(flatServerlessFunction) ||
|
||||
isDefined(flatServerlessFunction.deletedAt)
|
||||
) {
|
||||
throw new ServerlessFunctionException(
|
||||
`Serverless function with id ${id} not found`,
|
||||
ServerlessFunctionExceptionCode.SERVERLESS_FUNCTION_NOT_FOUND,
|
||||
);
|
||||
}
|
||||
|
||||
return flatServerlessFunction;
|
||||
};
|
||||
-76
@@ -1,76 +0,0 @@
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
import { v4 } from 'uuid';
|
||||
|
||||
import { DEFAULT_TOOL_INPUT_SCHEMA } from 'src/engine/metadata-modules/serverless-function/constants/default-tool-input-schema.constant';
|
||||
import { type CreateServerlessFunctionInput } from 'src/engine/metadata-modules/serverless-function/dtos/create-serverless-function.input';
|
||||
import {
|
||||
DEFAULT_BUILT_HANDLER_PATH,
|
||||
DEFAULT_HANDLER_NAME,
|
||||
DEFAULT_SOURCE_HANDLER_PATH,
|
||||
ServerlessFunctionRuntime,
|
||||
} from 'src/engine/metadata-modules/serverless-function/serverless-function.entity';
|
||||
import { type FlatServerlessFunction } from 'src/engine/metadata-modules/serverless-function/types/flat-serverless-function.type';
|
||||
import { serverlessFunctionCreateHash } from 'src/engine/metadata-modules/serverless-function/utils/serverless-function-create-hash.utils';
|
||||
|
||||
export type FromCreateServerlessFunctionInputToFlatServerlessFunctionArgs = {
|
||||
createServerlessFunctionInput: CreateServerlessFunctionInput & {
|
||||
serverlessFunctionLayerId: string;
|
||||
};
|
||||
workspaceId: string;
|
||||
workspaceCustomApplicationId: string;
|
||||
};
|
||||
|
||||
export const fromCreateServerlessFunctionInputToFlatServerlessFunction = ({
|
||||
createServerlessFunctionInput: rawCreateServerlessFunctionInput,
|
||||
workspaceId,
|
||||
workspaceCustomApplicationId,
|
||||
}: FromCreateServerlessFunctionInputToFlatServerlessFunctionArgs): FlatServerlessFunction => {
|
||||
const id = v4();
|
||||
const currentDate = new Date();
|
||||
|
||||
return {
|
||||
id,
|
||||
cronTriggerSettings: null,
|
||||
databaseEventTriggerSettings: null,
|
||||
httpRouteTriggerSettings: null,
|
||||
name: rawCreateServerlessFunctionInput.name,
|
||||
description: rawCreateServerlessFunctionInput.description ?? null,
|
||||
sourceHandlerPath:
|
||||
rawCreateServerlessFunctionInput.sourceHandlerPath ??
|
||||
DEFAULT_SOURCE_HANDLER_PATH,
|
||||
handlerName:
|
||||
rawCreateServerlessFunctionInput.handlerName ?? DEFAULT_HANDLER_NAME,
|
||||
builtHandlerPath:
|
||||
rawCreateServerlessFunctionInput.builtHandlerPath ??
|
||||
DEFAULT_BUILT_HANDLER_PATH,
|
||||
universalIdentifier:
|
||||
rawCreateServerlessFunctionInput.universalIdentifier ?? v4(),
|
||||
createdAt: currentDate.toISOString(),
|
||||
updatedAt: currentDate.toISOString(),
|
||||
deletedAt: null,
|
||||
latestVersion: null,
|
||||
publishedVersions: [],
|
||||
applicationId: workspaceCustomApplicationId,
|
||||
runtime: ServerlessFunctionRuntime.NODE22,
|
||||
timeoutSeconds: rawCreateServerlessFunctionInput.timeoutSeconds ?? 300,
|
||||
serverlessFunctionLayerId:
|
||||
rawCreateServerlessFunctionInput.serverlessFunctionLayerId,
|
||||
workspaceId,
|
||||
code: rawCreateServerlessFunctionInput?.code,
|
||||
checksum: rawCreateServerlessFunctionInput?.code
|
||||
? serverlessFunctionCreateHash(
|
||||
JSON.stringify(rawCreateServerlessFunctionInput.code),
|
||||
)
|
||||
: null,
|
||||
// If no schema provided and no code provided, use default schema
|
||||
// (because the default template will be used)
|
||||
toolInputSchema: isDefined(
|
||||
rawCreateServerlessFunctionInput?.toolInputSchema,
|
||||
)
|
||||
? rawCreateServerlessFunctionInput.toolInputSchema
|
||||
: !isDefined(rawCreateServerlessFunctionInput?.code)
|
||||
? DEFAULT_TOOL_INPUT_SCHEMA
|
||||
: null,
|
||||
isTool: rawCreateServerlessFunctionInput?.isTool ?? false,
|
||||
};
|
||||
};
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
import { type ServerlessFunctionDTO } from 'src/engine/metadata-modules/serverless-function/dtos/serverless-function.dto';
|
||||
import { type FlatServerlessFunction } from 'src/engine/metadata-modules/serverless-function/types/flat-serverless-function.type';
|
||||
|
||||
export const fromFlatServerlessFunctionToServerlessFunctionDto = ({
|
||||
flatServerlessFunction,
|
||||
}: {
|
||||
flatServerlessFunction: FlatServerlessFunction;
|
||||
}): ServerlessFunctionDTO => {
|
||||
return {
|
||||
id: flatServerlessFunction.id,
|
||||
name: flatServerlessFunction.name,
|
||||
description: flatServerlessFunction.description ?? undefined,
|
||||
runtime: flatServerlessFunction.runtime,
|
||||
timeoutSeconds: flatServerlessFunction.timeoutSeconds,
|
||||
latestVersion: flatServerlessFunction.latestVersion ?? undefined,
|
||||
sourceHandlerPath: flatServerlessFunction.sourceHandlerPath,
|
||||
builtHandlerPath: flatServerlessFunction.builtHandlerPath,
|
||||
handlerName: flatServerlessFunction.handlerName,
|
||||
publishedVersions: flatServerlessFunction.publishedVersions,
|
||||
toolInputSchema: flatServerlessFunction.toolInputSchema ?? undefined,
|
||||
isTool: flatServerlessFunction.isTool,
|
||||
applicationId: flatServerlessFunction.applicationId ?? undefined,
|
||||
workspaceId: flatServerlessFunction.workspaceId,
|
||||
createdAt: new Date(flatServerlessFunction.createdAt),
|
||||
updatedAt: new Date(flatServerlessFunction.updatedAt),
|
||||
cronTriggerSettings:
|
||||
flatServerlessFunction.cronTriggerSettings ?? undefined,
|
||||
databaseEventTriggerSettings:
|
||||
flatServerlessFunction.databaseEventTriggerSettings ?? undefined,
|
||||
httpRouteTriggerSettings:
|
||||
flatServerlessFunction.httpRouteTriggerSettings ?? undefined,
|
||||
};
|
||||
};
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
import { removePropertiesFromRecord } from 'twenty-shared/utils';
|
||||
|
||||
import { type ServerlessFunctionEntity } from 'src/engine/metadata-modules/serverless-function/serverless-function.entity';
|
||||
import { type FlatServerlessFunction } from 'src/engine/metadata-modules/serverless-function/types/flat-serverless-function.type';
|
||||
|
||||
export const fromServerlessFunctionEntityToFlatServerlessFunction = (
|
||||
serverlessFunctionEntity: ServerlessFunctionEntity,
|
||||
): FlatServerlessFunction => {
|
||||
const serverlessFunctionWithoutRelations = removePropertiesFromRecord(
|
||||
serverlessFunctionEntity,
|
||||
['serverlessFunctionLayer', 'application'],
|
||||
);
|
||||
|
||||
return {
|
||||
...serverlessFunctionWithoutRelations,
|
||||
createdAt: serverlessFunctionEntity.createdAt.toISOString(),
|
||||
updatedAt: serverlessFunctionEntity.updatedAt.toISOString(),
|
||||
deletedAt: serverlessFunctionEntity.deletedAt?.toISOString() ?? null,
|
||||
universalIdentifier: serverlessFunctionEntity.universalIdentifier,
|
||||
};
|
||||
};
|
||||
-51
@@ -1,51 +0,0 @@
|
||||
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_SERVERLESS_FUNCTION_EDITABLE_PROPERTIES } from 'src/engine/metadata-modules/serverless-function/constants/flat-serverless-function-editable-properties.constant';
|
||||
import { type UpdateServerlessFunctionInput } from 'src/engine/metadata-modules/serverless-function/dtos/update-serverless-function.input';
|
||||
import { type FlatServerlessFunction } from 'src/engine/metadata-modules/serverless-function/types/flat-serverless-function.type';
|
||||
import { findFlatServerlessFunctionOrThrow } from 'src/engine/metadata-modules/serverless-function/utils/find-flat-serverless-function-or-throw.util';
|
||||
import { serverlessFunctionCreateHash } from 'src/engine/metadata-modules/serverless-function/utils/serverless-function-create-hash.utils';
|
||||
import { mergeUpdateInExistingRecord } from 'src/utils/merge-update-in-existing-record.util';
|
||||
|
||||
export const fromUpdateServerlessFunctionInputToFlatServerlessFunctionToUpdateOrThrow =
|
||||
({
|
||||
updateServerlessFunctionInput: rawUpdateServerlessFunctionInput,
|
||||
flatServerlessFunctionMaps,
|
||||
}: {
|
||||
updateServerlessFunctionInput: UpdateServerlessFunctionInput;
|
||||
flatServerlessFunctionMaps: MetadataFlatEntityMaps<'serverlessFunction'>;
|
||||
}): FlatServerlessFunction => {
|
||||
const { id: serverlessFunctionToUpdateId } =
|
||||
trimAndRemoveDuplicatedWhitespacesFromObjectStringProperties(
|
||||
rawUpdateServerlessFunctionInput,
|
||||
['id'],
|
||||
);
|
||||
|
||||
const existingFlatServerlessFunctionToUpdate =
|
||||
findFlatServerlessFunctionOrThrow({
|
||||
id: serverlessFunctionToUpdateId,
|
||||
flatServerlessFunctionMaps,
|
||||
});
|
||||
const updatedEditableFieldProperties = {
|
||||
...extractAndSanitizeObjectStringFields(
|
||||
{
|
||||
...rawUpdateServerlessFunctionInput.update,
|
||||
checksum: serverlessFunctionCreateHash(
|
||||
JSON.stringify(rawUpdateServerlessFunctionInput.update.code),
|
||||
),
|
||||
},
|
||||
FLAT_SERVERLESS_FUNCTION_EDITABLE_PROPERTIES,
|
||||
),
|
||||
code: rawUpdateServerlessFunctionInput.update.code,
|
||||
};
|
||||
|
||||
return mergeUpdateInExistingRecord({
|
||||
existing: existingFlatServerlessFunctionToUpdate,
|
||||
properties: FLAT_SERVERLESS_FUNCTION_EDITABLE_PROPERTIES,
|
||||
update: updatedEditableFieldProperties,
|
||||
});
|
||||
};
|
||||
-40
@@ -1,40 +0,0 @@
|
||||
import { assertUnreachable } from 'twenty-shared/utils';
|
||||
|
||||
import {
|
||||
ConflictError,
|
||||
ForbiddenError,
|
||||
NotFoundError,
|
||||
TimeoutError,
|
||||
} from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
|
||||
import {
|
||||
ServerlessFunctionException,
|
||||
ServerlessFunctionExceptionCode,
|
||||
} from 'src/engine/metadata-modules/serverless-function/serverless-function.exception';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export const serverlessFunctionGraphQLApiExceptionHandler = (error: any) => {
|
||||
if (error instanceof ServerlessFunctionException) {
|
||||
switch (error.code) {
|
||||
case ServerlessFunctionExceptionCode.SERVERLESS_FUNCTION_NOT_FOUND:
|
||||
case ServerlessFunctionExceptionCode.SERVERLESS_FUNCTION_VERSION_NOT_FOUND:
|
||||
throw new NotFoundError(error);
|
||||
case ServerlessFunctionExceptionCode.SERVERLESS_FUNCTION_ALREADY_EXIST:
|
||||
throw new ConflictError(error);
|
||||
case ServerlessFunctionExceptionCode.SERVERLESS_FUNCTION_NOT_READY:
|
||||
case ServerlessFunctionExceptionCode.SERVERLESS_FUNCTION_BUILDING:
|
||||
case ServerlessFunctionExceptionCode.SERVERLESS_FUNCTION_EXECUTION_LIMIT_REACHED:
|
||||
throw new ForbiddenError(error);
|
||||
case ServerlessFunctionExceptionCode.SERVERLESS_FUNCTION_EXECUTION_TIMEOUT:
|
||||
throw new TimeoutError(error);
|
||||
case ServerlessFunctionExceptionCode.SERVERLESS_FUNCTION_CODE_UNCHANGED:
|
||||
case ServerlessFunctionExceptionCode.SERVERLESS_FUNCTION_CREATE_FAILED:
|
||||
throw error;
|
||||
case ServerlessFunctionExceptionCode.SERVERLESS_FUNCTION_DISABLED:
|
||||
throw new ForbiddenError(error);
|
||||
default: {
|
||||
return assertUnreachable(error.code);
|
||||
}
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
};
|
||||
Reference in New Issue
Block a user