forked from dipseth/dataproc-mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgeneric-converter.ts
More file actions
401 lines (352 loc) · 12 KB
/
generic-converter.ts
File metadata and controls
401 lines (352 loc) · 12 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
/**
* Generic Qdrant Converter
* Main conversion engine that orchestrates field analysis, transformation, and compression
*/
import {
ConversionConfig,
ConversionResult,
ValidationResult,
ConversionMetrics,
InferQdrantPayload,
CompressibleField,
} from '../types/generic-converter.js';
import { QdrantPayloadBase } from '../types/qdrant-payload.js';
import { QdrantStorageMetadata } from '../types/response-filter.js';
import { performance } from 'perf_hooks';
import {
isQueryResultData,
isExtendedClusterData,
isDataprocJob,
} from '../types/dataproc-responses.js';
import { FieldAnalyzer } from './field-analyzer.js';
import { TransformationEngine } from './transformation-engine.js';
import { CompressionService } from './compression.js';
import { logger } from '../utils/logger.js';
/**
* Main generic converter service
*/
export class GenericQdrantConverter {
private fieldAnalyzer: FieldAnalyzer;
private transformationEngine: TransformationEngine;
private compressionService: CompressionService;
private metrics: ConversionMetrics;
constructor(compressionService: CompressionService) {
this.fieldAnalyzer = new FieldAnalyzer();
this.transformationEngine = new TransformationEngine();
this.compressionService = compressionService;
this.metrics = this.initializeMetrics();
}
/**
* Convert any source type to Qdrant-compatible payload with automatic type inference
*/
async convert<TSource extends Record<string, any>>(
source: TSource,
metadata: QdrantStorageMetadata,
config?: ConversionConfig<TSource>
): Promise<ConversionResult<InferQdrantPayload<TSource>>> {
const startTime = performance.now();
try {
logger.info('Starting generic conversion', {
sourceType: this.detectSourceType(source),
fieldsCount: Object.keys(source).length,
hasConfig: !!config,
});
// 1. Validate source data
const validation = await this.validateSource(source);
if (!validation.isValid) {
throw new Error(`Source validation failed: ${validation.errors.join(', ')}`);
}
// 2. Analyze source fields
const fieldAnalysis = await this.fieldAnalyzer.analyzeFields(source);
// 3. Apply default transformations
const transformedSource = this.transformationEngine.applyDefaultTransformations(source);
// 4. Apply custom field mappings
const mappedFields = this.transformationEngine.applyFieldMappings(
transformedSource,
config?.fieldMappings
);
// 5. Apply custom transformations
const customTransformed = this.transformationEngine.applyTransformations(
mappedFields as TSource,
config?.transformations
);
// 6. Handle field-level compression
const compressedFields = await this.handleFieldCompression(
customTransformed,
fieldAnalysis,
config?.compressionRules
);
// 7. Merge compressed fields back into payload
const payloadWithCompression = this.transformationEngine.mergeCompressedFields(
customTransformed,
compressedFields
);
// 8. Inject metadata
const finalPayload = this.transformationEngine.injectMetadata(
payloadWithCompression,
metadata,
config?.metadata
);
// 9. Calculate metrics
const processingTime = performance.now() - startTime;
const conversionMetadata = this.calculateConversionMetadata(
source,
compressedFields,
processingTime
);
// 10. Update global metrics
this.updateMetrics(conversionMetadata);
logger.info('Generic conversion completed', {
processingTime: `${processingTime.toFixed(2)}ms`,
fieldsProcessed: conversionMetadata.fieldsProcessed,
fieldsCompressed: conversionMetadata.fieldsCompressed,
compressionRatio: conversionMetadata.compressionRatio,
});
return {
payload: finalPayload as unknown as InferQdrantPayload<TSource>,
metadata: conversionMetadata,
};
} catch (error) {
logger.error('Generic conversion failed', {
error: error instanceof Error ? error.message : String(error),
sourceType: this.detectSourceType(source),
});
throw error;
}
}
/**
* Convert with explicit type specification for better type safety
*/
async convertTyped<TSource extends Record<string, any>, TTarget extends QdrantPayloadBase>(
source: TSource,
metadata: QdrantStorageMetadata,
targetType: new () => TTarget,
config?: ConversionConfig<TSource>
): Promise<ConversionResult<TTarget>> {
const result = await this.convert(source, metadata, config);
return result as unknown as ConversionResult<TTarget>;
}
/**
* Validate source data for conversion compatibility
*/
async validateSource<T extends Record<string, any>>(source: T): Promise<ValidationResult> {
const errors: string[] = [];
const warnings: string[] = [];
const suggestions: string[] = [];
// Basic validation
if (!source || typeof source !== 'object') {
errors.push('Source must be a non-null object');
return { isValid: false, errors, warnings, suggestions };
}
if (Object.keys(source).length === 0) {
warnings.push('Source object is empty');
}
// Use field analyzer for detailed validation
const compatibility = this.fieldAnalyzer.validateQdrantCompatibility(source);
errors.push(...compatibility.issues);
suggestions.push(...compatibility.suggestions);
// Check for required metadata fields
const requiredFields = ['toolName', 'timestamp', 'projectId', 'region'];
for (const field of requiredFields) {
if (!(field in source)) {
warnings.push(`Recommended field '${field}' not found in source`);
}
}
return {
isValid: errors.length === 0,
errors,
warnings,
suggestions,
};
}
/**
* Handle field-level compression based on analysis and configuration
*/
private async handleFieldCompression<T extends Record<string, any>>(
source: T,
fieldAnalysis: any,
compressionRules?: any
): Promise<Record<string, CompressibleField<any>>> {
const compressedFields: Record<string, CompressibleField<any>> = {};
// Determine fields to compress
let fieldsToCompress: (keyof T)[] = [];
if (compressionRules?.fields) {
fieldsToCompress = compressionRules.fields;
} else {
// Use automatic detection
const recommendations = this.fieldAnalyzer.generateCompressionRecommendations(fieldAnalysis);
fieldsToCompress = [...recommendations.recommended, ...recommendations.optional];
}
// Compress each field
for (const fieldName of fieldsToCompress) {
if (fieldName in source) {
const fieldValue = source[fieldName];
const compressed = await this.compressionService.compressIfNeeded(fieldValue);
compressedFields[String(fieldName)] = {
data: compressed.data,
isCompressed: compressed.isCompressed,
compressionType: compressed.compressionType,
originalSize: compressed.originalSize,
compressedSize: compressed.compressedSize,
};
}
}
return compressedFields;
}
/**
* Detect the source data type for automatic configuration
*/
private detectSourceType(source: unknown): string {
if (isQueryResultData(source)) {
return 'QueryResultData';
}
if (isExtendedClusterData(source)) {
return 'ExtendedClusterData';
}
if (isDataprocJob(source)) {
return 'DataprocJob';
}
return 'Unknown';
}
/**
* Calculate conversion metadata for result
*/
private calculateConversionMetadata(
source: Record<string, any>,
compressedFields: Record<string, CompressibleField<any>>,
processingTime: number
) {
const fieldsProcessed = Object.keys(source).length;
const fieldsCompressed = Object.values(compressedFields).filter((f) => f.isCompressed).length;
const totalOriginalSize = Object.values(compressedFields).reduce(
(sum, field) => sum + (field.originalSize || 0),
0
);
const totalCompressedSize = Object.values(compressedFields).reduce(
(sum, field) => sum + (field.compressedSize || field.originalSize || 0),
0
);
const compressionRatio = totalOriginalSize > 0 ? totalCompressedSize / totalOriginalSize : 1;
return {
fieldsProcessed,
fieldsCompressed,
totalOriginalSize,
totalCompressedSize,
compressionRatio,
processingTime,
};
}
/**
* Update global conversion metrics
*/
private updateMetrics(conversionMetadata: any): void {
this.metrics.totalConversions++;
// Update averages
const totalTime =
this.metrics.averageProcessingTime * (this.metrics.totalConversions - 1) +
conversionMetadata.processingTime;
this.metrics.averageProcessingTime = totalTime / this.metrics.totalConversions;
const totalRatio =
this.metrics.averageCompressionRatio * (this.metrics.totalConversions - 1) +
conversionMetadata.compressionRatio;
this.metrics.averageCompressionRatio = totalRatio / this.metrics.totalConversions;
}
/**
* Get current conversion metrics
*/
getMetrics(): ConversionMetrics {
return { ...this.metrics };
}
/**
* Reset conversion metrics
*/
resetMetrics(): void {
this.metrics = this.initializeMetrics();
}
/**
* Initialize metrics object
*/
private initializeMetrics(): ConversionMetrics {
return {
totalConversions: 0,
averageProcessingTime: 0,
averageCompressionRatio: 1,
fieldCompressionStats: {},
};
}
/**
* Create conversion configuration for known types
*/
async createConfigForType<T extends Record<string, any>>(
source: T,
type: 'query' | 'cluster' | 'job' | 'auto'
): Promise<ConversionConfig<T>> {
const detectedType = type === 'auto' ? this.detectSourceType(source) : type;
// Generate automatic field mappings
const fieldMappings = this.transformationEngine.generateAutoFieldMappings(
source,
detectedType as any
);
// Generate compression recommendations
const fieldAnalysis = await this.fieldAnalyzer.analyzeFields(source);
const compressionRecommendations =
this.fieldAnalyzer.generateCompressionRecommendations(fieldAnalysis);
return {
fieldMappings,
compressionRules: {
fields: compressionRecommendations.recommended,
sizeThreshold: 10240, // 10KB
compressionType: 'gzip',
},
transformations: this.getDefaultTransformationsForType(detectedType),
metadata: {
autoTimestamp: true,
autoUUID: false,
},
};
}
/**
* Get default transformations for specific types
*/
private getDefaultTransformationsForType(type: string): any {
switch (type) {
case 'QueryResultData':
return {
totalRows: (value: any) => value || 0,
timestamp: () => new Date().toISOString(),
};
case 'ExtendedClusterData':
return {
createTime: (value: any) => value || new Date().toISOString(),
status: (value: any) => value || 'UNKNOWN',
};
case 'DataprocJob':
return {
submissionTime: (value: any) => value || new Date().toISOString(),
status: (value: any) => value || 'UNKNOWN',
};
default:
return {};
}
}
}
/**
* Factory function to create a configured generic converter
*/
export function createGenericConverter(
compressionService: CompressionService
): GenericQdrantConverter {
return new GenericQdrantConverter(compressionService);
}
/**
* Utility function for quick conversions with automatic configuration
*/
export async function quickConvert<TSource extends Record<string, any>>(
source: TSource,
metadata: QdrantStorageMetadata,
compressionService: CompressionService
): Promise<ConversionResult<InferQdrantPayload<TSource>>> {
const converter = createGenericConverter(compressionService);
const config = await converter.createConfigForType(source, 'auto');
return converter.convert(source, metadata, config);
}