mirror of
https://github.com/twentyhq/twenty.git
synced 2026-06-12 09:57:03 -04:00
## Introduction
That's an audit + RFC
## Fire-and-forget (`void`) -- Intentional, correct
These are telemetry, metrics, and audit logging in hot paths or
non-critical contexts. `void` is the right choice.
| File | What was voided |
|---|---|
| `sign-in-up.service.ts` | `metricsService.incrementCounter` (sign-up
metric) + `auditService.insertWorkspaceEvent` (workspace created) |
| `use-graphql-error-handler.hook.ts` | 5x
`metricsService.incrementCounter` (GraphQL operation metrics) |
| `bullmq.driver.ts` | 2x `metricsService.incrementCounter` (job
completed/failed metrics) |
| `call-webhook.job.ts` | 2x `auditService.insertWorkspaceEvent` + 1x
`metricsService.incrementCounter` |
| `custom-domain-manager.service.ts` | `analytics.insertWorkspaceEvent`
(domain activation event) |
| `logic-function-executor.service.ts` |
`auditService.insertWorkspaceEvent` (function execution) |
| `workflow-runner.workspace-service.ts` |
`metricsService.incrementCounter` (throttle metric) |
| `cleaner.workspace-service.ts` | `metricsService.incrementCounter`
(deleted workspace metric) |
| `stream-agent-chat.job.ts` | Detached IIFE for streaming chunks
(intentional concurrent pipeline) |
| `workspace-auth-context.middleware.ts` |
`withWorkspaceAuthContext(...)` (AsyncLocalStorage, returns void anyway)
|
## Top-level script entry points (`void bootstrap()`)
These are module-level calls where the promise has no consumer. `void`
makes the lint rule happy and documents the intent.
| File | What changed |
|---|---|
| `main.ts` | `void bootstrap()` |
| `command.ts` | `void bootstrap()` |
| `queue-worker.ts` | `void bootstrap()` |
| `truncate-db.ts` | `void dropSchemasSequentially()` |
| `codegen/index.ts` | `void generateTests(forceArg)` |
## Now properly awaited -- Real bug fixes
These were floating promises that could silently fail, lose data, or
cause race conditions.
| File | What was fixed |
|---|---|
| `billing-sync-plans-data.command.ts` | `meters.map(async ...)` wrapped
in `Promise.all` -- was returning before upserts finished |
| `cache-storage.service.ts` | `setAdd` and `setPop` had `.then()`
chains that weren't returned/awaited |
| `create-audit-log-from-internal-event.ts` | 4x
`auditService.createObjectEvent` now awaited inside a job |
| `cleaner.workspace-service.ts` | 2x `emailService.send(...)` now
awaited -- emails could silently fail |
| `agent-async-executor.service.ts` | `calculateAndBillUsage` +
`billNativeWebSearchUsage` in `finally` block now awaited |
| `repair-tool-call.util.ts` | `calculateAndBillUsage` now awaited |
| `agent-title-generation.service.ts` | `calculateAndBillUsage` now
awaited |
| `chat-execution.service.ts` | `billNativeWebSearchUsage` now awaited |
| `ai-generate-text.controller.ts` | `calculateAndBillUsage` in
`finally` block now awaited |
| `agent-turn.resolver.ts` | `messageQueueService.add(...)` now awaited
|
| `command.ts` | `app.close()` now awaited (was exiting before graceful
shutdown) |
| `i18n.service.ts` | `loadTranslations()` in `onModuleInit` now awaited
|
| `workspace-query-hook.explorer.ts` | `explore()` in `onModuleInit` now
awaited |
| `message-queue.explorer.ts` | `handleProcessorGroupCollection` in
`onModuleInit` now awaited |
| `ai-billing.service.spec.ts` | Test now properly `await`s the async
call |
| `messaging-messages-import.service.spec.ts` | `expect(...)` now
properly `await`ed for async assertion |
| `archive.finalize()` (3 files) | Voided -- promise resolution already
handled by `pipeline()` / `on('end')` |
## Impersonation & security audit trail -- Upgraded from `void` to
`await`
These were previously fire-and-forget but are
security/compliance-critical events that must be reliably persisted.
| File | What was fixed |
|---|---|
| `impersonation.service.ts` | 4x `auditService.insertWorkspaceEvent`
now awaited (impersonation attempt, token generation
attempt/success/failure) |
| `auth.resolver.ts` | 5x `auditService.insertWorkspaceEvent` now
awaited (impersonation token exchange attempt/success/failure at server
and workspace levels) |
| `auth.service.ts` | 2x `analytics.insertWorkspaceEvent` now awaited
(impersonation attempted/issued) |
## Billing audit -- Upgraded from `void` to `await`
Payment events should be reliably persisted for financial/compliance
reporting.
| File | What was fixed |
|---|---|
| `billing-webhook-invoice.service.ts` |
`auditService.insertWorkspaceEvent(PAYMENT_RECEIVED_EVENT)` now awaited
inside Stripe webhook handler |
## Fire-and-forget with proper error handling -- Upgraded from bare
`void`
These remain non-blocking but now catch and log errors instead of
risking unhandled rejections.
| File | What was fixed |
|---|---|
| `logic-function-executor.service.ts` |
`applicationLogsService.writeLogs` now uses `.catch()` instead of bare
`void` -- user-facing logs should surface errors |
## Systemic infrastructure fixes
| File | What was fixed |
|---|---|
| `metrics.service.ts` | `incrementCounter`: Redis cache write
(`metricsCacheService.updateCounter`) now uses `.catch()` internally
instead of raw `await` -- prevents unhandled rejections across all `void
metricsService.incrementCounter(...)` call sites when Redis is unhealthy
|
| `audit.service.ts` | `preventIfDisabled`: made properly `async` with
`await` and consistent `Promise<{ success: boolean }>` return type.
Removed broken `catch` that returned an `AuditException` as a value
(wrong constructor args, unreachable dead code). Removed unused
`AuditException` import |
## Fixed in this session (beyond original PR)
| File | What changed |
|---|---|
| `telemetry.listener.ts` | Removed misleading `Promise.all` + `void`
combo; replaced with simple `for...of` + `void` |
| `message-queue.explorer.ts` | Changed from `void` to `await` so
startup crashes on registration failure |
216 lines
5.9 KiB
TypeScript
216 lines
5.9 KiB
TypeScript
import * as fs from 'fs';
|
|
import * as path from 'path';
|
|
import * as process from 'process';
|
|
|
|
import { pascalToKebab } from 'twenty-shared/utils';
|
|
|
|
import { INTROSPECTION_QUERY } from './introspection-query';
|
|
import {
|
|
type Field,
|
|
type InputValue,
|
|
type IntrospectionResponse,
|
|
type TypeRef,
|
|
} from './introspection.interface';
|
|
|
|
const GRAPHQL_URL = 'http://localhost:3000/graphql';
|
|
const BEARER_TOKEN =
|
|
'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIyMDIwMjAyMC05ZTNiLTQ2ZDQtYTU1Ni04OGI5ZGRjMmIwMzQiLCJ3b3Jrc3BhY2VJZCI6IjIwMjAyMDIwLTFjMjUtNGQwMi1iZjI1LTZhZWNjZjdlYTQxOSIsIndvcmtzcGFjZU1lbWJlcklkIjoiMjAyMDIwMjAtMDY4Ny00YzQxLWI3MDctZWQxYmZjYTk3MmE3IiwiaWF0IjoxNzI2NDkyNTAyLCJleHAiOjEzMjQ1MDE2NTAyfQ.zM6TbfeOqYVH5Sgryc2zf02hd9uqUOSL1-iJlMgwzsI';
|
|
const TEST_OUTPUT_DIR = './test/integration/graphql/suites/object-generated';
|
|
|
|
const fetchGraphQLSchema = async (): Promise<IntrospectionResponse> => {
|
|
const headers = {
|
|
Authorization: BEARER_TOKEN,
|
|
'Content-Type': 'application/json',
|
|
};
|
|
const response = await fetch(GRAPHQL_URL, {
|
|
method: 'POST',
|
|
headers,
|
|
body: JSON.stringify({ query: INTROSPECTION_QUERY }),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error(`Failed to fetch schema: ${response.statusText}`);
|
|
}
|
|
|
|
return response.json();
|
|
};
|
|
|
|
const unwrapType = (typeInfo: TypeRef): any => {
|
|
while (typeInfo.ofType) {
|
|
typeInfo = typeInfo.ofType;
|
|
}
|
|
|
|
return typeInfo;
|
|
};
|
|
|
|
const hasRequiredArgs = (args: InputValue[]): boolean => {
|
|
return args.some((arg) => unwrapType(arg.type).kind === 'NON_NULL');
|
|
};
|
|
|
|
const generateTestContent = (
|
|
queryName: string,
|
|
fields: Field[],
|
|
): string | null => {
|
|
const fieldNames = fields
|
|
.filter((f) => ['SCALAR', 'ENUM'].includes(unwrapType(f.type).kind))
|
|
.map((f) => f.name);
|
|
|
|
if (fieldNames.length === 0) {
|
|
// oxlint-disable-next-line no-console
|
|
console.log(`Skipping ${queryName}: No usable fields found.`);
|
|
|
|
return null;
|
|
}
|
|
|
|
const fieldSelection = fieldNames.join('\n ');
|
|
const expectSelection = fieldNames
|
|
.map((f) => `expect(${queryName}).toHaveProperty('${f}');`)
|
|
.join('\n ');
|
|
|
|
return `import request from 'supertest';
|
|
|
|
const client = request(\`http://localhost:\${APP_PORT}\`);
|
|
|
|
describe('${queryName}Resolver (e2e)', () => {
|
|
it('should find many ${queryName}', () => {
|
|
const queryData = {
|
|
query: \`
|
|
query ${queryName} {
|
|
${queryName} {
|
|
edges {
|
|
node {
|
|
${fieldSelection}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
\`,
|
|
};
|
|
|
|
return client
|
|
.post('/graphql')
|
|
.set('Authorization', \`Bearer \${APPLE_JANE_ADMIN_ACCESS_TOKEN}\`)
|
|
.send(queryData)
|
|
.expect(200)
|
|
.expect((res) => {
|
|
expect(res.body.data).toBeDefined();
|
|
expect(res.body.errors).toBeUndefined();
|
|
})
|
|
.expect((res) => {
|
|
const data = res.body.data.${queryName};
|
|
|
|
expect(data).toBeDefined();
|
|
expect(Array.isArray(data.edges)).toBe(true);
|
|
|
|
const edges = data.edges;
|
|
|
|
if (edges.length > 0) {
|
|
const ${queryName} = edges[0].node;
|
|
|
|
${expectSelection}
|
|
}
|
|
});
|
|
});
|
|
});
|
|
`;
|
|
};
|
|
|
|
const writeTestFile = (
|
|
queryName: string,
|
|
content: string | null,
|
|
force = false,
|
|
): string => {
|
|
if (!content) return 'skipped';
|
|
|
|
const fileName = `${pascalToKebab(queryName)}.integration-spec.ts`;
|
|
const filePath = path.join(TEST_OUTPUT_DIR, fileName);
|
|
|
|
if (fs.existsSync(filePath) && !force) {
|
|
return 'skipped';
|
|
}
|
|
|
|
fs.writeFileSync(filePath, content);
|
|
|
|
return force ? 'updated' : 'created';
|
|
};
|
|
|
|
const generateTests = async (force = false) => {
|
|
fs.mkdirSync(TEST_OUTPUT_DIR, { recursive: true });
|
|
const schemaData = await fetchGraphQLSchema();
|
|
const types = schemaData.data.__schema.types;
|
|
|
|
const queryTypeName = schemaData.data.__schema.queryType.name;
|
|
const queryType = types.find((t: any) => t.name === queryTypeName);
|
|
|
|
let createdCount = 0;
|
|
let updatedCount = 0;
|
|
let totalCount = 0;
|
|
|
|
if (!queryType?.fields) {
|
|
// oxlint-disable-next-line no-console
|
|
console.log('No query fields found.');
|
|
|
|
return;
|
|
}
|
|
|
|
for (const query of queryType.fields) {
|
|
const queryName = query.name;
|
|
|
|
if (hasRequiredArgs(query.args)) continue;
|
|
if (queryName.includes('Duplicates')) continue;
|
|
|
|
const queryReturnType = unwrapType(query.type);
|
|
|
|
if (
|
|
queryReturnType.kind === 'OBJECT' &&
|
|
queryReturnType.name.includes('Connection')
|
|
) {
|
|
totalCount++;
|
|
const connectionTypeInfo = types.find(
|
|
(f: any) => f.name === queryReturnType.name,
|
|
);
|
|
const edgeTypeInfo = connectionTypeInfo?.fields?.find(
|
|
(f: any) => f.name === 'edges',
|
|
);
|
|
|
|
if (edgeTypeInfo) {
|
|
const returnType = unwrapType(edgeTypeInfo.type);
|
|
const returnTypeInfo = types.find(
|
|
(t: any) => t.name === returnType.name,
|
|
);
|
|
const returnNodeTypeInfo = returnTypeInfo?.fields?.find(
|
|
(f: any) => f.name === 'node',
|
|
);
|
|
|
|
if (returnNodeTypeInfo) {
|
|
const nodeType = unwrapType(returnNodeTypeInfo.type);
|
|
const nodeTypeInfo = types.find((t: any) => t.name === nodeType.name);
|
|
|
|
if (!nodeTypeInfo?.fields) {
|
|
continue;
|
|
}
|
|
|
|
const content = generateTestContent(queryName, nodeTypeInfo?.fields);
|
|
const result = writeTestFile(queryName, content, force);
|
|
|
|
if (result === 'created') createdCount++;
|
|
if (result === 'updated') updatedCount++;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// oxlint-disable-next-line no-console
|
|
console.log(`Number of tests created: ${createdCount}/${totalCount}`);
|
|
if (force) {
|
|
// oxlint-disable-next-line no-console
|
|
console.log(`Number of tests updated: ${updatedCount}/${totalCount}`);
|
|
}
|
|
};
|
|
|
|
// Basic command-line argument parsing
|
|
const forceArg = process.argv.includes('--force');
|
|
|
|
// Call the function with the parsed argument
|
|
void generateTests(forceArg);
|