This repository has been archived by the owner on Feb 5, 2025. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
378 lines (321 loc) · 13.9 KB
/
index.ts
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
import utils from '@eventcatalog/sdk';
import chalk from 'chalk';
import {
SchemasClient,
DescribeSchemaCommand,
ListSchemasCommand,
ExportSchemaCommand,
DescribeSchemaCommandOutput,
SchemaSummary,
} from '@aws-sdk/client-schemas';
import { EventCatalogConfig, Event, GeneratorProps, EventMap } from './types';
import { filterEvents } from './utils/filters';
import checkLicense from './checkLicense';
import { defaultMarkdown as generateMarkdownForService } from './utils/services';
import { defaultMarkdown as generateMarkdownForDomain } from './utils/domains';
import { defaultMarkdown as generateMarkdownForMessage, getBadgesForMessage } from './utils/messages';
import { generatedMarkdownByEventBus } from './utils/channel';
import { parse } from '@aws-sdk/util-arn-parser';
import { DescribeEventBusCommand, EventBridgeClient } from '@aws-sdk/client-eventbridge';
async function tryFetchJSONSchema(
schemasClient: SchemasClient,
registryName: string,
schemaName: string
): Promise<string | null> {
try {
const exportSchemaCommand = new ExportSchemaCommand({
RegistryName: registryName,
SchemaName: schemaName,
Type: 'JSONSchemaDraft4',
});
const exportResponse = await schemasClient.send(exportSchemaCommand);
return exportResponse.Content || null;
} catch (error) {
// Can't get the schema, just return null
// Custom schema regs will either be JSON or OpenAPI we try both...
// console.error(`Error getting JSON Schema for ${schemaName}:`, error);
return null;
}
}
async function tryFetchOpenAPISchema(
schemasClient: SchemasClient,
registryName: string,
schemaName: string
): Promise<DescribeSchemaCommandOutput | null> {
try {
const describeSchemaCommand = new DescribeSchemaCommand({
RegistryName: registryName,
SchemaName: schemaName,
});
const schemaDetails = await schemasClient.send(describeSchemaCommand);
return schemaDetails || null;
} catch (error) {
// Can't get the schema, just return null
// Custom schema regs will either be JSON or OpenAPI we try both...
// console.error(`Error getting OpenAPI Schema for ${schemaName}:`, error);
return null;
}
}
const fetchSchemasForRegistry =
(schemasClient: SchemasClient) =>
async (registryName: string, mapEventsBy: EventMap): Promise<Event[]> => {
// Get all schemas from discovered-schemas
const schemas = [] as Event[];
let allSchemas: SchemaSummary[] = [];
let nextToken: string | undefined;
do {
const listSchemasCommand = new ListSchemasCommand({
RegistryName: registryName,
NextToken: nextToken,
});
const response = await schemasClient.send(listSchemasCommand);
allSchemas = [...allSchemas, ...(response.Schemas || [])];
nextToken = response.NextToken;
} while (nextToken);
console.log(chalk.green(`Fetching EventBridge schemas...`));
for (const schema of allSchemas) {
if (!schema.SchemaName) {
console.log(`Skipping schema ${schema.SchemaName} as it has no name`);
continue;
}
const jsonSchema = await tryFetchJSONSchema(schemasClient, registryName, schema.SchemaName);
const openApiSchema = await tryFetchOpenAPISchema(schemasClient, registryName, schema.SchemaName);
if ((jsonSchema === null && openApiSchema === null) || !schema.SchemaName) {
console.log(`Skipping schema ${schema.SchemaName} as both JSON and OpenAPI schemas are null`);
continue;
}
const parts = schema.SchemaName?.split('@');
const source = parts[0];
const detailType = parts[1];
// ARN?
const arn = schema.SchemaArn ? parse(schema.SchemaArn) : undefined;
// in custom registries detailType is not a value, so we use schema name
const id = mapEventsBy === 'detail-type' ? detailType || schema.SchemaName : schema.SchemaName;
schemas.push({
id,
schemaName: schema.SchemaName,
registryName: registryName,
source,
// in custom registries detailType is not set
detailType,
jsonSchema,
openApiSchema: openApiSchema?.Content,
// Use EventBridge version count
version: schema.VersionCount?.toString() || '1',
createdDate: openApiSchema?.VersionCreatedDate,
// EventBridge versions with every change, we can use this as the minor version
versionCount: schema.VersionCount || 0,
region: arn?.region,
accountId: arn?.accountId,
jsonDraftFileName: `${schema.SchemaName}-jsondraft.json`,
openApiFileName: `${schema.SchemaName}-openapi.json`,
});
}
return schemas;
};
export default async (config: EventCatalogConfig, options: GeneratorProps) => {
if (!process.env.PROJECT_DIR) {
process.env.PROJECT_DIR = process.cwd();
}
// This is set by EventCatalog. This is the directory where the catalog is stored
const eventCatalogDirectory = process.env.PROJECT_DIR;
const { services, region, mapEventsBy = 'detail-type' } = options;
const schemasClient = new SchemasClient({ region, credentials: options.credentials });
if (!eventCatalogDirectory) {
throw new Error('Please provide catalog url (env variable PROJECT_DIR)');
}
// EventCatalog SDK (https://www.eventcatalog.dev/docs/sdk)
const {
writeService,
writeDomain,
getDomain,
versionDomain,
addServiceToDomain,
getService,
versionService,
getSpecificationFilesForService,
rmServiceById,
} = utils(eventCatalogDirectory);
const events = await fetchSchemasForRegistry(schemasClient)(options.registryName, mapEventsBy);
// If no domain or services, just write all messages to catalog.
if (!options.domain && !options.services) {
await processEvents(events, options);
return;
}
if (!services) {
throw new Error('Please provide services for your events. Please see the generator example and API docs');
}
console.log(chalk.green(`Processing ${services.length} services with EventBridge...`));
for (const service of services) {
console.log(chalk.gray(`Processing ${service.id}`));
let sendsEvents = [] as Event[];
let receivesEvents = [] as Event[];
if (service.sends) {
sendsEvents = filterEvents(events, service.sends);
}
if (service.receives) {
receivesEvents = filterEvents(events, service.receives);
}
const eventsToWrite = [...sendsEvents, ...receivesEvents];
await processEvents(eventsToWrite, options);
// Manage domain
if (options.domain) {
// Try and get the domain
const { id: domainId, name: domainName, version: domainVersion } = options.domain;
const domain = await getDomain(options.domain.id, domainVersion || 'latest');
const currentDomain = await getDomain(options.domain.id, 'latest');
console.log(chalk.blue(`\nProcessing domain: ${domainName} (v${domainVersion})`));
// Found a domain, but the versions do not match
if (currentDomain && currentDomain.version !== domainVersion) {
await versionDomain(domainId);
console.log(chalk.cyan(` - Versioned previous domain (v${currentDomain.version})`));
}
// Do we need to create a new domain?
if (!domain || (domain && domain.version !== domainVersion)) {
await writeDomain({
id: domainId,
name: domainName,
version: domainVersion,
markdown: generateMarkdownForDomain(),
// services: [{ id: serviceId, version: version }],
});
console.log(chalk.cyan(` - Domain (v${domainVersion}) created`));
}
if (currentDomain && currentDomain.version === domainVersion) {
console.log(chalk.yellow(` - Domain (v${domainVersion}) already exists, skipped creation...`));
}
// Add the service to the domain
await addServiceToDomain(domainId, { id: service.id, version: service.version }, domainVersion);
}
// Check if service is already defined... if the versions do not match then create service.
const latestServiceInCatalog = await getService(service.id, 'latest');
let serviceMarkdown = generateMarkdownForService();
let serviceSpecifications = {};
let serviceSpecificationsFiles = [];
let sends = sendsEvents.map((event) => ({ id: event.detailType || event.schemaName, version: event.version || 'latest' }));
let receives = receivesEvents.map((event) => ({
id: event.detailType || event.schemaName,
version: event.version || 'latest',
}));
let owners = [] as any;
console.log(chalk.blue(`Processing service: ${service.id} (v${service.version})`));
if (latestServiceInCatalog) {
serviceMarkdown = latestServiceInCatalog.markdown;
owners = latestServiceInCatalog.owners || [];
// Found a service, and versions do not match, we need to version the one already there
if (latestServiceInCatalog.version !== service.version) {
await versionService(service.id);
console.log(chalk.cyan(` - Versioned previous service (v${latestServiceInCatalog.version})`));
}
// Match found, override it
if (latestServiceInCatalog.version === service.version) {
// we want to preserve the markdown any any spec files that are already there
serviceMarkdown = latestServiceInCatalog.markdown;
serviceSpecifications = latestServiceInCatalog.specifications ?? {}; // Why this not here?
sends = latestServiceInCatalog.sends ? [...latestServiceInCatalog.sends, ...sends] : sends;
receives = latestServiceInCatalog.receives ? [...latestServiceInCatalog.receives, ...receives] : receives;
serviceSpecificationsFiles = await getSpecificationFilesForService(
latestServiceInCatalog.id,
latestServiceInCatalog.version
);
await rmServiceById(service.id);
}
}
await writeService({
id: service.id,
markdown: serviceMarkdown,
name: service.id,
version: service.version,
sends,
receives,
specifications: serviceSpecifications,
owners: owners,
});
}
console.log(chalk.green(`\nFinished generating event catalog with EventBridge schema registry ${options.registryName}`));
await checkLicense();
};
const processEvents = async (events: Event[], options: GeneratorProps) => {
// This is set by EventCatalog. This is the directory where the catalog is stored
const eventCatalogDirectory = process.env.PROJECT_DIR;
const eventBridgeClient = new EventBridgeClient({ region: options.region, credentials: options.credentials });
if (!eventCatalogDirectory) {
throw new Error('Please provide catalog url (env variable PROJECT_DIR)');
}
// EventCatalog SDK (https://www.eventcatalog.dev/docs/sdk)
const { getEvent, writeEvent, addSchemaToEvent, rmEventById, versionEvent, writeChannel, getChannel } =
utils(eventCatalogDirectory);
for (const event of events) {
// in custom registries detailType is not a value, so we use schema name
console.log(chalk.blue(`Processing event: ${event.id} (v${event.version})`));
const schemaPath = event.jsonSchema ? event.jsonDraftFileName : event.openApiSchema ? event.openApiFileName : '';
let messageMarkdown = generateMarkdownForMessage(event);
const catalogedEvent = await getEvent(event.id, event.version);
let eventChannel = [] as any;
if (catalogedEvent) {
// Persist markdown between versions
messageMarkdown = catalogedEvent.markdown;
// if the version matches, we can override the message but keep markdown as it was
if (catalogedEvent.version === event.version) {
await rmEventById(event.id, event.version);
} else {
// if the version does not match, we need to version the message
await versionEvent(event.id);
console.log(chalk.cyan(` - Versioned previous message: (v${catalogedEvent.version})`));
}
}
// If we have defined an eventbus for this event (channel), we document it
if (event.eventBusName) {
const channel = await getChannel(event.eventBusName);
if (!channel) {
let name = event.eventBusName;
let address = '';
let summary = 'Amazon EventBridge event bus';
let markdown =
'This EventBridge Event Bus serves as a message routing system on AWS. It handles events and routes them to targets.';
try {
console.log('GO');
const eventBusCommand = new DescribeEventBusCommand({
Name: event.eventBusName,
});
const response = await eventBridgeClient.send(eventBusCommand);
name = response.Name || event.eventBusName;
address = response.Arn || '';
summary = `Amazon EventBridge: ${response.Description}` || 'Amazon EventBridge event bus';
markdown = generatedMarkdownByEventBus(event, response);
} catch (error) {
console.log(error);
// Do nothing, fall back.
}
await writeChannel({
id: event.eventBusName,
name: `EventBridge: ${name}`,
markdown,
version: '1.0.0', // hardcode for now, what would this be?
address,
protocols: ['eventbridge'],
summary,
});
}
eventChannel = [{ id: event.eventBusName, version: 'latest' }];
}
await writeEvent({
id: event.id,
name: event.id,
version: event.version?.toString() || '',
schemaPath,
markdown: messageMarkdown,
badges: getBadgesForMessage(event, options.eventBusName),
channels: eventChannel,
});
console.log(chalk.cyan(` - Event (${event.id} v${event.version}) created`));
if (event.jsonSchema) {
await addSchemaToEvent(event.id, { fileName: event.jsonDraftFileName, schema: event.jsonSchema });
console.log(chalk.cyan(` - Schema added to event (v${event.version})`));
}
if (event.openApiSchema) {
await addSchemaToEvent(event.id, { fileName: event.openApiFileName, schema: event.openApiSchema });
console.log(chalk.cyan(` - Schema added to event (v${event.version})`));
}
}
};