Skip to content

The open alternative to Salesforce, designed for AI.

Monitor server routes left unreachable by their owner workspace (#27513)

martmull653a8dcc2732
diff --git a/packages/twenty-server/src/engine/core-modules/server-route-trigger/server-route-reachability.service.ts b/packages/twenty-server/src/engine/core-modules/server-route-trigger/server-route-reachability.service.ts
new file mode 100644
index 00000000000..03cc872d831
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/server-route-trigger/server-route-reachability.service.ts
@@ -0,0 +1,75 @@
+import { Injectable } from '@nestjs/common';
+
+import { type UnreachableServerRouteRegistration } from 'src/engine/core-modules/server-route-trigger/types/unreachable-server-route-registration.type';
+import { LogicFunctionEntity } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
+import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
+import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
+
+@Injectable()
+export class ServerRouteReachabilityService {
+ constructor(
+ @InjectWorkspaceScopedRepository(LogicFunctionEntity)
+ private readonly logicFunctionRepository: WorkspaceScopedRepository<LogicFunctionEntity>,
+ ) {}
+
+ async findUnreachableServerRouteRegistrations(): Promise<
+ UnreachableServerRouteRegistration[]
+ > {
+ const rows = await this.logicFunctionRepository
+ .createQueryBuilder('logicFunction')
+ .innerJoin('logicFunction.application', 'application')
+ .innerJoin('application.workspace', 'workspace')
+ .innerJoin(
+ 'application.applicationRegistration',
+ 'applicationRegistration',
+ )
+ .select('applicationRegistration.id', 'applicationRegistrationId')
+ .addSelect(
+ 'applicationRegistration.universalIdentifier',
+ 'universalIdentifier',
+ )
+ .addSelect('applicationRegistration.name', 'name')
+ .addSelect(
+ 'COUNT(DISTINCT application.workspaceId)',
+ 'unreachableWorkspaceCount',
+ )
+ .where('logicFunction.serverRouteTriggerSettings IS NOT NULL')
+ .andWhere('logicFunction.deletedAt IS NULL')
+ .andWhere('application.deletedAt IS NULL')
+ .andWhere('workspace.deletedAt IS NULL')
+ .andWhere((queryBuilder) => {
+ const ownerResolverQuery = queryBuilder
+ .subQuery()
+ .select('1')
+ .from(LogicFunctionEntity, 'ownerResolver')
+ .innerJoin('ownerResolver.application', 'ownerApplication')
+ .where(
+ 'ownerApplication.applicationRegistrationId = applicationRegistration.id',
+ )
+ .andWhere(
+ 'ownerResolver.workspaceId = applicationRegistration.ownerWorkspaceId',
+ )
+ .andWhere(
+ 'ownerResolver.universalIdentifier = logicFunction.universalIdentifier',
+ )
+ .andWhere('ownerResolver.serverRouteTriggerSettings IS NOT NULL')
+ .andWhere('ownerResolver.deletedAt IS NULL')
+ .andWhere('ownerApplication.deletedAt IS NULL')
+ .getQuery();
+
+ return `NOT EXISTS ${ownerResolverQuery}`;
+ })
+ .groupBy('applicationRegistration.id')
+ .getRawMany<{
+ applicationRegistrationId: string;
+ universalIdentifier: string;
+ name: string;
+ unreachableWorkspaceCount: string;
+ }>();
+
+ return rows.map((row) => ({
+ ...row,
+ unreachableWorkspaceCount: Number(row.unreachableWorkspaceCount),
+ }));
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/server-route-trigger/server-route-trigger-gauge.service.ts b/packages/twenty-server/src/engine/core-modules/server-route-trigger/server-route-trigger-gauge.service.ts
new file mode 100644
index 00000000000..c9c28645ba6
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/server-route-trigger/server-route-trigger-gauge.service.ts
@@ -0,0 +1,35 @@
+import { Injectable, OnModuleInit } from '@nestjs/common';
+
+import { MetricsService } from 'src/engine/core-modules/metrics/metrics.service';
+import { ServerRouteReachabilityService } from 'src/engine/core-modules/server-route-trigger/server-route-reachability.service';
+
+@Injectable()
+export class ServerRouteTriggerGaugeService implements OnModuleInit {
+ constructor(
+ private readonly metricsService: MetricsService,
+ private readonly serverRouteReachabilityService: ServerRouteReachabilityService,
+ ) {}
+
+ onModuleInit() {
+ this.metricsService.createMultiObservableGauge({
+ metricName: 'twenty_app_server_route_unreachable_workspaces',
+ options: {
+ description:
+ 'Number of workspaces where an application exposes a server route that cannot be reached because its owner workspace does not serve it',
+ },
+ callback: async () => {
+ const unreachableRegistrations =
+ await this.serverRouteReachabilityService.findUnreachableServerRouteRegistrations();
+
+ return unreachableRegistrations.map((unreachableRegistration) => ({
+ value: unreachableRegistration.unreachableWorkspaceCount,
+ attributes: {
+ universal_identifier: unreachableRegistration.universalIdentifier,
+ app_name: unreachableRegistration.name,
+ },
+ }));
+ },
+ cacheValue: true,
+ });
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/server-route-trigger/server-route-trigger.module.ts b/packages/twenty-server/src/engine/core-modules/server-route-trigger/server-route-trigger.module.ts
index 7410421b866..f815ebd88b2 100644
--- a/packages/twenty-server/src/engine/core-modules/server-route-trigger/server-route-trigger.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/server-route-trigger/server-route-trigger.module.ts
@@ -1,17 +1,22 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
+import { MetricsModule } from 'src/engine/core-modules/metrics/metrics.module';
+import { ServerRouteReachabilityService } from 'src/engine/core-modules/server-route-trigger/server-route-reachability.service';
import { ServerRouteTriggerController } from 'src/engine/core-modules/server-route-trigger/server-route-trigger.controller';
+import { ServerRouteTriggerGaugeService } from 'src/engine/core-modules/server-route-trigger/server-route-trigger-gauge.service';
import { ServerRouteTriggerService } from 'src/engine/core-modules/server-route-trigger/server-route-trigger.service';
import { LogicFunctionEntity } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/provide-workspace-scoped-repository';
@Module({
- imports: [TypeOrmModule.forFeature([LogicFunctionEntity])],
+ imports: [TypeOrmModule.forFeature([LogicFunctionEntity]), MetricsModule],
controllers: [ServerRouteTriggerController],
providers: [
provideWorkspaceScopedRepository(LogicFunctionEntity),
ServerRouteTriggerService,
+ ServerRouteReachabilityService,
+ ServerRouteTriggerGaugeService,
],
})
export class ServerRouteTriggerModule {}
diff --git a/packages/twenty-server/src/engine/core-modules/server-route-trigger/types/unreachable-server-route-registration.type.ts b/packages/twenty-server/src/engine/core-modules/server-route-trigger/types/unreachable-server-route-registration.type.ts
new file mode 100644
index 00000000000..e737731ee5c
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/server-route-trigger/types/unreachable-server-route-registration.type.ts
@@ -0,0 +1,6 @@
+export type UnreachableServerRouteRegistration = {
+ applicationRegistrationId: string;
+ universalIdentifier: string;
+ name: string;
+ unreachableWorkspaceCount: number;
+};
diff --git a/packages/twenty-server/test/integration/server-route-trigger/suites/server-route-reachability.integration-spec.ts b/packages/twenty-server/test/integration/server-route-trigger/suites/server-route-reachability.integration-spec.ts
new file mode 100644
index 00000000000..50d07020884
--- /dev/null
+++ b/packages/twenty-server/test/integration/server-route-trigger/suites/server-route-reachability.integration-spec.ts
@@ -0,0 +1,138 @@
+import { transferApplicationRegistrationOwnership } from 'test/integration/metadata/suites/application-registration/utils/transfer-application-registration-ownership.util';
+import { buildBaseManifest } from 'test/integration/metadata/suites/application/utils/build-base-manifest.util';
+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
+import { setupApplicationForSync } from 'test/integration/metadata/suites/application/utils/setup-application-for-sync.util';
+import { syncApplication } from 'test/integration/metadata/suites/application/utils/sync-application.util';
+import {
+ removeApplicationInstallFromForeignWorkspace,
+ seedApplicationInstallInForeignWorkspace,
+} from 'test/integration/server-route-trigger/utils/seed-application-install-in-foreign-workspace.util';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { type LogicFunctionManifest } from 'twenty-shared/application';
+
+import { type ServerRouteReachabilityService } from 'src/engine/core-modules/server-route-trigger/server-route-reachability.service';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+
+const APP_UNIVERSAL_IDENTIFIER = '6e9c3a4b-1d5f-4c0a-8b4e-5f7a9b1c3d4e';
+const ROLE_UNIVERSAL_IDENTIFIER = '7f0d4b5c-2e6a-4d1b-9c5f-6a8b0c2d4e5f';
+const RESOLVER_UNIVERSAL_IDENTIFIER = '8a1e5c6d-3f7b-4e2c-8d6a-7b9c1d3e5f6a';
+const NEWER_RESOLVER_UNIVERSAL_IDENTIFIER =
+ '9b2f6d7e-4a8c-4f3d-9e7b-8c0d2e4f6a7b';
+
+const buildResolverManifest = (): LogicFunctionManifest => ({
+ universalIdentifier: RESOLVER_UNIVERSAL_IDENTIFIER,
+ name: 'reachability-resolver',
+ handlerName: 'main',
+ sourceHandlerPath: 'src/reachability-resolver.ts',
+ builtHandlerPath: 'dist/reachability-resolver.mjs',
+ builtHandlerChecksum: 'checksum-reachability-resolver',
+ serverRouteTriggerSettings: { forwardedRequestHeaders: [] },
+});
+
+const findUnreachableRegistration = async () => {
+ const unreachableRegistrations =
+ await getAppProviderByClassName<ServerRouteReachabilityService>(
+ 'ServerRouteReachabilityService',
+ ).findUnreachableServerRouteRegistrations();
+
+ return unreachableRegistrations.find(
+ (unreachableRegistration) =>
+ unreachableRegistration.universalIdentifier === APP_UNIVERSAL_IDENTIFIER,
+ );
+};
+
+const setOwnerWorkspaceId = (ownerWorkspaceId: string | null) =>
+ globalThis.testDataSource.query(
+ `UPDATE core."applicationRegistration" SET "workspaceId" = $1
+ WHERE "universalIdentifier" = $2`,
+ [ownerWorkspaceId, APP_UNIVERSAL_IDENTIFIER],
+ );
+
+describe('ServerRouteReachabilityService (integration)', () => {
+ let applicationRegistrationId: string;
+
+ beforeAll(async () => {
+ await setupApplicationForSync({
+ applicationUniversalIdentifier: APP_UNIVERSAL_IDENTIFIER,
+ name: 'Server Route Reachability App',
+ description: 'App exposing a server route from its owner workspace',
+ sourcePath: 'server-route-reachability-app',
+ });
+
+ await syncApplication({
+ manifest: buildBaseManifest({
+ appId: APP_UNIVERSAL_IDENTIFIER,
+ roleId: ROLE_UNIVERSAL_IDENTIFIER,
+ overrides: { logicFunctions: [buildResolverManifest()] },
+ }),
+ expectToFail: false,
+ });
+
+ [{ id: applicationRegistrationId }] = await globalThis.testDataSource.query(
+ `SELECT id FROM core."applicationRegistration" WHERE "universalIdentifier" = $1`,
+ [APP_UNIVERSAL_IDENTIFIER],
+ );
+ }, 60000);
+
+ afterEach(async () => {
+ await removeApplicationInstallFromForeignWorkspace({
+ applicationUniversalIdentifier: APP_UNIVERSAL_IDENTIFIER,
+ });
+ await setOwnerWorkspaceId(SEED_APPLE_WORKSPACE_ID);
+ });
+
+ afterAll(async () => {
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: APP_UNIVERSAL_IDENTIFIER,
+ });
+ }, 60000);
+
+ it('does not report a registration whose owner workspace serves its server route', async () => {
+ await seedApplicationInstallInForeignWorkspace({
+ applicationUniversalIdentifier: APP_UNIVERSAL_IDENTIFIER,
+ resolverUniversalIdentifier: RESOLVER_UNIVERSAL_IDENTIFIER,
+ });
+
+ expect(await findUnreachableRegistration()).toBeUndefined();
+ });
+
+ it('reports the workspaces relying on a route the owner workspace does not serve', async () => {
+ await seedApplicationInstallInForeignWorkspace({
+ applicationUniversalIdentifier: APP_UNIVERSAL_IDENTIFIER,
+ resolverUniversalIdentifier: NEWER_RESOLVER_UNIVERSAL_IDENTIFIER,
+ });
+
+ expect(await findUnreachableRegistration()).toEqual(
+ expect.objectContaining({
+ applicationRegistrationId,
+ unreachableWorkspaceCount: 1,
+ }),
+ );
+ });
+
+ it('reports the installed workspaces once ownership moves to a workspace without the application', async () => {
+ await transferApplicationRegistrationOwnership({
+ input: { applicationRegistrationId, targetWorkspaceSubdomain: 'yc' },
+ expectToFail: false,
+ });
+
+ expect(await findUnreachableRegistration()).toEqual(
+ expect.objectContaining({
+ applicationRegistrationId,
+ unreachableWorkspaceCount: 1,
+ }),
+ );
+ });
+
+ it('reports every installed workspace once the registration has no owner workspace', async () => {
+ await seedApplicationInstallInForeignWorkspace({
+ applicationUniversalIdentifier: APP_UNIVERSAL_IDENTIFIER,
+ resolverUniversalIdentifier: RESOLVER_UNIVERSAL_IDENTIFIER,
+ });
+ await setOwnerWorkspaceId(null);
+
+ expect(await findUnreachableRegistration()).toEqual(
+ expect.objectContaining({ unreachableWorkspaceCount: 2 }),
+ );
+ });
+});