forked from dipseth/dataproc-mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransformation-engine.ts
More file actions
360 lines (308 loc) · 11.1 KB
/
transformation-engine.ts
File metadata and controls
360 lines (308 loc) · 11.1 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
/**
* Transformation Engine
* Handles field mapping, transformations, and metadata injection for generic conversions
*/
import {
FieldTransformations,
MetadataInjectionRules,
CompressibleField,
} from '../types/generic-converter.js';
import { QdrantStorageMetadata } from '../types/response-filter.js';
import { QdrantPayloadBase } from '../types/qdrant-payload.js';
import { logger } from '../utils/logger.js';
import { v4 as uuidv4 } from 'uuid';
/**
* Engine for applying field transformations and mappings
*/
export class TransformationEngine {
/**
* Apply field mappings to transform source fields to target structure
*/
applyFieldMappings<TSource extends Record<string, any>, TTarget extends Record<string, any>>(
source: TSource,
fieldMappings?: Partial<Record<keyof TSource, string>>
): Partial<TTarget> {
const result: any = {};
for (const [sourceKey, sourceValue] of Object.entries(source)) {
const typedSourceKey = sourceKey as keyof TSource;
// Use mapped field name if provided, otherwise use original key
const targetKey = fieldMappings?.[typedSourceKey] || sourceKey;
result[targetKey] = sourceValue;
}
logger.debug('Applied field mappings', {
sourceFields: Object.keys(source).length,
mappedFields: fieldMappings ? Object.keys(fieldMappings).length : 0,
resultFields: Object.keys(result).length,
});
return result;
}
/**
* Apply field transformations to modify field values
*/
applyTransformations<TSource extends Record<string, any>>(
source: TSource,
transformations?: FieldTransformations<TSource>
): TSource {
if (!transformations) {
return source;
}
const result = { ...source };
let transformedCount = 0;
for (const [fieldName, transformer] of Object.entries(transformations)) {
const typedFieldName = fieldName as keyof TSource;
if (typedFieldName in result && typeof transformer === 'function') {
try {
const originalValue = result[typedFieldName];
const transformedValue = transformer(originalValue);
result[typedFieldName] = transformedValue;
transformedCount++;
logger.debug(`Transformed field '${String(fieldName)}'`, {
originalType: typeof originalValue,
transformedType: typeof transformedValue,
});
} catch (error) {
logger.warn(`Failed to transform field '${String(fieldName)}'`, {
error: error instanceof Error ? error.message : String(error),
});
}
}
}
logger.debug('Applied field transformations', {
totalFields: Object.keys(source).length,
transformedFields: transformedCount,
});
return result;
}
/**
* Inject metadata fields into the payload
*/
injectMetadata<T extends Record<string, any>>(
payload: T,
baseMetadata: QdrantStorageMetadata,
metadataRules?: MetadataInjectionRules
): T & QdrantPayloadBase {
const result = {
...payload,
...baseMetadata,
storedAt: new Date().toISOString(),
} as T & QdrantPayloadBase;
// Apply metadata injection rules
if (metadataRules) {
if (metadataRules.autoTimestamp) {
result.timestamp = new Date().toISOString();
}
if (metadataRules.autoUUID && !result.id) {
(result as any).id = uuidv4();
}
if (metadataRules.customFields) {
for (const [fieldName, generator] of Object.entries(metadataRules.customFields)) {
try {
(result as any)[fieldName] = generator();
} catch (error) {
logger.warn(`Failed to generate custom field '${fieldName}'`, {
error: error instanceof Error ? error.message : String(error),
});
}
}
}
}
logger.debug('Injected metadata', {
baseFields: Object.keys(baseMetadata).length,
customFields: metadataRules?.customFields
? Object.keys(metadataRules.customFields).length
: 0,
autoTimestamp: metadataRules?.autoTimestamp || false,
autoUUID: metadataRules?.autoUUID || false,
});
return result;
}
/**
* Merge compressed fields back into the payload structure
*/
mergeCompressedFields<T extends Record<string, any>>(
basePayload: T,
compressedFields: Record<string, CompressibleField<any>>
): T {
const result = { ...basePayload };
for (const [fieldName, compressedField] of Object.entries(compressedFields)) {
(result as any)[fieldName] = compressedField.data;
// Add compression metadata if field was compressed
if (compressedField.isCompressed) {
(result as any)[`${fieldName}_isCompressed`] = compressedField.isCompressed;
(result as any)[`${fieldName}_compressionType`] = compressedField.compressionType;
(result as any)[`${fieldName}_originalSize`] = compressedField.originalSize;
(result as any)[`${fieldName}_compressedSize`] = compressedField.compressedSize;
}
}
logger.debug('Merged compressed fields', {
totalFields: Object.keys(compressedFields).length,
compressedFields: Object.values(compressedFields).filter((f) => f.isCompressed).length,
});
return result;
}
/**
* Apply default value transformations for common field patterns
*/
applyDefaultTransformations<T extends Record<string, any>>(source: T): T {
const result = { ...source };
// Apply common transformations
for (const [key, value] of Object.entries(result)) {
// Convert Date objects to ISO strings
if (value instanceof Date) {
(result as any)[key] = value.toISOString();
}
// Ensure numeric fields are properly typed
else if (typeof value === 'string' && this.isNumericString(value)) {
const numValue = Number(value);
if (!isNaN(numValue)) {
(result as any)[key] = numValue;
}
}
// Convert undefined to null for JSON compatibility
else if (value === undefined) {
(result as any)[key] = null;
}
// Handle empty arrays and objects
else if (Array.isArray(value) && value.length === 0) {
// Keep empty arrays as-is, but log for potential optimization
logger.debug(`Empty array found for field '${key}'`);
} else if (typeof value === 'object' && value !== null && Object.keys(value).length === 0) {
// Keep empty objects as-is, but log for potential optimization
logger.debug(`Empty object found for field '${key}'`);
}
}
return result;
}
/**
* Validate field mappings for type safety
*/
validateFieldMappings<TSource extends Record<string, any>>(
source: TSource,
fieldMappings: Partial<Record<keyof TSource, string>>
): {
valid: boolean;
errors: string[];
warnings: string[];
} {
const errors: string[] = [];
const warnings: string[] = [];
for (const [sourceField, targetField] of Object.entries(fieldMappings)) {
// Check if source field exists
if (!(sourceField in source)) {
warnings.push(`Source field '${sourceField}' not found in source object`);
}
// Check for valid target field names
if (typeof targetField !== 'string' || targetField.trim() === '') {
errors.push(`Invalid target field name for '${sourceField}': '${targetField}'`);
}
// Check for reserved field names
const reservedFields = ['id', 'vector', 'payload'];
if (typeof targetField === 'string' && reservedFields.includes(targetField)) {
warnings.push(`Target field '${targetField}' is a reserved Qdrant field name`);
}
}
// Check for duplicate target field names
const targetFields = Object.values(fieldMappings).filter(Boolean);
const uniqueTargetFields = new Set(targetFields);
if (targetFields.length !== uniqueTargetFields.size) {
errors.push('Duplicate target field names detected in field mappings');
}
return {
valid: errors.length === 0,
errors,
warnings,
};
}
/**
* Generate automatic field mappings based on common patterns
*/
generateAutoFieldMappings<T extends Record<string, any>>(
source: T,
targetType: 'query' | 'cluster' | 'job' | 'generic'
): Partial<Record<keyof T, string>> {
const mappings: Partial<Record<keyof T, string>> = {};
for (const key of Object.keys(source)) {
const typedKey = key as keyof T;
const keyLower = key.toLowerCase();
switch (targetType) {
case 'query':
if (keyLower.includes('total') && keyLower.includes('row')) {
mappings[typedKey] = 'totalRows';
} else if (keyLower.includes('result') || keyLower.includes('row')) {
mappings[typedKey] = 'rows';
} else if (keyLower.includes('schema') || keyLower.includes('field')) {
mappings[typedKey] = 'schema';
}
break;
case 'cluster':
if (keyLower.includes('config')) {
mappings[typedKey] = 'clusterConfig';
} else if (keyLower.includes('machine') || keyLower.includes('instance')) {
mappings[typedKey] = 'machineTypes';
} else if (keyLower.includes('network')) {
mappings[typedKey] = 'networkConfig';
} else if (keyLower.includes('software')) {
mappings[typedKey] = 'softwareConfig';
}
break;
case 'job':
if (keyLower.includes('result')) {
mappings[typedKey] = 'results';
} else if (keyLower.includes('type')) {
mappings[typedKey] = 'jobType';
} else if (keyLower.includes('status') || keyLower.includes('state')) {
mappings[typedKey] = 'status';
} else if (keyLower.includes('time') && keyLower.includes('submit')) {
mappings[typedKey] = 'submissionTime';
}
break;
case 'generic':
default:
// For generic mappings, use snake_case to camelCase conversion
if (key.includes('_')) {
mappings[typedKey] = this.toCamelCase(key);
}
break;
}
}
logger.debug('Generated automatic field mappings', {
targetType,
sourceFields: Object.keys(source).length,
generatedMappings: Object.keys(mappings).length,
});
return mappings;
}
/**
* Convert snake_case to camelCase
*/
private toCamelCase(str: string): string {
return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
}
/**
* Check if a string represents a numeric value
*/
private isNumericString(str: string): boolean {
return /^-?\d+(\.\d+)?$/.test(str.trim());
}
/**
* Deep clone an object to avoid mutation
*/
private deepClone<T>(obj: T): T {
if (obj === null || typeof obj !== 'object') {
return obj;
}
if (obj instanceof Date) {
return new Date(obj.getTime()) as unknown as T;
}
if (Array.isArray(obj)) {
return obj.map((item) => this.deepClone(item)) as unknown as T;
}
const cloned = {} as T;
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
cloned[key] = this.deepClone(obj[key]);
}
}
return cloned;
}
}