1751 extensibility twenty sdk v2 use twenty sdk to define a serverless function trigger (#15347)

This PR adds 2 columns handlerPath and handlerName in serverlessFunction
to locate the entrypoint of a serverless in a codebase

It adds the following decorators in twenty-sdk:
- ServerlessFunction
- DatabaseEventTrigger
- RouteTrigger
- CronTrigger
- ApplicationVariable

It still supports deprecated entity.manifest.jsonc 

Overall code needs to be cleaned a little bit, but it should work
properly so you can try to test if the DEVX fits your needs

See updates in hello-world application

```typescript
import axios from 'axios';
import {
  DatabaseEventTrigger,
  ServerlessFunction,
  RouteTrigger,
  CronTrigger,
  ApplicationVariable,
} from 'twenty-sdk';

@ApplicationVariable({
  universalIdentifier: 'dedc53eb-9c12-4fe2-ba86-4a2add19d305',
  key: 'TWENTY_API_KEY',
  description: 'Twenty API Key',
  isSecret: true,
})
@DatabaseEventTrigger({
  universalIdentifier: '203f1df3-4a82-4d06-a001-b8cf22a31156',
  eventName: 'person.created',
})
@RouteTrigger({
  universalIdentifier: 'c9f84c8d-b26d-40d1-95dd-4f834ae5a2c6',
  path: '/post-card/create',
  httpMethod: 'GET',
  isAuthRequired: false,
})
@CronTrigger({
  universalIdentifier: 'dd802808-0695-49e1-98c9-d5c9e2704ce2',
  pattern: '0 0 1 1 *', // Every year 1st of January
})
@ServerlessFunction({
  universalIdentifier: 'e56d363b-0bdc-4d8a-a393-6f0d1c75bdcf',
})
class CreateNewPostCard {
  main = async (params: { recipient: string }): Promise<string> => {
    const { recipient } = params;

    const options = {
      method: 'POST',
      url: 'http://localhost:3000/rest/postCards',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${process.env.TWENTY_API_KEY}`,
      },
      data: { name: recipient ?? 'Unknown' },
    };

    try {
      const { data } = await axios.request(options);

      console.log(`New post card to "${recipient}" created`);

      return data;
    } catch (error) {
      console.error(error);
      throw error;
    }
  };
}

export const createNewPostCardHandler = new CreateNewPostCard().main;

```


### [edit] V2 

After the v1 proposal, I see that using a class method to define the
serverless function handler is pretty confusing. Lets leave
serverlessFunction configuration decorators on the class, but move the
handler like before. Here is the v2 hello-world serverless function:

```typescript
import axios from 'axios';
import {
  DatabaseEventTrigger,
  ServerlessFunction,
  RouteTrigger,
  CronTrigger,
  ApplicationVariable,
} from 'twenty-sdk';

@ApplicationVariable({
  universalIdentifier: 'dedc53eb-9c12-4fe2-ba86-4a2add19d305',
  key: 'TWENTY_API_KEY',
  description: 'Twenty API Key',
  isSecret: true,
})
@DatabaseEventTrigger({
  universalIdentifier: '203f1df3-4a82-4d06-a001-b8cf22a31156',
  eventName: 'person.created',
})
@RouteTrigger({
  universalIdentifier: 'c9f84c8d-b26d-40d1-95dd-4f834ae5a2c6',
  path: '/post-card/create',
  httpMethod: 'GET',
  isAuthRequired: false,
})
@CronTrigger({
  universalIdentifier: 'dd802808-0695-49e1-98c9-d5c9e2704ce2',
  pattern: '0 0 1 1 *', // Every year 1st of January
})
@ServerlessFunction({
  universalIdentifier: 'e56d363b-0bdc-4d8a-a393-6f0d1c75bdcf',
})
export class ServerlessFunctionDefinition {}

