@arcaelas/dynamite 1.0.13 → 1.0.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1165 -152
- package/package.json +6 -9
- package/LICENSE.txt +0 -32
- package/README.txt +0 -206
- package/SECURITY.md +0 -41
- package/src/@types/index.d.ts +0 -96
- package/src/@types/index.js +0 -9
- package/src/core/client.d.ts +0 -69
- package/src/core/client.js +0 -164
- package/src/core/table.d.ts +0 -98
- package/src/core/table.js +0 -459
- package/src/core/wrapper.d.ts +0 -17
- package/src/core/wrapper.js +0 -46
- package/src/decorators/belongs_to.d.ts +0 -1
- package/src/decorators/belongs_to.js +0 -24
- package/src/decorators/created_at.d.ts +0 -1
- package/src/decorators/created_at.js +0 -11
- package/src/decorators/default.d.ts +0 -1
- package/src/decorators/default.js +0 -47
- package/src/decorators/has_many.d.ts +0 -1
- package/src/decorators/has_many.js +0 -24
- package/src/decorators/index.d.ts +0 -11
- package/src/decorators/index.js +0 -36
- package/src/decorators/index_sort.d.ts +0 -12
- package/src/decorators/index_sort.js +0 -43
- package/src/decorators/mutate.d.ts +0 -2
- package/src/decorators/mutate.js +0 -51
- package/src/decorators/name.d.ts +0 -1
- package/src/decorators/name.js +0 -28
- package/src/decorators/not_null.d.ts +0 -1
- package/src/decorators/not_null.js +0 -13
- package/src/decorators/primary_key.d.ts +0 -6
- package/src/decorators/primary_key.js +0 -30
- package/src/decorators/updated_at.d.ts +0 -12
- package/src/decorators/updated_at.js +0 -26
- package/src/decorators/validate.d.ts +0 -1
- package/src/decorators/validate.js +0 -53
- package/src/index.d.ts +0 -22
- package/src/index.js +0 -47
- package/src/utils/batch-relations.d.ts +0 -14
- package/src/utils/batch-relations.js +0 -131
- package/src/utils/circular-detector.d.ts +0 -82
- package/src/utils/circular-detector.js +0 -209
- package/src/utils/memory-manager.d.ts +0 -42
- package/src/utils/memory-manager.js +0 -108
- package/src/utils/naming.d.ts +0 -8
- package/src/utils/naming.js +0 -18
- package/src/utils/projection.d.ts +0 -12
- package/src/utils/projection.js +0 -51
- package/src/utils/relations.d.ts +0 -17
- package/src/utils/relations.js +0 -166
- package/src/utils/security-validator.d.ts +0 -49
- package/src/utils/security-validator.js +0 -152
- package/src/utils/throttle-manager.d.ts +0 -78
- package/src/utils/throttle-manager.js +0 -196
- package/src/utils/transaction-manager.d.ts +0 -88
- package/src/utils/transaction-manager.js +0 -298
package/src/utils/relations.js
DELETED
|
@@ -1,166 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* @file relations.ts
|
|
4
|
-
* @descripcion Sistema de relaciones optimizado
|
|
5
|
-
* @autor Miguel Alejandro
|
|
6
|
-
* @fecha 2025-01-28
|
|
7
|
-
*/
|
|
8
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
-
exports.separateQueryOptions = exports.processIncludes = exports.belongsTo = exports.hasMany = void 0;
|
|
10
|
-
// =============================================================================
|
|
11
|
-
// IMPORTS
|
|
12
|
-
// =============================================================================
|
|
13
|
-
const wrapper_1 = require("../core/wrapper");
|
|
14
|
-
const naming_1 = require("./naming");
|
|
15
|
-
// =============================================================================
|
|
16
|
-
// DECORATORS
|
|
17
|
-
// =============================================================================
|
|
18
|
-
/** Decorador @hasMany para relaciones 1:N */
|
|
19
|
-
const hasMany = (targetModel, foreignKey, localKey = "id") => (target, propertyKey) => {
|
|
20
|
-
(0, wrapper_1.ensureConfig)(target.constructor, (0, naming_1.toSnakePlural)(target.constructor.name)).relations.set(propertyKey, {
|
|
21
|
-
type: "hasMany",
|
|
22
|
-
targetModel,
|
|
23
|
-
foreignKey,
|
|
24
|
-
localKey,
|
|
25
|
-
});
|
|
26
|
-
Object.defineProperty(target, propertyKey, {
|
|
27
|
-
get() {
|
|
28
|
-
const cached = this[`_${propertyKey}`];
|
|
29
|
-
return cached !== undefined
|
|
30
|
-
? cached
|
|
31
|
-
: (console.warn(`Relación ${propertyKey} no cargada. Use includes en la consulta.`),
|
|
32
|
-
[]);
|
|
33
|
-
},
|
|
34
|
-
configurable: true,
|
|
35
|
-
enumerable: false,
|
|
36
|
-
});
|
|
37
|
-
};
|
|
38
|
-
exports.hasMany = hasMany;
|
|
39
|
-
/** Decorador @belongsTo para relaciones N:1 */
|
|
40
|
-
const belongsTo = (targetModel, localKey, foreignKey = "id") => (target, propertyKey) => {
|
|
41
|
-
(0, wrapper_1.ensureConfig)(target.constructor, (0, naming_1.toSnakePlural)(target.constructor.name)).relations.set(propertyKey, {
|
|
42
|
-
type: "belongsTo",
|
|
43
|
-
targetModel,
|
|
44
|
-
localKey,
|
|
45
|
-
foreignKey,
|
|
46
|
-
});
|
|
47
|
-
Object.defineProperty(target, propertyKey, {
|
|
48
|
-
get() {
|
|
49
|
-
const cached = this[`_${propertyKey}`];
|
|
50
|
-
return cached !== undefined
|
|
51
|
-
? cached
|
|
52
|
-
: (console.warn(`Relación ${propertyKey} no cargada. Use includes en la consulta.`),
|
|
53
|
-
null);
|
|
54
|
-
},
|
|
55
|
-
configurable: true,
|
|
56
|
-
enumerable: false,
|
|
57
|
-
});
|
|
58
|
-
};
|
|
59
|
-
exports.belongsTo = belongsTo;
|
|
60
|
-
// =============================================================================
|
|
61
|
-
// FUNCTIONS
|
|
62
|
-
// =============================================================================
|
|
63
|
-
/** Batch loading para relaciones hasMany */
|
|
64
|
-
const batchLoadHasMany = async (Model, items, relation, options = {}) => {
|
|
65
|
-
const { targetModel, foreignKey, localKey = "id" } = relation;
|
|
66
|
-
const parent_keys = items.map((item) => item[localKey]).filter(Boolean);
|
|
67
|
-
if (!parent_keys.length)
|
|
68
|
-
return new Map();
|
|
69
|
-
// Build query with relation options
|
|
70
|
-
let query = targetModel().where(foreignKey, "in", parent_keys);
|
|
71
|
-
// Apply additional filters if specified
|
|
72
|
-
if (options.where) {
|
|
73
|
-
const additionalFilters = Object.entries(options.where);
|
|
74
|
-
for (const [key, value] of additionalFilters) {
|
|
75
|
-
const currentResults = await query;
|
|
76
|
-
query = Promise.resolve(currentResults.filter((item) => item[key] === value));
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
const related_items = await query;
|
|
80
|
-
// TODO: Apply attributes selection
|
|
81
|
-
// For now, skip attributes filtering to ensure basic relations work
|
|
82
|
-
let processedItems = related_items;
|
|
83
|
-
// Apply other options like limit, order
|
|
84
|
-
let filteredItems = processedItems;
|
|
85
|
-
if (options.order === "DESC") {
|
|
86
|
-
filteredItems.sort((a, b) => b.id.localeCompare(a.id));
|
|
87
|
-
}
|
|
88
|
-
else if (options.order === "ASC") {
|
|
89
|
-
filteredItems.sort((a, b) => a.id.localeCompare(b.id));
|
|
90
|
-
}
|
|
91
|
-
if (options.limit) {
|
|
92
|
-
filteredItems = filteredItems.slice(0, options.limit);
|
|
93
|
-
}
|
|
94
|
-
const grouped = new Map();
|
|
95
|
-
filteredItems.forEach((item) => {
|
|
96
|
-
const key = item[foreignKey];
|
|
97
|
-
grouped.has(key) ? grouped.get(key).push(item) : grouped.set(key, [item]);
|
|
98
|
-
});
|
|
99
|
-
return grouped;
|
|
100
|
-
};
|
|
101
|
-
/** Batch loading para relaciones belongsTo */
|
|
102
|
-
const batchLoadBelongsTo = async (Model, items, relation, options = {}) => {
|
|
103
|
-
const { targetModel, localKey, foreignKey = "id" } = relation;
|
|
104
|
-
// Para BelongsTo: obtener valores de localKey (ej: category_id) de los items
|
|
105
|
-
const keys = items.map((item) => localKey ? item[localKey] : null).filter(Boolean);
|
|
106
|
-
if (!keys.length)
|
|
107
|
-
return new Map();
|
|
108
|
-
// Buscar en targetModel donde foreignKey (ej: id) esté en los keys
|
|
109
|
-
const fetched_items = await targetModel().where(foreignKey, "in", keys);
|
|
110
|
-
// TODO: Apply attributes selection
|
|
111
|
-
// For now, skip attributes filtering to ensure basic relations work
|
|
112
|
-
let processedItems = fetched_items;
|
|
113
|
-
const results = new Map();
|
|
114
|
-
// Mapear por foreignKey para que coincida con localKey de los items
|
|
115
|
-
processedItems.forEach((item) => results.set(item[foreignKey], item));
|
|
116
|
-
return results;
|
|
117
|
-
};
|
|
118
|
-
/** Procesamiento optimizado de includes con batch loading transparente */
|
|
119
|
-
const processIncludes = async (Model, items, include, depth = 0) => {
|
|
120
|
-
if (!include || depth > 10 || !items.length)
|
|
121
|
-
return items;
|
|
122
|
-
const meta = (0, wrapper_1.mustMeta)(Model);
|
|
123
|
-
const relation_promises = Object.entries(include).map(async ([relation_key, relation_options]) => {
|
|
124
|
-
const relation = meta.relations.get(relation_key);
|
|
125
|
-
if (!relation)
|
|
126
|
-
return;
|
|
127
|
-
const related_data = relation.type === "hasMany"
|
|
128
|
-
? await batchLoadHasMany(Model, items, relation, relation_options)
|
|
129
|
-
: await batchLoadBelongsTo(Model, items, relation, relation_options);
|
|
130
|
-
items.forEach((item) => {
|
|
131
|
-
let key;
|
|
132
|
-
if (relation.type === "hasMany") {
|
|
133
|
-
// Para HasMany: usar localKey (ej: "id") del item actual
|
|
134
|
-
key = item[relation.localKey || "id"];
|
|
135
|
-
}
|
|
136
|
-
else {
|
|
137
|
-
// Para BelongsTo: usar localKey (ej: "category_id") del item actual
|
|
138
|
-
key = relation.localKey ? item[relation.localKey] : null;
|
|
139
|
-
}
|
|
140
|
-
const related = related_data.get(key);
|
|
141
|
-
// Usar una propiedad temporal para evitar conflictos con getters
|
|
142
|
-
Object.defineProperty(item, relation_key, {
|
|
143
|
-
value: relation.type === "hasMany" ? related || [] : related || null,
|
|
144
|
-
writable: true,
|
|
145
|
-
enumerable: true,
|
|
146
|
-
configurable: true
|
|
147
|
-
});
|
|
148
|
-
});
|
|
149
|
-
if (relation_options?.include && related_data.size) {
|
|
150
|
-
const all_related = Array.from(related_data.values())
|
|
151
|
-
.flat()
|
|
152
|
-
.filter(Boolean);
|
|
153
|
-
await (0, exports.processIncludes)(relation.targetModel(), all_related, relation_options.include, depth + 1);
|
|
154
|
-
}
|
|
155
|
-
});
|
|
156
|
-
await Promise.all(relation_promises);
|
|
157
|
-
return items;
|
|
158
|
-
};
|
|
159
|
-
exports.processIncludes = processIncludes;
|
|
160
|
-
/** Separar opciones de query e include */
|
|
161
|
-
const separateQueryOptions = (options) => {
|
|
162
|
-
const { include, ...queryOptions } = options;
|
|
163
|
-
return { queryOptions, includeOptions: include };
|
|
164
|
-
};
|
|
165
|
-
exports.separateQueryOptions = separateQueryOptions;
|
|
166
|
-
//# sourceMappingURL=relations.js.map
|
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @file security-validator.ts
|
|
3
|
-
* @description Security validation and NoSQL injection prevention
|
|
4
|
-
* @author Miguel Alejandro
|
|
5
|
-
* @fecha 2025-08-31
|
|
6
|
-
*/
|
|
7
|
-
import { QueryOperator } from "../@types/index";
|
|
8
|
-
interface SecurityConfig {
|
|
9
|
-
maxStringLength: number;
|
|
10
|
-
maxArrayLength: number;
|
|
11
|
-
maxNestedDepth: number;
|
|
12
|
-
allowedOperators: QueryOperator[];
|
|
13
|
-
blockedPatterns: RegExp[];
|
|
14
|
-
}
|
|
15
|
-
declare class SecurityValidator {
|
|
16
|
-
private static readonly DEFAULT_CONFIG;
|
|
17
|
-
private config;
|
|
18
|
-
constructor(config?: Partial<SecurityConfig>);
|
|
19
|
-
/**
|
|
20
|
-
* Validar nombre de atributo/tabla
|
|
21
|
-
*/
|
|
22
|
-
validateAttributeName(name: string): void;
|
|
23
|
-
/**
|
|
24
|
-
* Validar operador de query
|
|
25
|
-
*/
|
|
26
|
-
validateOperator(operator: string): QueryOperator;
|
|
27
|
-
/**
|
|
28
|
-
* Validar valor de campo
|
|
29
|
-
*/
|
|
30
|
-
validateValue(value: any, depth?: number): any;
|
|
31
|
-
/**
|
|
32
|
-
* Validar filtros de query completos
|
|
33
|
-
*/
|
|
34
|
-
validateQueryFilters(filters: Record<string, any>): Record<string, any>;
|
|
35
|
-
/**
|
|
36
|
-
* Sanitizar string para DynamoDB
|
|
37
|
-
*/
|
|
38
|
-
sanitizeString(input: string): string;
|
|
39
|
-
/**
|
|
40
|
-
* Validar tamaño de item para DynamoDB (límite 400KB)
|
|
41
|
-
*/
|
|
42
|
-
validateItemSize(item: any): void;
|
|
43
|
-
}
|
|
44
|
-
declare class SecurityError extends Error {
|
|
45
|
-
constructor(message: string);
|
|
46
|
-
}
|
|
47
|
-
declare const securityValidator: SecurityValidator;
|
|
48
|
-
export { SecurityValidator, SecurityError, securityValidator };
|
|
49
|
-
export default securityValidator;
|
|
@@ -1,152 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* @file security-validator.ts
|
|
4
|
-
* @description Security validation and NoSQL injection prevention
|
|
5
|
-
* @author Miguel Alejandro
|
|
6
|
-
* @fecha 2025-08-31
|
|
7
|
-
*/
|
|
8
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
-
exports.securityValidator = exports.SecurityError = exports.SecurityValidator = void 0;
|
|
10
|
-
class SecurityValidator {
|
|
11
|
-
static { this.DEFAULT_CONFIG = {
|
|
12
|
-
maxStringLength: 10000,
|
|
13
|
-
maxArrayLength: 1000,
|
|
14
|
-
maxNestedDepth: 10,
|
|
15
|
-
allowedOperators: ["=", "!=", "<", "<=", ">", ">=", "in", "not-in", "contains", "begins-with"],
|
|
16
|
-
blockedPatterns: [
|
|
17
|
-
/\$\w+/g, // MongoDB operators
|
|
18
|
-
/javascript:/gi, // JavaScript injection
|
|
19
|
-
/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, // Script tags
|
|
20
|
-
/eval\s*\(/gi, // eval() calls
|
|
21
|
-
/function\s*\(/gi, // function declarations
|
|
22
|
-
/\{\s*\$\w+/g, // NoSQL operators
|
|
23
|
-
/\.\.\//g, // Path traversal
|
|
24
|
-
/union\s+select/gi, // SQL injection patterns
|
|
25
|
-
/drop\s+table/gi, // Destructive SQL
|
|
26
|
-
]
|
|
27
|
-
}; }
|
|
28
|
-
constructor(config) {
|
|
29
|
-
this.config = { ...SecurityValidator.DEFAULT_CONFIG, ...config };
|
|
30
|
-
}
|
|
31
|
-
/**
|
|
32
|
-
* Validar nombre de atributo/tabla
|
|
33
|
-
*/
|
|
34
|
-
validateAttributeName(name) {
|
|
35
|
-
if (!name || typeof name !== 'string') {
|
|
36
|
-
throw new SecurityError('Nombre de atributo inválido');
|
|
37
|
-
}
|
|
38
|
-
if (name.length > 255) {
|
|
39
|
-
throw new SecurityError('Nombre de atributo muy largo');
|
|
40
|
-
}
|
|
41
|
-
// Solo permitir caracteres alfanuméricos, guiones y guiones bajos
|
|
42
|
-
if (!/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(name)) {
|
|
43
|
-
throw new SecurityError('Nombre de atributo contiene caracteres inválidos');
|
|
44
|
-
}
|
|
45
|
-
// Verificar patrones bloqueados
|
|
46
|
-
for (const pattern of this.config.blockedPatterns) {
|
|
47
|
-
if (pattern.test(name)) {
|
|
48
|
-
throw new SecurityError('Nombre de atributo contiene patrones peligrosos');
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
/**
|
|
53
|
-
* Validar operador de query
|
|
54
|
-
*/
|
|
55
|
-
validateOperator(operator) {
|
|
56
|
-
if (!this.config.allowedOperators.includes(operator)) {
|
|
57
|
-
throw new SecurityError(`Operador no permitido: ${operator}`);
|
|
58
|
-
}
|
|
59
|
-
return operator;
|
|
60
|
-
}
|
|
61
|
-
/**
|
|
62
|
-
* Validar valor de campo
|
|
63
|
-
*/
|
|
64
|
-
validateValue(value, depth = 0) {
|
|
65
|
-
if (depth > this.config.maxNestedDepth) {
|
|
66
|
-
throw new SecurityError('Estructura de datos anidada muy profunda');
|
|
67
|
-
}
|
|
68
|
-
// Valores null/undefined son válidos
|
|
69
|
-
if (value === null || value === undefined) {
|
|
70
|
-
return value;
|
|
71
|
-
}
|
|
72
|
-
// Validar strings
|
|
73
|
-
if (typeof value === 'string') {
|
|
74
|
-
if (value.length > this.config.maxStringLength) {
|
|
75
|
-
throw new SecurityError('String muy largo');
|
|
76
|
-
}
|
|
77
|
-
for (const pattern of this.config.blockedPatterns) {
|
|
78
|
-
if (pattern.test(value)) {
|
|
79
|
-
throw new SecurityError('Valor contiene patrones peligrosos');
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
return value;
|
|
83
|
-
}
|
|
84
|
-
// Validar arrays
|
|
85
|
-
if (Array.isArray(value)) {
|
|
86
|
-
if (value.length > this.config.maxArrayLength) {
|
|
87
|
-
throw new SecurityError('Array muy largo');
|
|
88
|
-
}
|
|
89
|
-
return value.map(item => this.validateValue(item, depth + 1));
|
|
90
|
-
}
|
|
91
|
-
// Validar objetos
|
|
92
|
-
if (typeof value === 'object') {
|
|
93
|
-
const validated = {};
|
|
94
|
-
for (const [key, val] of Object.entries(value)) {
|
|
95
|
-
this.validateAttributeName(key);
|
|
96
|
-
validated[key] = this.validateValue(val, depth + 1);
|
|
97
|
-
}
|
|
98
|
-
return validated;
|
|
99
|
-
}
|
|
100
|
-
// Números, booleans son válidos
|
|
101
|
-
if (typeof value === 'number' || typeof value === 'boolean') {
|
|
102
|
-
return value;
|
|
103
|
-
}
|
|
104
|
-
throw new SecurityError(`Tipo de valor no permitido: ${typeof value}`);
|
|
105
|
-
}
|
|
106
|
-
/**
|
|
107
|
-
* Validar filtros de query completos
|
|
108
|
-
*/
|
|
109
|
-
validateQueryFilters(filters) {
|
|
110
|
-
const validated = {};
|
|
111
|
-
for (const [key, value] of Object.entries(filters)) {
|
|
112
|
-
this.validateAttributeName(key);
|
|
113
|
-
validated[key] = this.validateValue(value);
|
|
114
|
-
}
|
|
115
|
-
return validated;
|
|
116
|
-
}
|
|
117
|
-
/**
|
|
118
|
-
* Sanitizar string para DynamoDB
|
|
119
|
-
*/
|
|
120
|
-
sanitizeString(input) {
|
|
121
|
-
if (typeof input !== 'string') {
|
|
122
|
-
return String(input);
|
|
123
|
-
}
|
|
124
|
-
return input
|
|
125
|
-
.replace(/[\x00-\x1F\x7F]/g, '') // Remover caracteres de control
|
|
126
|
-
.trim()
|
|
127
|
-
.slice(0, this.config.maxStringLength);
|
|
128
|
-
}
|
|
129
|
-
/**
|
|
130
|
-
* Validar tamaño de item para DynamoDB (límite 400KB)
|
|
131
|
-
*/
|
|
132
|
-
validateItemSize(item) {
|
|
133
|
-
const size = JSON.stringify(item).length;
|
|
134
|
-
const maxSize = 400 * 1024; // 400KB en bytes
|
|
135
|
-
if (size > maxSize) {
|
|
136
|
-
throw new SecurityError(`Item muy grande: ${size} bytes (máximo: ${maxSize} bytes)`);
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
exports.SecurityValidator = SecurityValidator;
|
|
141
|
-
class SecurityError extends Error {
|
|
142
|
-
constructor(message) {
|
|
143
|
-
super(message);
|
|
144
|
-
this.name = 'SecurityError';
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
exports.SecurityError = SecurityError;
|
|
148
|
-
// Instancia singleton
|
|
149
|
-
const securityValidator = new SecurityValidator();
|
|
150
|
-
exports.securityValidator = securityValidator;
|
|
151
|
-
exports.default = securityValidator;
|
|
152
|
-
//# sourceMappingURL=security-validator.js.map
|
|
@@ -1,78 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @file throttle-manager.ts
|
|
3
|
-
* @description AWS DynamoDB throttling and retry management
|
|
4
|
-
* @author Miguel Alejandro
|
|
5
|
-
* @fecha 2025-08-31
|
|
6
|
-
*/
|
|
7
|
-
interface RetryConfig {
|
|
8
|
-
maxRetries: number;
|
|
9
|
-
baseDelay: number;
|
|
10
|
-
maxDelay: number;
|
|
11
|
-
backoffMultiplier: number;
|
|
12
|
-
jitterFactor: number;
|
|
13
|
-
}
|
|
14
|
-
interface ThrottleStats {
|
|
15
|
-
totalRequests: number;
|
|
16
|
-
throttledRequests: number;
|
|
17
|
-
retriedRequests: number;
|
|
18
|
-
averageLatency: number;
|
|
19
|
-
}
|
|
20
|
-
declare class ThrottleManager {
|
|
21
|
-
private static readonly DEFAULT_CONFIG;
|
|
22
|
-
private config;
|
|
23
|
-
private stats;
|
|
24
|
-
private requestQueue;
|
|
25
|
-
private isProcessingQueue;
|
|
26
|
-
private concurrentRequests;
|
|
27
|
-
private maxConcurrentRequests;
|
|
28
|
-
constructor(config?: Partial<RetryConfig>);
|
|
29
|
-
/**
|
|
30
|
-
* Ejecutar operación con retry automático
|
|
31
|
-
*/
|
|
32
|
-
executeWithRetry<T>(operation: () => Promise<T>, operationName?: string): Promise<T>;
|
|
33
|
-
/**
|
|
34
|
-
* Verificar si el error es reintentable
|
|
35
|
-
*/
|
|
36
|
-
private isRetryableError;
|
|
37
|
-
/**
|
|
38
|
-
* Calcular delay con exponential backoff + jitter
|
|
39
|
-
*/
|
|
40
|
-
private calculateDelay;
|
|
41
|
-
/**
|
|
42
|
-
* Controlar concurrencia de requests
|
|
43
|
-
*/
|
|
44
|
-
private acquireConcurrencySlot;
|
|
45
|
-
private releaseConcurrencySlot;
|
|
46
|
-
/**
|
|
47
|
-
* Queue para operaciones batch con rate limiting
|
|
48
|
-
*/
|
|
49
|
-
queueOperation<T>(operation: () => Promise<T>): Promise<T>;
|
|
50
|
-
private processQueue;
|
|
51
|
-
/**
|
|
52
|
-
* Obtener estadísticas de throttling
|
|
53
|
-
*/
|
|
54
|
-
getStats(): ThrottleStats;
|
|
55
|
-
/**
|
|
56
|
-
* Resetear estadísticas
|
|
57
|
-
*/
|
|
58
|
-
resetStats(): void;
|
|
59
|
-
private updateLatencyStats;
|
|
60
|
-
private sleep;
|
|
61
|
-
/**
|
|
62
|
-
* Configurar límites de concurrencia dinámicamente
|
|
63
|
-
*/
|
|
64
|
-
setConcurrencyLimit(limit: number): void;
|
|
65
|
-
/**
|
|
66
|
-
* Obtener métricas de salud del throttling
|
|
67
|
-
*/
|
|
68
|
-
getHealthMetrics(): {
|
|
69
|
-
throttleRate: number;
|
|
70
|
-
retryRate: number;
|
|
71
|
-
avgLatency: number;
|
|
72
|
-
concurrentRequests: number;
|
|
73
|
-
queueSize: number;
|
|
74
|
-
};
|
|
75
|
-
}
|
|
76
|
-
declare const throttleManager: ThrottleManager;
|
|
77
|
-
export { ThrottleManager, RetryConfig, ThrottleStats, throttleManager };
|
|
78
|
-
export default throttleManager;
|
|
@@ -1,196 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* @file throttle-manager.ts
|
|
4
|
-
* @description AWS DynamoDB throttling and retry management
|
|
5
|
-
* @author Miguel Alejandro
|
|
6
|
-
* @fecha 2025-08-31
|
|
7
|
-
*/
|
|
8
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
-
exports.throttleManager = exports.ThrottleManager = void 0;
|
|
10
|
-
class ThrottleManager {
|
|
11
|
-
static { this.DEFAULT_CONFIG = {
|
|
12
|
-
maxRetries: 10,
|
|
13
|
-
baseDelay: 100, // 100ms base delay
|
|
14
|
-
maxDelay: 30000, // 30s max delay
|
|
15
|
-
backoffMultiplier: 2, // Exponential backoff
|
|
16
|
-
jitterFactor: 0.1, // 10% jitter
|
|
17
|
-
}; }
|
|
18
|
-
constructor(config) {
|
|
19
|
-
this.requestQueue = [];
|
|
20
|
-
this.isProcessingQueue = false;
|
|
21
|
-
this.concurrentRequests = 0;
|
|
22
|
-
this.maxConcurrentRequests = 25; // DynamoDB default
|
|
23
|
-
this.config = { ...ThrottleManager.DEFAULT_CONFIG, ...config };
|
|
24
|
-
this.stats = {
|
|
25
|
-
totalRequests: 0,
|
|
26
|
-
throttledRequests: 0,
|
|
27
|
-
retriedRequests: 0,
|
|
28
|
-
averageLatency: 0,
|
|
29
|
-
};
|
|
30
|
-
}
|
|
31
|
-
/**
|
|
32
|
-
* Ejecutar operación con retry automático
|
|
33
|
-
*/
|
|
34
|
-
async executeWithRetry(operation, operationName = 'DynamoDB Operation') {
|
|
35
|
-
const startTime = Date.now();
|
|
36
|
-
let lastError = null;
|
|
37
|
-
this.stats.totalRequests++;
|
|
38
|
-
for (let attempt = 0; attempt <= this.config.maxRetries; attempt++) {
|
|
39
|
-
try {
|
|
40
|
-
// Control de concurrencia
|
|
41
|
-
await this.acquireConcurrencySlot();
|
|
42
|
-
const result = await operation();
|
|
43
|
-
this.releaseConcurrencySlot();
|
|
44
|
-
this.updateLatencyStats(Date.now() - startTime);
|
|
45
|
-
if (attempt > 0) {
|
|
46
|
-
console.log(`✅ ${operationName} succeeded after ${attempt} retries`);
|
|
47
|
-
}
|
|
48
|
-
return result;
|
|
49
|
-
}
|
|
50
|
-
catch (error) {
|
|
51
|
-
this.releaseConcurrencySlot();
|
|
52
|
-
lastError = error;
|
|
53
|
-
// Verificar si es un error que podemos reintentar
|
|
54
|
-
if (!this.isRetryableError(error)) {
|
|
55
|
-
throw error;
|
|
56
|
-
}
|
|
57
|
-
this.stats.throttledRequests++;
|
|
58
|
-
if (attempt === this.config.maxRetries) {
|
|
59
|
-
console.error(`❌ ${operationName} failed after ${this.config.maxRetries} retries:`, error.message);
|
|
60
|
-
throw new Error(`Max retries exceeded for ${operationName}: ${error.message}`);
|
|
61
|
-
}
|
|
62
|
-
this.stats.retriedRequests++;
|
|
63
|
-
const delay = this.calculateDelay(attempt);
|
|
64
|
-
console.warn(`⚠️ ${operationName} throttled, retrying in ${delay}ms (attempt ${attempt + 1}/${this.config.maxRetries})`);
|
|
65
|
-
await this.sleep(delay);
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
throw lastError;
|
|
69
|
-
}
|
|
70
|
-
/**
|
|
71
|
-
* Verificar si el error es reintentable
|
|
72
|
-
*/
|
|
73
|
-
isRetryableError(error) {
|
|
74
|
-
if (!error.name)
|
|
75
|
-
return false;
|
|
76
|
-
const retryableErrors = [
|
|
77
|
-
'ProvisionedThroughputExceededException',
|
|
78
|
-
'ThrottlingException',
|
|
79
|
-
'RequestLimitExceeded',
|
|
80
|
-
'ServiceUnavailableException',
|
|
81
|
-
'InternalServerError',
|
|
82
|
-
'NetworkingError',
|
|
83
|
-
'TimeoutError',
|
|
84
|
-
];
|
|
85
|
-
return retryableErrors.includes(error.name) || error.retryable === true;
|
|
86
|
-
}
|
|
87
|
-
/**
|
|
88
|
-
* Calcular delay con exponential backoff + jitter
|
|
89
|
-
*/
|
|
90
|
-
calculateDelay(attempt) {
|
|
91
|
-
const exponentialDelay = this.config.baseDelay * Math.pow(this.config.backoffMultiplier, attempt);
|
|
92
|
-
const cappedDelay = Math.min(exponentialDelay, this.config.maxDelay);
|
|
93
|
-
// Agregar jitter para evitar "thundering herd"
|
|
94
|
-
const jitter = cappedDelay * this.config.jitterFactor * Math.random();
|
|
95
|
-
return Math.floor(cappedDelay + jitter);
|
|
96
|
-
}
|
|
97
|
-
/**
|
|
98
|
-
* Controlar concurrencia de requests
|
|
99
|
-
*/
|
|
100
|
-
async acquireConcurrencySlot() {
|
|
101
|
-
while (this.concurrentRequests >= this.maxConcurrentRequests) {
|
|
102
|
-
await this.sleep(10); // Esperar 10ms
|
|
103
|
-
}
|
|
104
|
-
this.concurrentRequests++;
|
|
105
|
-
}
|
|
106
|
-
releaseConcurrencySlot() {
|
|
107
|
-
this.concurrentRequests = Math.max(0, this.concurrentRequests - 1);
|
|
108
|
-
}
|
|
109
|
-
/**
|
|
110
|
-
* Queue para operaciones batch con rate limiting
|
|
111
|
-
*/
|
|
112
|
-
async queueOperation(operation) {
|
|
113
|
-
return new Promise((resolve, reject) => {
|
|
114
|
-
this.requestQueue.push(async () => {
|
|
115
|
-
try {
|
|
116
|
-
const result = await this.executeWithRetry(operation);
|
|
117
|
-
resolve(result);
|
|
118
|
-
}
|
|
119
|
-
catch (error) {
|
|
120
|
-
reject(error);
|
|
121
|
-
}
|
|
122
|
-
});
|
|
123
|
-
this.processQueue();
|
|
124
|
-
});
|
|
125
|
-
}
|
|
126
|
-
async processQueue() {
|
|
127
|
-
if (this.isProcessingQueue || this.requestQueue.length === 0) {
|
|
128
|
-
return;
|
|
129
|
-
}
|
|
130
|
-
this.isProcessingQueue = true;
|
|
131
|
-
while (this.requestQueue.length > 0) {
|
|
132
|
-
const operation = this.requestQueue.shift();
|
|
133
|
-
try {
|
|
134
|
-
await operation();
|
|
135
|
-
}
|
|
136
|
-
catch (error) {
|
|
137
|
-
console.error('Queue operation failed:', error);
|
|
138
|
-
}
|
|
139
|
-
// Rate limiting: pequeña pausa entre operaciones
|
|
140
|
-
if (this.requestQueue.length > 0) {
|
|
141
|
-
await this.sleep(50); // 50ms entre requests
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
this.isProcessingQueue = false;
|
|
145
|
-
}
|
|
146
|
-
/**
|
|
147
|
-
* Obtener estadísticas de throttling
|
|
148
|
-
*/
|
|
149
|
-
getStats() {
|
|
150
|
-
return { ...this.stats };
|
|
151
|
-
}
|
|
152
|
-
/**
|
|
153
|
-
* Resetear estadísticas
|
|
154
|
-
*/
|
|
155
|
-
resetStats() {
|
|
156
|
-
this.stats = {
|
|
157
|
-
totalRequests: 0,
|
|
158
|
-
throttledRequests: 0,
|
|
159
|
-
retriedRequests: 0,
|
|
160
|
-
averageLatency: 0,
|
|
161
|
-
};
|
|
162
|
-
}
|
|
163
|
-
updateLatencyStats(latency) {
|
|
164
|
-
const totalRequests = this.stats.totalRequests;
|
|
165
|
-
this.stats.averageLatency =
|
|
166
|
-
((this.stats.averageLatency * (totalRequests - 1)) + latency) / totalRequests;
|
|
167
|
-
}
|
|
168
|
-
sleep(ms) {
|
|
169
|
-
return new Promise(resolve => setTimeout(resolve, ms));
|
|
170
|
-
}
|
|
171
|
-
/**
|
|
172
|
-
* Configurar límites de concurrencia dinámicamente
|
|
173
|
-
*/
|
|
174
|
-
setConcurrencyLimit(limit) {
|
|
175
|
-
this.maxConcurrentRequests = Math.max(1, Math.min(limit, 100));
|
|
176
|
-
}
|
|
177
|
-
/**
|
|
178
|
-
* Obtener métricas de salud del throttling
|
|
179
|
-
*/
|
|
180
|
-
getHealthMetrics() {
|
|
181
|
-
const stats = this.getStats();
|
|
182
|
-
return {
|
|
183
|
-
throttleRate: stats.totalRequests > 0 ? stats.throttledRequests / stats.totalRequests : 0,
|
|
184
|
-
retryRate: stats.totalRequests > 0 ? stats.retriedRequests / stats.totalRequests : 0,
|
|
185
|
-
avgLatency: stats.averageLatency,
|
|
186
|
-
concurrentRequests: this.concurrentRequests,
|
|
187
|
-
queueSize: this.requestQueue.length,
|
|
188
|
-
};
|
|
189
|
-
}
|
|
190
|
-
}
|
|
191
|
-
exports.ThrottleManager = ThrottleManager;
|
|
192
|
-
// Instancia singleton
|
|
193
|
-
const throttleManager = new ThrottleManager();
|
|
194
|
-
exports.throttleManager = throttleManager;
|
|
195
|
-
exports.default = throttleManager;
|
|
196
|
-
//# sourceMappingURL=throttle-manager.js.map
|