mirror of
https://github.com/dadosfera/maestro.git
synced 2026-11-27 04:10:04 +00:00
458 lines
11 KiB
TypeScript
458 lines
11 KiB
TypeScript
import { Injectable, Inject } from '@nestjs/common';
|
|
import axios, { AxiosInstance, AxiosError } from 'axios';
|
|
import { DadosferaLogger } from '@dadosfera/dadosfera-logs';
|
|
import { ELASTICSEARCH_CONFIG } from './elasticsearch.config';
|
|
|
|
interface MultiLang {
|
|
'en-us': string;
|
|
'pt-br': string;
|
|
'es-es': string;
|
|
}
|
|
|
|
interface MultiLangArray {
|
|
'en-us': string[];
|
|
'pt-br': string[];
|
|
'es-es': string[];
|
|
}
|
|
|
|
interface ConnectorInfo {
|
|
plugin: string;
|
|
name: MultiLang;
|
|
image: string;
|
|
version: string;
|
|
tags: string[];
|
|
}
|
|
|
|
interface PipelineDocument {
|
|
id: string;
|
|
name: MultiLang;
|
|
description: MultiLang;
|
|
customer_id: string;
|
|
user_id: string;
|
|
username: string;
|
|
status: string;
|
|
created_at: string;
|
|
updated_at: string;
|
|
last_status_updated: string;
|
|
tags: string[];
|
|
// Connector metadata
|
|
connection_id: string;
|
|
connector_name: string;
|
|
connector_plugin: string;
|
|
connector_version: string;
|
|
image_url: string;
|
|
// Config
|
|
config: {
|
|
cron: string;
|
|
tables?: string;
|
|
};
|
|
properties: string;
|
|
type: string;
|
|
in_use: number;
|
|
keywords: MultiLangArray;
|
|
}
|
|
|
|
@Injectable()
|
|
export class ElasticsearchService {
|
|
private client: AxiosInstance;
|
|
private logger: any;
|
|
|
|
constructor(
|
|
@Inject(DadosferaLogger) dadosferaLogger: DadosferaLogger,
|
|
) {
|
|
this.logger = dadosferaLogger.logger;
|
|
this.client = axios.create({
|
|
baseURL: ELASTICSEARCH_CONFIG.getUrl(),
|
|
headers: {
|
|
Authorization: `ApiKey ${ELASTICSEARCH_CONFIG.getApiKey()}`,
|
|
'Content-Type': 'application/json',
|
|
},
|
|
timeout: ELASTICSEARCH_CONFIG.timeout,
|
|
});
|
|
}
|
|
|
|
private getIndex(customerName: string): string {
|
|
return `${customerName}_pipelines`;
|
|
}
|
|
|
|
private formatMultiLang(value: string): MultiLang {
|
|
return {
|
|
'en-us': value,
|
|
'pt-br': value,
|
|
'es-es': value,
|
|
};
|
|
}
|
|
|
|
private formatMultiLangArray(value: string[] = []): MultiLangArray {
|
|
return {
|
|
'en-us': value,
|
|
'pt-br': value,
|
|
'es-es': value,
|
|
};
|
|
}
|
|
|
|
buildPipelineDocument(
|
|
pipelineId: string,
|
|
data: {
|
|
name: string;
|
|
description?: string;
|
|
user_id: string;
|
|
username: string;
|
|
customer_id: string;
|
|
plugin: string;
|
|
connection_id: string;
|
|
cron?: string;
|
|
tables?: string;
|
|
properties?: Record<string, any>;
|
|
type?: string;
|
|
status?: string;
|
|
created_at?: string;
|
|
keywords?: string[];
|
|
},
|
|
connector: ConnectorInfo | null,
|
|
): PipelineDocument {
|
|
const now = new Date().toISOString();
|
|
|
|
return {
|
|
id: pipelineId,
|
|
connection_id: data.connection_id,
|
|
connector_name: connector?.name?.['en-us'] || '',
|
|
connector_plugin: connector?.plugin || data.plugin,
|
|
connector_version: connector?.version || '1.0.0',
|
|
created_at: data.created_at || now,
|
|
updated_at: now,
|
|
customer_id: data.customer_id,
|
|
description: this.formatMultiLang(data.description || ''),
|
|
image_url: connector?.image || '',
|
|
keywords: this.formatMultiLangArray(data.keywords),
|
|
name: this.formatMultiLang(data.name || ''),
|
|
status: data.status || 'CREATED',
|
|
user_id: data.user_id,
|
|
username: data.username,
|
|
config: {
|
|
cron: data.cron,
|
|
tables: data.tables,
|
|
},
|
|
properties: data.properties ? JSON.stringify(data.properties) : '{}',
|
|
type: data.type,
|
|
in_use: 1,
|
|
last_status_updated: now,
|
|
tags: connector?.tags || [],
|
|
};
|
|
}
|
|
|
|
async getConnectorByPlugin(plugin: string): Promise<ConnectorInfo | null> {
|
|
this.logger.info('Elasticsearch: Looking up connector', { plugin });
|
|
|
|
try {
|
|
const response = await this.client.post('/connectors/_search', {
|
|
query: {
|
|
term: { plugin: plugin },
|
|
},
|
|
size: 1,
|
|
});
|
|
|
|
const hits = response.data.hits?.hits || [];
|
|
if (hits.length === 0) {
|
|
this.logger.warn('Elasticsearch: Connector not found', { plugin });
|
|
return null;
|
|
}
|
|
|
|
const source = hits[0]._source;
|
|
return {
|
|
plugin: source.plugin,
|
|
name: source.name,
|
|
image: source.image,
|
|
version: source.version,
|
|
tags: source.tags || [],
|
|
};
|
|
} catch (error) {
|
|
this.handleError('getConnectorByPlugin', error, { plugin });
|
|
return null;
|
|
}
|
|
}
|
|
|
|
async createPipeline(
|
|
customerName: string,
|
|
pipelineId: string,
|
|
data: {
|
|
name: string;
|
|
description?: string;
|
|
user_id: string;
|
|
username: string;
|
|
customer_id: string;
|
|
status?: string;
|
|
created_at?: string;
|
|
plugin: string;
|
|
connection_id: string;
|
|
cron?: string;
|
|
tables?: string;
|
|
properties?: Record<string, any>;
|
|
type?: string;
|
|
},
|
|
connector: ConnectorInfo | null,
|
|
): Promise<any> {
|
|
const index = this.getIndex(customerName);
|
|
const document = this.buildPipelineDocument(pipelineId, data, connector);
|
|
|
|
this.logger.info('Elasticsearch: Creating pipeline', {
|
|
index,
|
|
pipelineId,
|
|
plugin: document.connector_plugin,
|
|
});
|
|
|
|
try {
|
|
const response = await this.client.post(
|
|
`${index}/_doc/${pipelineId}`,
|
|
document,
|
|
{ params: { refresh: 'wait_for' } },
|
|
);
|
|
|
|
this.logger.info('Elasticsearch: Pipeline created successfully', {
|
|
pipelineId,
|
|
result: response.data.result,
|
|
});
|
|
|
|
return response.data;
|
|
} catch (error) {
|
|
this.handleError('createPipeline', error, { pipelineId, index });
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async updatePipeline(
|
|
customerName: string,
|
|
pipelineId: string,
|
|
changes: {
|
|
name?: string;
|
|
description?: string;
|
|
cron?: string;
|
|
status?: string;
|
|
tags?: string[];
|
|
},
|
|
): Promise<any> {
|
|
const index = this.getIndex(customerName);
|
|
const now = new Date().toISOString();
|
|
|
|
this.logger.info('Elasticsearch: Updating pipeline', {
|
|
index,
|
|
pipelineId,
|
|
fields: Object.keys(changes),
|
|
});
|
|
|
|
try {
|
|
// Fetch current document
|
|
const currentDoc = await this.client.get(`${index}/_doc/${pipelineId}`);
|
|
const current = currentDoc.data._source;
|
|
|
|
// Build updated document, preserving existing values
|
|
const updated: Record<string, any> = {
|
|
...current,
|
|
updated_at: now,
|
|
};
|
|
|
|
if ('name' in changes) {
|
|
updated.name = this.formatMultiLang(changes.name);
|
|
}
|
|
|
|
if ('description' in changes) {
|
|
updated.description = this.formatMultiLang(changes.description);
|
|
}
|
|
|
|
if ('cron' in changes) {
|
|
updated.config = {
|
|
...current.config,
|
|
cron: changes.cron,
|
|
};
|
|
}
|
|
|
|
if ('status' in changes) {
|
|
updated.status = changes.status;
|
|
updated.last_status_updated = now;
|
|
}
|
|
|
|
if ('tags' in changes) {
|
|
updated.tags = changes.tags;
|
|
}
|
|
|
|
const response = await this.client.post(
|
|
`${index}/_doc/${pipelineId}`,
|
|
updated,
|
|
{ params: { refresh: 'wait_for' } },
|
|
);
|
|
|
|
this.logger.info('Elasticsearch: Pipeline updated successfully', {
|
|
pipelineId,
|
|
result: response.data.result,
|
|
});
|
|
|
|
return response.data;
|
|
} catch (error) {
|
|
this.handleError('updatePipeline', error, { pipelineId, index });
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async getPipeline(
|
|
customerName: string,
|
|
pipelineId: string,
|
|
): Promise<PipelineDocument | null> {
|
|
const index = this.getIndex(customerName);
|
|
|
|
this.logger.info('Elasticsearch: Getting pipeline', {
|
|
index,
|
|
pipelineId,
|
|
});
|
|
|
|
try {
|
|
const response = await this.client.get(`${index}/_doc/${pipelineId}`);
|
|
return response.data._source as PipelineDocument;
|
|
} catch (error) {
|
|
if (error instanceof AxiosError && error.response?.status === 404) {
|
|
this.logger.warn('Elasticsearch: Pipeline not found', {
|
|
pipelineId,
|
|
index,
|
|
});
|
|
return null;
|
|
}
|
|
this.handleError('getPipeline', error, { pipelineId, index });
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async deletePipeline(
|
|
customerName: string,
|
|
pipelineId: string,
|
|
): Promise<any> {
|
|
const index = this.getIndex(customerName);
|
|
|
|
this.logger.info('Elasticsearch: Deleting pipeline', {
|
|
index,
|
|
pipelineId,
|
|
});
|
|
|
|
try {
|
|
const response = await this.client.delete(
|
|
`${index}/_doc/${pipelineId}`,
|
|
{ params: { refresh: 'wait_for' } },
|
|
);
|
|
|
|
this.logger.info('Elasticsearch: Pipeline deleted successfully', {
|
|
pipelineId,
|
|
result: response.data.result,
|
|
});
|
|
|
|
return response.data;
|
|
} catch (error) {
|
|
// If document not found, log warning but don't throw
|
|
if (error instanceof AxiosError && error.response?.status === 404) {
|
|
this.logger.warn('Elasticsearch: Pipeline not found for deletion', {
|
|
pipelineId,
|
|
index,
|
|
});
|
|
return { result: 'not_found' };
|
|
}
|
|
|
|
this.handleError('deletePipeline', error, { pipelineId, index });
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
private getDataAssetIndex(customerName: string): string {
|
|
return `${customerName}_data_assets_catalog`;
|
|
}
|
|
|
|
async findDataAssetByTable(
|
|
customerName: string,
|
|
tableName: string,
|
|
tableSchema: string,
|
|
): Promise<{ id: string; nimbus_id: number | null; [key: string]: any } | null> {
|
|
const index = this.getDataAssetIndex(customerName);
|
|
|
|
this.logger.info('Elasticsearch: Searching data asset', {
|
|
index,
|
|
tableName,
|
|
tableSchema,
|
|
});
|
|
|
|
try {
|
|
const response = await this.client.post(`/${index}/_search`, {
|
|
query: {
|
|
bool: {
|
|
must: [
|
|
{ term: { 'table_name.keyword': tableName.toUpperCase() } },
|
|
{ term: { 'table_schema.keyword': tableSchema.toUpperCase() } },
|
|
],
|
|
},
|
|
},
|
|
size: 1,
|
|
});
|
|
|
|
const hits = response.data.hits?.hits || [];
|
|
if (hits.length === 0) {
|
|
this.logger.warn('Elasticsearch: Data asset not found', { tableName, tableSchema, index });
|
|
return null;
|
|
}
|
|
|
|
return { ...hits[0]._source, _es_id: hits[0]._id };
|
|
} catch (error) {
|
|
this.handleError('findDataAssetByTable', error, { tableName, tableSchema, index });
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async updateDataAsset(
|
|
customerName: string,
|
|
assetId: string,
|
|
updates: Record<string, any>,
|
|
): Promise<any> {
|
|
const index = this.getDataAssetIndex(customerName);
|
|
|
|
this.logger.info('Elasticsearch: Updating data asset', {
|
|
index,
|
|
assetId,
|
|
fields: Object.keys(updates),
|
|
});
|
|
|
|
try {
|
|
const response = await this.client.post(
|
|
`/${index}/_update/${assetId}`,
|
|
{ doc: updates },
|
|
{ params: { refresh: 'wait_for' } },
|
|
);
|
|
|
|
this.logger.info('Elasticsearch: Data asset updated', {
|
|
assetId,
|
|
result: response.data.result,
|
|
});
|
|
|
|
return response.data;
|
|
} catch (error) {
|
|
this.handleError('updateDataAsset', error, { assetId, index });
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
private handleError(
|
|
operation: string,
|
|
error: any,
|
|
context: Record<string, any>,
|
|
): void {
|
|
if (error instanceof AxiosError) {
|
|
this.logger.error(`Elasticsearch: ${operation} failed`, {
|
|
...context,
|
|
status: error.response?.status,
|
|
statusText: error.response?.statusText,
|
|
errorData: error.response?.data,
|
|
message: error.message,
|
|
});
|
|
} else {
|
|
this.logger.error(`Elasticsearch: ${operation} failed`, {
|
|
...context,
|
|
message: error.message,
|
|
stack: error.stack,
|
|
});
|
|
}
|
|
}
|
|
}
|