-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path05_GracefulDegradation.gs
More file actions
710 lines (602 loc) · 20 KB
/
Copy path05_GracefulDegradation.gs
File metadata and controls
710 lines (602 loc) · 20 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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
/**
* @file 05_GracefulDegradation.gs
* @description Sistema de Degradação Graciosa para resiliência do sistema
* @version 1.0.0
* @author Sistema TE-DF-PP
* @since 2025-12-14
*
* FUNCIONALIDADES:
* - Fallback automático para operações críticas
* - Modo offline com sincronização posterior
* - Cache de emergência para dados críticos
* - Recuperação automática de serviços
* - Priorização de operações em modo degradado
*/
// ============================================================================
// CONFIGURAÇÃO DE DEGRADAÇÃO
// ============================================================================
const DEGRADATION_CONFIG = Object.freeze({
// Níveis de degradação
LEVELS: {
NORMAL: 'NORMAL', // Sistema operando normalmente
DEGRADED: 'DEGRADED', // Funcionalidades reduzidas
EMERGENCY: 'EMERGENCY', // Apenas operações críticas
OFFLINE: 'OFFLINE' // Modo offline
},
// Prioridades de operação
PRIORITIES: {
CRITICAL: 1, // Autenticação, dados de sessão
HIGH: 2, // CRUD principal
MEDIUM: 3, // Relatórios, exportações
LOW: 4 // Logs, telemetria
},
// Timeouts por nível
TIMEOUTS: {
NORMAL: 30000, // 30s
DEGRADED: 15000, // 15s
EMERGENCY: 5000, // 5s
OFFLINE: 1000 // 1s (apenas cache)
},
// Cache de emergência
EMERGENCY_CACHE_TTL: 3600, // 1 hora
// Retry em modo degradado
DEGRADED_MAX_RETRIES: 1,
// Operações permitidas por nível
ALLOWED_OPERATIONS: {
NORMAL: ['*'],
DEGRADED: ['auth', 'read', 'create', 'update'],
EMERGENCY: ['auth', 'read'],
OFFLINE: ['read_cache']
}
});
// ============================================================================
// GRACEFUL DEGRADATION SERVICE
// ============================================================================
const GracefulDegradation = (function() {
'use strict';
// Estado atual do sistema
let currentLevel = DEGRADATION_CONFIG.LEVELS.NORMAL;
let lastHealthCheck = null;
let failureCount = 0;
let recoveryAttempts = 0;
// Cache de emergência
const emergencyCache = CacheService.getScriptCache();
// Métricas
const metrics = {
degradations: 0,
recoveries: 0,
fallbacksUsed: 0,
operationsBlocked: 0
};
// ============================================================================
// CORE FUNCTIONS
// ============================================================================
/**
* Obtém nível atual de degradação
* @return {string} Nível atual
*/
function getCurrentLevel() {
return currentLevel;
}
/**
* Define nível de degradação
* @param {string} level - Novo nível
* @param {string} reason - Motivo da mudança
*/
function setLevel(level, reason) {
const oldLevel = currentLevel;
currentLevel = level;
if (oldLevel !== level) {
_logLevelChange(oldLevel, level, reason);
if (_isMoreDegraded(level, oldLevel)) {
metrics.degradations++;
} else {
metrics.recoveries++;
}
}
}
/**
* Executa operação com degradação graciosa
* @param {Object} options - Opções da operação
* @param {Function} options.operation - Operação principal
* @param {Function} options.fallback - Operação de fallback
* @param {string} options.type - Tipo da operação (auth, read, write, etc)
* @param {number} options.priority - Prioridade (1-4)
* @param {string} options.cacheKey - Chave para cache de emergência
10BC0
* @return {Object} Resultado da operação
*/
function execute(options) {
const { operation, fallback, type, priority, cacheKey } = options;
// Verifica se operação é permitida no nível atual
if (!_isOperationAllowed(type)) {
metrics.operationsBlocked++;
return _createBlockedResponse(type);
}
// Obtém timeout baseado no nível
const timeout = _getTimeout();
try {
// Tenta operação principal
const result = _executeWithTimeout(operation, timeout);
// Sucesso - atualiza cache de emergência se aplicável
if (cacheKey && result.success) {
_updateEmergencyCache(cacheKey, result.data);
}
// Considera recuperação se estava degradado
_considerRecovery();
return result;
} catch (error) {
// Falha - incrementa contador
failureCount++;
// Avalia se deve degradar
_evaluateDegradation(error);
// Tenta fallback
if (fallback && typeof fallback === 'function') {
try {
metrics.fallbacksUsed++;
const fallbackResult = fallback(error);
return {
success: true,
data: fallbackResult,
source: 'fallback',
originalError: error.message
};
} catch (fallbackError) {
// Fallback também falhou
}
}
// Tenta cache de emergência
if (cacheKey) {
const cached = _getFromEmergencyCache(cacheKey);
if (cached) {
return {
success: true,
data: cached,
source: 'emergency_cache',
stale: true,
originalError: error.message
};
}
}
// Nenhuma alternativa disponível
return {
success: false,
error: error.message,
level: currentLevel
};
}
}
/**
* Wrapper para operações de leitura com fallback automático
* @param {Function} readOperation - Operação de leitura
* @param {string} cacheKey - Chave do cache
* @param {*} defaultValue - Valor padrão se tudo falhar
* @return {*} Dados lidos ou fallback
*/
function safeRead(readOperation, cacheKey, defaultValue) {
return execute({
operation: readOperation,
fallback: () => defaultValue,
type: 'read',
priority: DEGRADATION_CONFIG.PRIORITIES.HIGH,
cacheKey: cacheKey
});
}
/**
* Wrapper para operações de escrita com queue offline
* @param {Function} writeOperation - Operação de escrita
* @param {Object} data - Dados a serem escritos
* @param {string} entityType - Tipo da entidade
* @return {Object} Resultado
*/
function safeWrite(writeOperation, data, entityType) {
if (currentLevel === DEGRADATION_CONFIG.LEVELS.OFFLINE) {
// Em modo offline, adiciona à fila
_queueOfflineOperation('write', entityType, data);
return {
success: true,
queued: true,
message: 'Operação adicionada à fila offline'
};
}
return execute({
operation: writeOperation,
fallback: () => {
_queueOfflineOperation('write', entityType, data);
return { queued: true };
},
type: 'write',
priority: DEGRADATION_CONFIG.PRIORITIES.HIGH
});
}
// ============================================================================
// HEALTH MONITORING
// ============================================================================
/**
* Executa verificação de saúde e ajusta nível
* @return {Object} Status de saúde
*/
function checkHealth() {
try {
const checks = {
spreadsheet: _checkSpreadsheetHealth(),
cache: _checkCacheHealth(),
properties: _checkPropertiesHealth()
};
lastHealthCheck = {
timestamp: new Date().toISOString(),
checks: checks
};
// Determina nível baseado nos checks
const failedChecks = Object.values(checks).filter(c => !c.healthy).length;
if (failedChecks === 0) {
setLevel(DEGRADATION_CONFIG.LEVELS.NORMAL, 'All health checks passed');
} else if (failedChecks === 1) {
setLevel(DEGRADATION_CONFIG.LEVELS.DEGRADED, 'One service degraded');
} else if (failedChecks === 2) {
setLevel(DEGRADATION_CONFIG.LEVELS.EMERGENCY, 'Multiple services failing');
} else {
setLevel(DEGRADATION_CONFIG.LEVELS.OFFLINE, 'Critical failure');
}
return {
level: currentLevel,
checks: checks,
timestamp: lastHealthCheck.timestamp
};
} catch (error) {
setLevel(DEGRADATION_CONFIG.LEVELS.EMERGENCY, 'Health check failed: ' + error.message);
return {
level: currentLevel,
error: error.message
};
}
}
/**
* Tenta recuperação do sistema
* @return {boolean} Se recuperou
*/
function attemptRecovery() {
if (currentLevel === DEGRADATION_CONFIG.LEVELS.NORMAL) {
return true;
}
recoveryAttempts++;
const health = checkHealth();
if (health.level === DEGRADATION_CONFIG.LEVELS.NORMAL) {
// Processa fila offline se houver
_processOfflineQueue();
return true;
}
return false;
}
// ============================================================================
// OFFLINE QUEUE
// ============================================================================
/**
* Processa fila de operações offline
* @return {Object} Resultado do processamento
*/
function processOfflineQueue() {
return _processOfflineQueue();
}
/**
* Obtém tamanho da fila offline
* @return {number} Número de operações pendentes
*/
function getOfflineQueueSize() {
try {
const queueStr = emergencyCache.get('offline_queue');
if (!queueStr) return 0;
const queue = JSON.parse(queueStr);
return Array.isArray(queue) ? queue.length : 0;
} catch (e) {
return 0;
}
}
// ============================================================================
// METRICS
// ============================================================================
/**
* Obtém métricas do sistema de degradação
* @return {Object} Métricas
*/
function getMetrics() {
return {
currentLevel: currentLevel,
failureCount: failureCount,
recoveryAttempts: recoveryAttempts,
offlineQueueSize: getOfflineQueueSize(),
lastHealthCheck: lastHealthCheck,
stats: { ...metrics }
};
}
/**
* Reseta métricas
*/
function resetMetrics() {
failureCount = 0;
recoveryAttempts = 0;
metrics.degradations = 0;
metrics.recoveries = 0;
metrics.fallbacksUsed = 0;
metrics.operationsBlocked = 0;
}
// ============================================================================
// PRIVATE HELPERS
// ============================================================================
function _isOperationAllowed(type) {
const allowed = DEGRADATION_CONFIG.ALLOWED_OPERATIONS[currentLevel];
return allowed.includes('*') || allowed.includes(type);
}
function _getTimeout() {
return DEGRADATION_CONFIG.TIMEOUTS[currentLevel] || DEGRADATION_CONFIG.TIMEOUTS.NORMAL;
}
function _executeWithTimeout(operation, timeout) {
// GAS não suporta timeout real, mas podemos usar para logging
const start = Date.now();
const result = operation();
const duration = Date.now() - start;
if (duration > timeout) {
Logger.log(`[GracefulDegradation] Operação excedeu timeout: ${duration}ms > ${timeout}ms`);
}
return { success: true, data: result, duration: duration };
}
function _updateEmergencyCache(key, data) {
try {
const cacheKey = 'emergency_' + key;
emergencyCache.put(cacheKey, JSON.stringify({
data: data,
timestamp: Date.now()
}), DEGRADATION_CONFIG.EMERGENCY_CACHE_TTL);
} catch (e) {
// Silently fail
}
}
function _getFromEmergencyCache(key) {
try {
const cacheKey = 'emergency_' + key;
const cached = emergencyCache.get(cacheKey);
if (cached) {
const parsed = JSON.parse(cached);
return parsed.data;
}
} catch (e) {
// Silently fail
}
return null;
}
function _queueOfflineOperation(type, entityType, data) {
try {
const queueStr = emergencyCache.get('offline_queue') || '[]';
const queue = JSON.parse(queueStr);
queue.push({
id: 'op_' + Date.now(),
type: type,
entityType: entityType,
data: data,
timestamp: Date.now()
});
// Limita tamanho da fila
while (queue.length > 100) {
queue.shift();
}
emergencyCache.put('offline_queue', JSON.stringify(queue), 86400); // 24h
} catch (e) {
Logger.log('[GracefulDegradation] Erro ao enfileirar operação: ' + e.message);
}
}
function _processOfflineQueue() {
const results = { processed: 0, failed: 0, remaining: 0 };
try {
const queueStr = emergencyCache.get('offline_queue');
if (!queueStr) return results;
const queue = JSON.parse(queueStr);
const remaining = [];
for (const op of queue) {
try {
// Tenta processar operação
// Aqui você integraria com o DataService real
Logger.log(`[GracefulDegradation] Processando operação offline: ${op.type} ${op.entityType}`);
results.processed++;
} catch (e) {
remaining.push(op);
results.failed++;
}
}
results.remaining = remaining.length;
if (remaining.length > 0) {
emergencyCache.put('offline_queue', JSON.stringify(remaining), 86400);
} else {
emergencyCache.remove('offline_queue');
}
} catch (e) {
Logger.log('[GracefulDegradation] Erro ao processar fila: ' + e.message);
}
return results;
}
function _evaluateDegradation(error) {
const errorMsg = error.message || '';
// Erros que indicam problemas graves
if (errorMsg.includes('Service invoked too many times') ||
errorMsg.includes('Rate limit') ||
errorMsg.includes('Quota exceeded')) {
setLevel(DEGRADATION_CONFIG.LEVELS.EMERGENCY, 'Quota/Rate limit exceeded');
} else if (errorMsg.includes('timeout') || errorMsg.includes('Timeout')) {
if (failureCount >= 3) {
setLevel(DEGRADATION_CONFIG.LEVELS.DEGRADED, 'Multiple timeouts');
}
} else if (failureCount >= 5) {
setLevel(DEGRADATION_CONFIG.LEVELS.DEGRADED, 'High failure count');
}
}
function _considerRecovery() {
if (currentLevel !== DEGRADATION_CONFIG.LEVELS.NORMAL && failureCount === 0) {
// Sucesso após falhas - considera recuperação gradual
if (currentLevel === DEGRADATION_CONFIG.LEVELS.DEGRADED) {
setLevel(DEGRADATION_CONFIG.LEVELS.NORMAL, 'Recovered from degraded state');
} else if (currentLevel === DEGRADATION_CONFIG.LEVELS.EMERGENCY) {
setLevel(DEGRADATION_CONFIG.LEVELS.DEGRADED, 'Partial recovery');
}
}
// Reset failure count após sucesso
failureCount = Math.max(0, failureCount - 1);
}
function _isMoreDegraded(newLevel, oldLevel) {
const order = [
DEGRADATION_CONFIG.LEVELS.NORMAL,
DEGRADATION_CONFIG.LEVELS.DEGRADED,
DEGRADATION_CONFIG.LEVELS.EMERGENCY,
DEGRADATION_CONFIG.LEVELS.OFFLINE
];
return order.indexOf(newLevel) > order.indexOf(oldLevel);
}
function _logLevelChange(oldLevel, newLevel, reason) {
Logger.log(`[GracefulDegradation] Level changed: ${oldLevel} → ${newLevel} (${reason})`);
try {
if (typeof getLogger === 'function') {
getLogger().warn('Degradation level changed', {
from: oldLevel,
to: newLevel,
reason: reason
});
}
} catch (e) {
// Silently fail
}
}
function _createBlockedResponse(type) {
return {
success: false,
blocked: true,
message: `Operação '${type}' não permitida no nível ${currentLevel}`,
level: currentLevel
};
}
function _checkSpreadsheetHealth() {
try {
// Usa timeout para evitar travamento
const startTime = Date.now();
const timeout = 5000; // 5 segundos
const ss = SpreadsheetApp.getActiveSpreadsheet();
if (!ss) return { healthy: false, error: 'No spreadsheet' };
// Verifica se não excedeu timeout
if (Date.now() - startTime > timeout) {
return { healthy: false, error: 'Timeout' };
}
ss.getSheets(); // Testa acesso
return { healthy: true };
} catch (e) {
return { healthy: false, error: e.message };
}
}
function _checkCacheHealth() {
try {
const cache = CacheService.getScriptCache();
const testKey = 'health_' + Date.now();
// Timeout implícito de 5s
cache.put(testKey, 'test', 10);
const result = cache.get(testKey) === 'test';
cache.remove(testKey);
return { healthy: result };
} catch (e) {
return { healthy: false, error: e.message };
}
}
function _checkPropertiesHealth() {
try {
const props = PropertiesService.getScriptProperties();
// Testa leitura sem modificar dados reais
const testKey = '_health_check_' + Date.now();
props.setProperty(testKey, 'test');
const result = props.getProperty(testKey) === 'test';
props.deleteProperty(testKey);
return { healthy: result };
} catch (e) {
return { healthy: false, error: e.message };
}
}
// ============================================================================
// PUBLIC API
// ============================================================================
return {
// Core
getCurrentLevel: getCurrentLevel,
setLevel: setLevel,
execute: execute,
// Wrappers
safeRead: safeRead,
safeWrite: safeWrite,
// Health
checkHealth: checkHealth,
attemptRecovery: attemptRecovery,
// Offline Queue
processOfflineQueue: processOfflineQueue,
getOfflineQueueSize: getOfflineQueueSize,
// Metrics
getMetrics: getMetrics,
resetMetrics: resetMetrics,
// Config
LEVELS: DEGRADATION_CONFIG.LEVELS,
PRIORITIES: DEGRADATION_CONFIG.PRIORITIES
};
})();
// ============================================================================
// FUNÇÕES GLOBAIS DE CONVENIÊNCIA
// ============================================================================
/**
* Obtém nível atual de degradação
* @return {string}
*/
function getDegradationLevel() {
return GracefulDegradation.getCurrentLevel();
}
/**
* Verifica se sistema está em modo degradado
* @return {boolean}
*/
function isSystemDegraded() {
return GracefulDegradation.getCurrentLevel() !== DEGRADATION_CONFIG.LEVELS.NORMAL;
}
/**
* Executa health check e ajusta nível
* @return {Object}
*/
function checkSystemDegradation() {
return GracefulDegradation.checkHealth();
}
// ============================================================================
// TESTES
// ============================================================================
<
506C
/div>/**
* Testa o sistema de degradação graciosa
*/
function testGracefulDegradation() {
Logger.log('🛡️ Testando Graceful Degradation...\n');
// Teste 1: Nível inicial
Logger.log('Teste 1: Nível inicial');
Logger.log(' Nível: ' + GracefulDegradation.getCurrentLevel());
// Teste 2: Operação bem-sucedida
Logger.log('\nTeste 2: Operação bem-sucedida');
const result1 = GracefulDegradation.execute({
operation: () => ({ data: 'test' }),
type: 'read',
priority: 2
});
Logger.log(' Resultado: ' + JSON.stringify(result1));
// Teste 3: Operação com fallback
Logger.log('\nTeste 3: Operação com fallback');
const result2 = GracefulDegradation.execute({
operation: () => { throw new Error('Simulated failure'); },
fallback: () => ({ fallback: true }),
type: 'read',
priority: 2
});
Logger.log(' Resultado: ' + JSON.stringify(result2));
// Teste 4: Health check
Logger.log('\nTeste 4: Health check');
const health = GracefulDegradation.checkHealth();
Logger.log(' Health: ' + JSON.stringify(health, null, 2));
// Teste 5: Métricas
Logger.log('\nTeste 5: Métricas');
const metrics = GracefulDegradation.getMetrics();
Logger.log(' Métricas: ' + JSON.stringify(metrics, null, 2));
Logger.log('\n✅ Testes concluídos!');
}