export const main = async (params: { recipient: string }): Promise<string> => {
  const { recipient } = params;

  const options = {
    method: 'POST',
    url: 'http://localhost:3000/rest/postCards',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${process.env.TWENTY_API_KEY}`,
    },
    data: { name: recipient ?? 'Unknown' },
  };

  try {
    const { data } = await axios.request(options);

    console.log(`New post card to "${recipient}" created`);

    return data;
  } catch (error) {
    console.error(error);
    throw error;
  }
};

```


### [edit] V3

After the v2 proposal, we don't really like decorators on empty classes.
We decided to go with a Vercel approach with a config constant

```typescript
import axios from 'axios';
import { ServerlessFunctionConfig } from 'twenty-sdk';

export const main = async (params: { recipient: string }): Promise<string> => {
  const { recipient } = params;

  const options = {
    method: 'POST',
    url: 'http://localhost:3000/rest/postCards',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${process.env.TWENTY_API_KEY}`,
    },
    data: { name: recipient ?? 'Unknown' },
  };

  try {
    const { data } = await axios.request(options);

    console.log(`New post card to "${recipient}" created`);

    return data;
  } catch (error) {
    console.error(error);
    throw error;
  }
};

export const config: ServerlessFunctionConfig = {
  universalIdentifier: 'e56d363b-0bdc-4d8a-a393-6f0d1c75bdcf',
  routeTriggers: [
  {
    universalIdentifier: 'c9f84c8d-b26d-40d1-95dd-4f834ae5a2c6',
    path: '/post-card/create',
    httpMethod: 'GET',
    isAuthRequired: false,
  }
  ],
  cronTriggers: [
    {
      universalIdentifier: 'dd802808-0695-49e1-98c9-d5c9e2704ce2',
      pattern: '0 0 1 1 *', // Every year 1st of January
    }
  ],
  databaseEventTriggers: [
  {
    universalIdentifier: '203f1df3-4a82-4d06-a001-b8cf22a31156',
    eventName: 'person.created',
   }
  ]
}

