-
Notifications
You must be signed in to change notification settings - Fork 297
Expand file tree
/
Copy pathdynamic-integrations.controller.ts
More file actions
525 lines (464 loc) · 16.3 KB
/
dynamic-integrations.controller.ts
File metadata and controls
525 lines (464 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
import {
Controller,
Get,
Post,
Put,
Patch,
Delete,
Body,
Param,
HttpException,
HttpStatus,
Logger,
UseGuards,
} from '@nestjs/common';
import type { Prisma } from '@prisma/client';
import { db } from '@db';
import { InternalTokenGuard } from '../../auth/internal-token.guard';
import { DynamicIntegrationRepository } from '../repositories/dynamic-integration.repository';
import { DynamicCheckRepository } from '../repositories/dynamic-check.repository';
import { ProviderRepository } from '../repositories/provider.repository';
import { CheckRunRepository } from '../repositories/check-run.repository';
import { DynamicManifestLoaderService } from '../services/dynamic-manifest-loader.service';
import {
validateIntegrationDefinition,
SyncDefinitionSchema,
} from '@trycompai/integration-platform';
@Controller({ path: 'internal/dynamic-integrations', version: '1' })
@UseGuards(InternalTokenGuard)
export class DynamicIntegrationsController {
private readonly logger = new Logger(DynamicIntegrationsController.name);
constructor(
private readonly dynamicIntegrationRepo: DynamicIntegrationRepository,
private readonly dynamicCheckRepo: DynamicCheckRepository,
private readonly providerRepo: ProviderRepository,
private readonly checkRunRepo: CheckRunRepository,
private readonly loaderService: DynamicManifestLoaderService,
) {}
/**
* Upsert a dynamic integration with checks from a full definition.
* Creates if new, updates if exists. This is the primary endpoint for AI agents.
*/
@Put()
async upsert(@Body() body: Record<string, unknown>) {
const validation = validateIntegrationDefinition(body);
if (!validation.success) {
throw new HttpException(
{ message: 'Invalid integration definition', errors: validation.errors },
HttpStatus.BAD_REQUEST,
);
}
const def = validation.data!;
// Validate and store syncDefinition through Zod to apply defaults (e.g., employeesPath)
const rawSyncDef = (body as Record<string, unknown>).syncDefinition;
const validatedSyncDef = rawSyncDef
? SyncDefinitionSchema.parse(rawSyncDef)
: undefined;
// Upsert the integration
const integration = await this.dynamicIntegrationRepo.upsertBySlug({
slug: def.slug,
name: def.name,
description: def.description,
category: def.category,
logoUrl: def.logoUrl,
docsUrl: def.docsUrl,
baseUrl: def.baseUrl,
defaultHeaders: def.defaultHeaders as unknown as Prisma.InputJsonValue,
authConfig: def.authConfig as unknown as Prisma.InputJsonValue,
capabilities: def.capabilities as unknown as Prisma.InputJsonValue,
supportsMultipleConnections: def.supportsMultipleConnections,
syncDefinition: validatedSyncDef
? (JSON.parse(JSON.stringify(validatedSyncDef)) as Prisma.InputJsonValue)
: null,
});
// Delete checks not in the new definition, then upsert the rest
const existingChecks = await this.dynamicCheckRepo.findByIntegrationId(integration.id);
const newCheckSlugs = new Set(def.checks.map((c) => c.checkSlug));
for (const existing of existingChecks) {
if (!newCheckSlugs.has(existing.checkSlug)) {
await this.dynamicCheckRepo.delete(existing.id);
}
}
for (const [index, check] of def.checks.entries()) {
await this.dynamicCheckRepo.upsert({
integrationId: integration.id,
checkSlug: check.checkSlug,
name: check.name,
description: check.description,
taskMapping: check.taskMapping,
defaultSeverity: check.defaultSeverity,
definition: check.definition as unknown as Prisma.InputJsonValue,
variables: (check.variables ?? []) as unknown as Prisma.InputJsonValue,
isEnabled: check.isEnabled ?? true,
sortOrder: check.sortOrder ?? index,
});
}
// Upsert IntegrationProvider row
await this.providerRepo.upsert({
slug: def.slug,
name: def.name,
category: def.category,
capabilities: (def.capabilities as unknown as string[]) ?? ['checks'],
isActive: true,
});
// Refresh registry
await this.loaderService.invalidateCache();
this.logger.log(`Upserted dynamic integration: ${def.slug} with ${def.checks.length} checks`);
return {
success: true,
id: integration.id,
slug: integration.slug,
checksCount: def.checks.length,
};
}
/**
* Create a dynamic integration with checks from a full definition.
*/
@Post()
async create(@Body() body: Record<string, unknown>) {
const validation = validateIntegrationDefinition(body);
if (!validation.success) {
throw new HttpException(
{ message: 'Invalid integration definition', errors: validation.errors },
HttpStatus.BAD_REQUEST,
);
}
const def = validation.data!;
const existing = await this.dynamicIntegrationRepo.findBySlug(def.slug);
if (existing) {
throw new HttpException(
`Integration with slug "${def.slug}" already exists. Use PUT to upsert.`,
HttpStatus.CONFLICT,
);
}
const rawSyncDefCreate = (body as Record<string, unknown>).syncDefinition;
const validatedSyncDefCreate = rawSyncDefCreate
? SyncDefinitionSchema.parse(rawSyncDefCreate)
: undefined;
const integration = await this.dynamicIntegrationRepo.create({
slug: def.slug,
name: def.name,
description: def.description,
category: def.category,
logoUrl: def.logoUrl,
docsUrl: def.docsUrl,
baseUrl: def.baseUrl,
defaultHeaders: def.defaultHeaders as unknown as Prisma.InputJsonValue,
authConfig: def.authConfig as unknown as Prisma.InputJsonValue,
capabilities: def.capabilities as unknown as Prisma.InputJsonValue,
supportsMultipleConnections: def.supportsMultipleConnections,
syncDefinition: validatedSyncDefCreate
? (JSON.parse(JSON.stringify(validatedSyncDefCreate)) as Prisma.InputJsonValue)
: undefined,
});
for (const [index, check] of def.checks.entries()) {
await this.dynamicCheckRepo.create({
integrationId: integration.id,
checkSlug: check.checkSlug,
name: check.name,
description: check.description,
taskMapping: check.taskMapping,
defaultSeverity: check.defaultSeverity,
definition: check.definition as unknown as Prisma.InputJsonValue,
variables: (check.variables ?? []) as unknown as Prisma.InputJsonValue,
isEnabled: check.isEnabled ?? true,
sortOrder: check.sortOrder ?? index,
});
}
// Create provider row and refresh registry
await this.providerRepo.upsert({
slug: def.slug,
name: def.name,
category: def.category,
capabilities: (def.capabilities as unknown as string[]) ?? ['checks'],
isActive: true,
});
await this.loaderService.invalidateCache();
this.logger.log(`Created dynamic integration: ${def.slug} with ${def.checks.length} checks`);
return { success: true, id: integration.id, slug: integration.slug };
}
/**
* List all dynamic integrations.
*/
@Get()
async list() {
const integrations = await this.dynamicIntegrationRepo.findAll();
return integrations.map((i) => ({
id: i.id,
slug: i.slug,
name: i.name,
description: i.description,
category: i.category,
isActive: i.isActive,
checksCount: i.checks.length,
createdAt: i.createdAt,
updatedAt: i.updatedAt,
}));
}
/**
* Get details of a dynamic integration with all checks.
*/
@Get(':id')
async getById(@Param('id') id: string) {
const integration = await this.dynamicIntegrationRepo.findById(id);
if (!integration) {
throw new HttpException('Dynamic integration not found', HttpStatus.NOT_FOUND);
}
return integration;
}
/**
* Update manifest fields of a dynamic integration.
*/
@Patch(':id')
async update(@Param('id') id: string, @Body() body: Record<string, unknown>) {
const existing = await this.dynamicIntegrationRepo.findById(id);
if (!existing) {
throw new HttpException('Dynamic integration not found', HttpStatus.NOT_FOUND);
}
await this.dynamicIntegrationRepo.update(id, body);
await this.loaderService.invalidateCache();
return { success: true };
}
/**
* Delete a dynamic integration (cascades to checks).
*/
@Delete(':id')
async remove(@Param('id') id: string) {
const existing = await this.dynamicIntegrationRepo.findById(id);
if (!existing) {
throw new HttpException('Dynamic integration not found', HttpStatus.NOT_FOUND);
}
await this.dynamicIntegrationRepo.delete(id);
await this.loaderService.invalidateCache();
this.logger.log(`Deleted dynamic integration: ${existing.slug}`);
return { success: true };
}
// ==================== Check Management ====================
/**
* Add a check to a dynamic integration.
*/
@Post(':id/checks')
async addCheck(
@Param('id') id: string,
@Body() body: Record<string, unknown>,
) {
const integration = await this.dynamicIntegrationRepo.findById(id);
if (!integration) {
throw new HttpException('Dynamic integration not found', HttpStatus.NOT_FOUND);
}
const check = await this.dynamicCheckRepo.create({
integrationId: id,
checkSlug: body.checkSlug as string,
name: body.name as string,
description: body.description as string,
taskMapping: body.taskMapping as string | undefined,
defaultSeverity: body.defaultSeverity as string | undefined,
definition: body.definition as Prisma.InputJsonValue,
variables: body.variables as Prisma.InputJsonValue | undefined,
isEnabled: (body.isEnabled as boolean) ?? true,
sortOrder: (body.sortOrder as number) ?? 0,
});
await this.loaderService.invalidateCache();
return { success: true, id: check.id };
}
/**
* Update a check.
*/
@Patch(':id/checks/:checkId')
async updateCheck(
@Param('id') id: string,
@Param('checkId') checkId: string,
@Body() body: Record<string, unknown>,
) {
const check = await this.dynamicCheckRepo.findById(checkId);
if (!check || check.integrationId !== id) {
throw new HttpException('Check not found', HttpStatus.NOT_FOUND);
}
await this.dynamicCheckRepo.update(checkId, body);
await this.loaderService.invalidateCache();
return { success: true };
}
/**
* Delete a check.
*/
@Delete(':id/checks/:checkId')
async removeCheck(
@Param('id') id: string,
@Param('checkId') checkId: string,
) {
const check = await this.dynamicCheckRepo.findById(checkId);
if (!check || check.integrationId !== id) {
throw new HttpException('Check not found', HttpStatus.NOT_FOUND);
}
await this.dynamicCheckRepo.delete(checkId);
await this.loaderService.invalidateCache();
return { success: true };
}
// ==================== Activation ====================
/**
* Activate a dynamic integration.
*/
@Post(':id/activate')
async activate(@Param('id') id: string) {
const integration = await this.dynamicIntegrationRepo.findById(id);
if (!integration) {
throw new HttpException('Dynamic integration not found', HttpStatus.NOT_FOUND);
}
for (const check of integration.checks) {
if (!check.definition || typeof check.definition !== 'object') {
throw new HttpException(
`Check "${check.checkSlug}" has invalid definition`,
HttpStatus.BAD_REQUEST,
);
}
}
await this.providerRepo.upsert({
slug: integration.slug,
name: integration.name,
category: integration.category,
capabilities: (integration.capabilities as unknown as string[]) ?? ['checks'],
isActive: true,
});
await this.dynamicIntegrationRepo.update(id, { isActive: true });
await this.loaderService.invalidateCache();
this.logger.log(`Activated dynamic integration: ${integration.slug}`);
return { success: true };
}
/**
* Deactivate a dynamic integration.
*/
@Post(':id/deactivate')
async deactivate(@Param('id') id: string) {
const integration = await this.dynamicIntegrationRepo.findById(id);
if (!integration) {
throw new HttpException('Dynamic integration not found', HttpStatus.NOT_FOUND);
}
await this.dynamicIntegrationRepo.update(id, { isActive: false });
await this.loaderService.invalidateCache();
this.logger.log(`Deactivated dynamic integration: ${integration.slug}`);
return { success: true };
}
// ==================== Agent Debugging Endpoints ====================
/**
* Validate a definition without saving.
* Agents use this to check syntax/structure before committing.
*/
@Post('validate')
async validate(@Body() body: Record<string, unknown>) {
const result = validateIntegrationDefinition(body);
if (!result.success) {
return {
valid: false,
errors: result.errors,
};
}
// validateIntegrationDefinition validates everything via Zod:
// the manifest fields, all check definitions, and syncDefinition.
// If we got here, the entire definition is valid.
const definition = result.data!;
return {
valid: true,
summary: {
slug: definition.slug,
name: definition.name,
category: definition.category,
capabilities: definition.capabilities,
checksCount: definition.checks.length,
checkSlugs: definition.checks.map((c) => c.checkSlug),
hasSyncDefinition: !!(body as Record<string, unknown>).syncDefinition,
},
};
}
/**
* Get recent check run history for a dynamic integration.
* Agents use this to debug failing checks — includes full logs and results.
*/
@Get(':id/check-runs')
async getCheckRuns(@Param('id') id: string) {
const integration = await this.dynamicIntegrationRepo.findById(id);
if (!integration) {
throw new HttpException('Dynamic integration not found', HttpStatus.NOT_FOUND);
}
// Find all connections for this provider
const connections = await db.integrationConnection.findMany({
where: {
provider: { slug: integration.slug },
status: 'active',
},
select: { id: true, organizationId: true },
});
if (connections.length === 0) {
return { runs: [], total: 0 };
}
// Get recent runs across all connections
const runs = await db.integrationCheckRun.findMany({
where: {
connectionId: { in: connections.map((c) => c.id) },
},
include: {
results: {
select: {
id: true,
passed: true,
title: true,
resourceType: true,
resourceId: true,
severity: true,
remediation: true,
},
},
},
orderBy: { createdAt: 'desc' },
take: 20,
});
return {
runs: runs.map((run) => ({
id: run.id,
checkId: run.checkId,
checkName: run.checkName,
connectionId: run.connectionId,
status: run.status,
startedAt: run.startedAt,
completedAt: run.completedAt,
durationMs: run.durationMs,
totalChecked: run.totalChecked,
passedCount: run.passedCount,
failedCount: run.failedCount,
errorMessage: run.errorMessage,
logs: run.logs,
results: run.results,
})),
total: runs.length,
};
}
/**
* Get a single check run with full details (logs, results, error info).
* Agents use this to debug a specific failed run.
*/
@Get('check-runs/:runId')
async getCheckRunById(@Param('runId') runId: string) {
const run = await this.checkRunRepo.findById(runId);
if (!run) {
throw new HttpException('Check run not found', HttpStatus.NOT_FOUND);
}
return {
id: run.id,
checkId: run.checkId,
checkName: run.checkName,
connectionId: run.connectionId,
status: run.status,
startedAt: run.startedAt,
completedAt: run.completedAt,
durationMs: run.durationMs,
totalChecked: run.totalChecked,
passedCount: run.passedCount,
failedCount: run.failedCount,
errorMessage: run.errorMessage,
logs: run.logs,
results: run.results,
provider: run.connection?.provider
? { slug: run.connection.provider.slug, name: run.connection.provider.name }
: null,
};
}
}