```
This commit is contained in:
martmull
2025-10-29 16:51:43 +00:00
committed by GitHub
parent 75ed5cb3a2
commit a6cc80eedd
81 changed files with 2070 additions and 1044 deletions
@@ -6,4 +6,6 @@ export const FLAT_SERVERLESS_FUNCTION_EDITABLE_PROPERTIES = [
'timeoutSeconds',
'checksum',
'code',
'handlerPath',
'handlerName',
] as const satisfies (keyof FlatServerlessFunction)[];
@@ -11,7 +11,7 @@ import {
} from 'class-validator';
import graphqlTypeJson from 'graphql-type-json';
import { ServerlessFunctionCode } from 'src/engine/metadata-modules/serverless-function/types/serverless-function-code.type';
import { Sources } from 'src/engine/core-modules/file-storage/types/source.type';
@InputType()
export class CreateServerlessFunctionInput {
@@ -44,5 +44,5 @@ export class CreateServerlessFunctionInput {
@Field(() => graphqlTypeJson, { nullable: true })
@IsObject()
@IsOptional()
code?: ServerlessFunctionCode;
code?: Sources;
}
@@ -57,6 +57,14 @@ export class ServerlessFunctionDTO {
@Field({ nullable: true })
latestVersion?: string;
@IsString()
@Field()
handlerPath: string;
@IsString()
@Field()
handlerName: string;
@IsArray()
@Field(() => [String], { nullable: false })
publishedVersions: string[];
@@ -15,13 +15,14 @@ import {
import graphqlTypeJson from 'graphql-type-json';
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
import { ServerlessFunctionCode } from 'src/engine/metadata-modules/serverless-function/types/serverless-function-code.type';
import type { Sources } from 'src/engine/core-modules/file-storage/types/source.type';
@InputType()
class UpdateServerlessFunctionInputUpdates {
@IsString()
@Field()
name: string;
@IsOptional()
name?: string;
@IsString()
@Field({ nullable: true })
@@ -37,7 +38,17 @@ class UpdateServerlessFunctionInputUpdates {
@Field(() => graphqlTypeJson)
@IsObject()
code: ServerlessFunctionCode;
code: Sources;
@IsString()
@Field({ nullable: true })
@IsOptional()
handlerName?: string;
@IsString()
@Field({ nullable: true })
@IsOptional()
handlerPath?: string;
}
@InputType()
@@ -28,6 +28,9 @@ export enum ServerlessFunctionRuntime {
NODE22 = 'nodejs22.x',
}
export const DEFAULT_HANDLER_PATH = 'src/index.ts';
export const DEFAULT_HANDLER_NAME = 'main';
export const SERVERLESS_FUNCTION_ENTITY_RELATION_PROPERTIES = [
'cronTriggers',
'databaseEventTriggers',
@@ -46,6 +49,12 @@ export class ServerlessFunctionEntity
@Column({ nullable: false })
name: string;
@Column({ nullable: false, default: DEFAULT_HANDLER_PATH })
handlerPath: string;
@Column({ nullable: false, default: DEFAULT_HANDLER_NAME })
handlerName: string;
@Column({ nullable: true, type: 'varchar' })
description: string | null;
@@ -5,8 +5,8 @@ import { type FlatEntityFrom } from 'src/engine/metadata-modules/flat-entity/typ
import { type RouteTriggerEntity } from 'src/engine/metadata-modules/route-trigger/route-trigger.entity';
import { type ServerlessFunctionLayerEntity } from 'src/engine/metadata-modules/serverless-function-layer/serverless-function-layer.entity';
import { type ServerlessFunctionEntity } from 'src/engine/metadata-modules/serverless-function/serverless-function.entity';
import { type ServerlessFunctionCode } from 'src/engine/metadata-modules/serverless-function/types/serverless-function-code.type';
import { type ExtractRecordTypeOrmRelationProperties } from 'src/engine/workspace-manager/workspace-migration-v2/types/extract-record-typeorm-relation-properties.type';
import { type Sources } from 'src/engine/core-modules/file-storage/types/source.type';
export type ServerlessFunctionEntityRelationProperties =
ExtractRecordTypeOrmRelationProperties<
@@ -22,5 +22,5 @@ export type FlatServerlessFunction = FlatEntityFrom<
ServerlessFunctionEntity,
ServerlessFunctionEntityRelationProperties
> & {
code?: ServerlessFunctionCode;
code?: Sources;
};
@@ -1,7 +0,0 @@
import { type Sources } from 'src/engine/core-modules/file-storage/types/source.type';
export type ServerlessFunctionCode = {
src: {
'index.ts': string;
} & Sources;
};
@@ -1,7 +1,11 @@
import { v4 } from 'uuid';
import { type CreateServerlessFunctionInput } from 'src/engine/metadata-modules/serverless-function/dtos/create-serverless-function.input';
import { ServerlessFunctionRuntime } from 'src/engine/metadata-modules/serverless-function/serverless-function.entity';
import {
DEFAULT_HANDLER_NAME,
DEFAULT_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';
@@ -23,6 +27,8 @@ export const fromCreateServerlessFunctionInputToFlatServerlessFunction = ({
id,
name: rawCreateServerlessFunctionInput.name,
description: rawCreateServerlessFunctionInput.description ?? null,
handlerPath: DEFAULT_HANDLER_PATH,
handlerName: DEFAULT_HANDLER_NAME,
universalIdentifier:
rawCreateServerlessFunctionInput.universalIdentifier ?? v4(),
createdAt: currentDate,
@@ -1,20 +0,0 @@
import { isDefined } from 'twenty-shared/utils';
import { serverlessFunctionCreateHash } from 'src/engine/metadata-modules/serverless-function/utils/serverless-function-create-hash.utils';
import { type ServerlessFunctionCode } from 'src/engine/metadata-modules/serverless-function/types/serverless-function-code.type';
export const serverlessFunctionCreateCodeChecksum = (
code: ServerlessFunctionCode,
): string => {
if (!isDefined(code) || typeof code !== 'object') {
return serverlessFunctionCreateHash('');
}
const codeObj = code as unknown as Record<string, string>;
const sortedKeys = Object.keys(codeObj).sort();
const concatenatedContent = sortedKeys
.map((key) => `${key}:${codeObj[key]}`)
.join('|');
return serverlessFunctionCreateHash(concatenatedContent);
};