-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebhook_trigger.py
More file actions
3998 lines (3577 loc) · 186 KB
/
webhook_trigger.py
File metadata and controls
3998 lines (3577 loc) · 186 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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# === webhook_trigger.py (fixed / extended) ===
# Order matters: imports and logger first to keep Pylance happy.
import csv
import json
import requests
import time
import argparse
import sys
import os
import random
import glob
import logging
import yaml
import sqlite3
import hashlib
import shutil
from datetime import datetime, timezone
from concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETED
import heapq
from threading import Lock, Semaphore, Event, Thread
from tqdm import tqdm
from typing import List, Dict, Optional, Tuple, Set
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import email.utils
import smtplib
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import queue
import signal
import traceback
from contextlib import contextmanager
from logging.handlers import RotatingFileHandler
# Webhook rate limiting
from collections import defaultdict
import time
class WebhookRateLimiter:
def __init__(self, max_requests_per_minute=60):
self.max_requests = max_requests_per_minute
self.requests = defaultdict(list)
self.lock = Lock()
def is_allowed(self, client_ip: str) -> bool:
with self.lock:
now = time.time()
minute_ago = now - 60
# Clean old requests
self.requests[client_ip] = [t for t in self.requests[client_ip] if t > minute_ago]
# Check rate limit
if len(self.requests[client_ip]) >= self.max_requests:
return False
# Record this request
self.requests[client_ip].append(now)
return True
def get_reset_time(self, client_ip: str) -> int:
with self.lock:
if not self.requests[client_ip]:
return 0
oldest = min(self.requests[client_ip])
return int(oldest + 60)
# Global rate limiter instance
webhook_rate_limiter = WebhookRateLimiter(
max_requests_per_minute=int(os.getenv('WEBHOOK_RATE_LIMIT', '60'))
)
# ---------- Logging ----------
def setup_logging():
"""Setup enhanced logging with rotation (robust, UTF-8, single-init, flush on exit)."""
import atexit
from logging.handlers import RotatingFileHandler
# Global module-level guard to prevent any possibility of duplicate setup
if globals().get('_logging_initialized'):
return logging.getLogger(__name__)
globals()['_logging_initialized'] = True
# Avoid duplicate handlers if setup_logging() is ever called twice.
root_logger = logging.getLogger()
if getattr(root_logger, "_already_configured", False):
return logging.getLogger(__name__)
# Also check for existing handlers of same type
for handler in root_logger.handlers:
if isinstance(handler, (RotatingFileHandler, logging.StreamHandler)):
return logging.getLogger(__name__)
# Read level early
level_name = os.getenv("LOG_LEVEL", "INFO").upper()
level = getattr(logging, level_name, logging.INFO)
# Ensure directories exist and are writable
log_dir = '/app/data/logs'
try:
os.makedirs(log_dir, exist_ok=True)
except OSError:
# Fallback for local development (non-Docker)
log_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data', 'logs')
os.makedirs(log_dir, exist_ok=True)
log_path = os.path.join(log_dir, 'webhook_trigger.log')
# Formatter: include thread and time
log_formatter = logging.Formatter(
'%(asctime)s - %(levelname)s - [%(threadName)s] - %(name)s - %(message)s'
)
# File handler with rotation - UTF-8, explicit size from env if present
max_mb = int(os.getenv('MAX_LOG_SIZE_MB', '100'))
file_handler = RotatingFileHandler(
log_path,
maxBytes=max_mb * 1024 * 1024,
backupCount=5,
encoding='utf-8', # important for emoji
delay=False
)
file_handler.setFormatter(log_formatter)
file_handler.setLevel(level)
# Console handler to stdout
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(log_formatter)
console_handler.setLevel(level)
# Reset root handlers and apply exactly ours
root_logger.handlers.clear()
root_logger.setLevel(level)
root_logger.addHandler(file_handler)
root_logger.addHandler(console_handler)
# Mark configured to avoid re-adding on imports
root_logger._already_configured = True
# Flush everything on exit (and on SIGTERM/INT via your signal handler)
def _flush_handlers():
for h in list(root_logger.handlers):
try:
h.flush()
except Exception:
pass
atexit.register(_flush_handlers)
lg = logging.getLogger(__name__)
lg.debug("Logging initialized (level=%s, path=%s, max_mb=%d)", level_name, log_path, max_mb)
return lg
logger = setup_logging()
# Webhook-specific logger
webhook_logger = logging.getLogger('webhook')
webhook_logger.setLevel(logging.INFO)
def log_webhook_trigger(endpoint: str, data: Dict, response_code: int, client_addr: str = None):
"""Log webhook trigger events"""
try:
log_entry = {
'timestamp': datetime.now().isoformat(),
'endpoint': endpoint,
'client': client_addr,
'request': data,
'response_code': response_code
}
webhook_logger.info(f"Webhook trigger: {json.dumps(log_entry)}")
except Exception as e:
logger.error(f"Failed to log webhook event: {e}")
# Constants
DEFAULT_DEBOUNCE_DELAY = 3.0
MAX_BACKOFF_SECONDS = 30.0
MAX_HEADER_SIZE = 10000
MAX_HEADER_COUNT = 50
HEARTBEAT_INTERVAL = 300 # 5 minutes
# Global shutdown coordination
SHUTDOWN_EVENT = Event()
def _handle_sigterm(signum, frame):
try:
logger.info("Received signal %s, shutting down gracefully...", signum)
SHUTDOWN_EVENT.set()
except Exception as e:
print(f"Error in signal handler: {e}")
signal.signal(signal.SIGTERM, _handle_sigterm)
signal.signal(signal.SIGINT, _handle_sigterm)
# Keep stdout line-buffered in Docker-ish envs
try:
sys.stdout.reconfigure(line_buffering=True)
except Exception:
pass
# ---------- Small utils ----------
def _to_float(v, default=0.0):
try:
return float(v) if v is not None else default
except (TypeError, ValueError):
return default
SENSITIVE_HEADER_KEYS = {"authorization", "x-api-key", "api-key", "proxy-authorization", "authentication"}
def _deep_merge(dst: dict, src: dict) -> None:
"""Deep merge src dict into dst dict"""
for k, v in (src or {}).items():
if isinstance(v, dict) and isinstance(dst.get(k), dict):
_deep_merge(dst[k], v)
else:
dst[k] = v
# File hash cache to avoid recalculation
_hash_cache = {}
_hash_cache_lock = Lock()
def _calculate_file_hash(file_path: str) -> str:
"""Calculate file hash with caching to avoid redundant calculations"""
if not file_path or not os.path.exists(file_path):
return ""
try:
# Use file path and modification time as cache key
stat = os.stat(file_path)
cache_key = f"{file_path}:{stat.st_mtime}:{stat.st_size}"
with _hash_cache_lock:
if cache_key in _hash_cache:
return _hash_cache[cache_key]
file_size = stat.st_size
if file_size == 0:
hash_result = hashlib.md5().hexdigest()
else:
hash_md5 = hashlib.md5()
# Use adaptive chunk size with reasonable bounds
chunk_size = min(65536, max(4096, file_size // 100))
with open(file_path, "rb") as f:
for chunk in iter(lambda: f.read(chunk_size), b""):
hash_md5.update(chunk)
hash_result = hash_md5.hexdigest()
with _hash_cache_lock:
# Keep cache size reasonable
if len(_hash_cache) > 1000:
# Remove oldest entries (simple cleanup)
keys_to_remove = list(_hash_cache.keys())[:500]
for k in keys_to_remove:
_hash_cache.pop(k, None)
_hash_cache[cache_key] = hash_result
return hash_result
except (IOError, OSError) as e:
logger.error(f"Error calculating hash for {file_path}: {e}")
return ""
except Exception as e:
logger.error(f"Unexpected error calculating hash for {file_path}: {e}")
return ""
def _redact_headers(h: Dict[str, str]) -> Dict[str, str]:
redacted = {}
for k, v in (h or {}).items():
if k.lower() in SENSITIVE_HEADER_KEYS:
redacted[k] = "***REDACTED***"
else:
redacted[k] = v
return redacted
def _resume_marker_path(file_path: str, file_hash: str, config: Dict = None) -> str:
# Priority: resume config > deployment config > env > default
base_dir = (
(config or {}).get('resume', {}).get('marker_path')
or (config or {}).get('deployment', {}).get('report_path')
or os.getenv('RESUME_MARKER_PATH')
or os.getenv('REPORT_PATH')
or '/app/data/reports'
)
os.makedirs(base_dir, exist_ok=True)
base = os.path.basename(file_path).replace('/', '_').replace('\\', '_')
safe_hash = file_hash[:16] if file_hash else 'unknown' # Use first 16 chars of hash
return os.path.join(base_dir, f".resume_{safe_hash}_{base}.json")
def _load_resume_rows(file_path: str, file_hash: str, config: Dict = None) -> int:
try:
p = _resume_marker_path(file_path, file_hash, config)
if not os.path.exists(p):
return 0
with open(p, "r", encoding="utf-8") as f:
data = json.load(f)
# Validate the resume data
stored_hash = data.get("file_hash", "")
if stored_hash and stored_hash != file_hash:
logger.warning(f"Resume marker hash mismatch for {file_path}, clearing marker")
_clear_resume_marker(file_path, file_hash, config)
return 0
skip_rows = int(data.get("skip_rows", 0))
last_checkpoint = data.get("last_checkpoint")
# Check if checkpoint is too old (configurable, default 7 days)
if last_checkpoint:
try:
checkpoint_time = datetime.fromisoformat(last_checkpoint)
max_age_days = int(os.getenv('RESUME_MAX_AGE_DAYS', '7'))
if (datetime.now() - checkpoint_time).days > max_age_days:
logger.warning(f"Resume marker too old ({last_checkpoint}), ignoring")
return 0
except Exception:
pass
logger.info(f"Loaded resume position {skip_rows} for {file_path} (checkpoint: {last_checkpoint})")
return max(0, skip_rows)
except Exception as e:
logger.error(f"Failed to load resume marker: {e}")
return 0
def _save_resume_rows(file_path: str, file_hash: str, skip_rows: int, config: Dict = None) -> None:
try:
p = _resume_marker_path(file_path, file_hash, config)
resume_data = {
"skip_rows": int(max(0, skip_rows)),
"file_path": file_path,
"file_hash": file_hash,
"last_checkpoint": datetime.now().isoformat(),
"total_rows": _count_csv_rows(file_path) if os.path.exists(file_path) else 0
}
with open(p, "w", encoding="utf-8") as f:
json.dump(resume_data, f, indent=2)
except Exception as e:
logger.error(f"Resume marker write failed for {file_path}: {e}")
def _clear_resume_marker(file_path: str, file_hash: str, config: Dict = None) -> None:
try:
p = _resume_marker_path(file_path, file_hash, config)
if os.path.exists(p):
os.remove(p)
except Exception:
pass
def prune_old_reports(report_dir: str, keep: int = 200):
try:
if not report_dir or not os.path.exists(report_dir):
logger.debug(f"Report directory does not exist: {report_dir}")
return
keep = max(1, keep) # Keep at least 1 report
files = sorted(
[os.path.join(report_dir, f) for f in os.listdir(report_dir)
if f.startswith('job_') and f.endswith('.json')],
key=lambda x: os.path.getmtime(x) if os.path.exists(x) else 0,
reverse=True
)
removed_count = 0
for f in files[keep:]:
try:
os.remove(f)
removed_count += 1
except Exception as e:
logger.warning(f"Could not remove old report {f}: {e}")
if removed_count > 0:
logger.debug(f"Pruned {removed_count} old reports from {report_dir}")
except Exception as e:
logger.debug(f"Report pruning skipped: {e}")
# CSV row counting cache to avoid multiple file reads
_row_count_cache = {}
_row_count_cache_lock = Lock()
def _count_csv_rows(file_path: str) -> int:
"""Count non-header rows with caching to avoid redundant file reads"""
if not file_path or not os.path.exists(file_path):
return 0
try:
# Use file path and modification time as cache key
stat = os.stat(file_path)
cache_key = f"{file_path}:{stat.st_mtime}:{stat.st_size}"
with _row_count_cache_lock:
if cache_key in _row_count_cache:
return _row_count_cache[cache_key]
enc = _detect_encoding(file_path)
with open(file_path, 'r', encoding=enc, newline='') as f:
delim = _detect_delimiter(f)
reader = csv.DictReader(f, delimiter=delim)
raw_headers = reader.fieldnames or []
headers = _normalize_headers(raw_headers)
if 'webhook_url' not in headers:
result = 0
else:
name_map = {orig: norm for orig, norm in zip(raw_headers, headers)}
count = 0
for row in reader:
nrow = {name_map.get(k, k or ''): (v or '').strip() for k, v in row.items()}
u = nrow.get('webhook_url')
if u and _is_valid_url(u):
count += 1
result = count
with _row_count_cache_lock:
# Keep cache size reasonable
if len(_row_count_cache) > 100:
# Remove oldest entries
keys_to_remove = list(_row_count_cache.keys())[:50]
for k in keys_to_remove:
_row_count_cache.pop(k, None)
_row_count_cache[cache_key] = result
return result
except Exception:
return 0
def _slack_urgency_for_progress(successful_count: int, processed_count: int) -> str:
"""Pick a Slack urgency based on live success rate."""
if processed_count <= 0:
return "normal"
rate = max(0.0, min(1.0, successful_count / max(1, processed_count))) # Prevent division by zero and bound rate
if rate >= 0.98:
return "low"
if rate >= 0.90:
return "normal"
if rate >= 0.80:
return "high"
return "critical"
def _detect_encoding(csv_path: str) -> str:
"""Detect CSV file encoding"""
for enc in ('utf-8-sig', 'utf-8', 'iso-8859-1', 'cp1252'):
try:
with open(csv_path, 'r', encoding=enc) as f:
f.read(256)
return enc
except UnicodeDecodeError:
continue
return 'utf-8'
def _detect_delimiter(file_obj) -> str:
"""Detect CSV delimiter from file object"""
try:
pos = file_obj.tell()
except Exception:
pos = 0
try:
sample = file_obj.read(4096)
file_obj.seek(pos)
except Exception:
try:
file_obj.seek(pos)
except Exception:
pass
return ',' # Default to comma on any error
try:
dialect = csv.Sniffer().sniff(sample, delimiters=[',',';','\t','|'])
return dialect.delimiter
except Exception:
# heuristic fallback
if sample.count(';') > sample.count(',') and sample.count(';') > sample.count('\t'):
return ';'
if sample.count('\t') > sample.count(','):
return '\t'
return ','
def _normalize_headers(raw_headers):
"""Normalize CSV headers by stripping BOM, trimming, lowercase"""
return [ (h or '').lstrip('\ufeff').strip().lower() for h in (raw_headers or []) ]
from urllib.parse import urlparse
def _is_valid_url(u: str) -> bool:
try:
if not u:
return False
p = urlparse(u.strip())
return p.scheme in ('http', 'https') and bool(p.netloc)
except Exception:
return False
from requests.adapters import HTTPAdapter
# ---- HTTP result classification & execution helpers ----
from requests.exceptions import RequestException
NON_RETRIABLE_STATUS = {400, 401, 403, 404, 405, 410, 413, 415, 422}
def _create_http_session() -> requests.Session:
s = requests.Session()
pool = max(1, int(os.getenv('HTTP_POOL_MAXSIZE', '16') or '16'))
adapter = HTTPAdapter(pool_connections=pool, pool_maxsize=pool, max_retries=0)
s.mount('http://', adapter)
s.mount('https://', adapter)
# Set a sane default User-Agent; allow override via env
s.headers.update({'User-Agent': os.getenv('HTTP_USER_AGENT', 'BulkAPITrigger/1.0')})
return s
import threading
_HTTP_LOCAL = threading.local()
def get_http_session():
"""Get thread-local HTTP session with proper cleanup"""
if not hasattr(_HTTP_LOCAL, 'session') or _HTTP_LOCAL.session is None:
try:
_HTTP_LOCAL.session = _create_http_session()
except Exception as e:
logger.error(f"Failed to create HTTP session: {e}")
# Create a new session without pooling as fallback
_HTTP_LOCAL.session = requests.Session()
return _HTTP_LOCAL.session
def cleanup_http_session():
"""Cleanup thread-local HTTP session"""
if hasattr(_HTTP_LOCAL, 'session') and _HTTP_LOCAL.session:
try:
_HTTP_LOCAL.session.close()
except Exception:
pass
_HTTP_LOCAL.session = None
# =========================
# Database
# =========================
class DatabaseManager:
def __init__(self, db_path='/app/data/webhook_results.db'):
self.db_path = db_path
os.makedirs(os.path.dirname(self.db_path), exist_ok=True)
self._connection_lock = Lock()
self.init_database()
@contextmanager
def get_connection(self):
"""Thread-safe database connection context manager with proper cleanup"""
with self._connection_lock:
conn = None
try:
conn = sqlite3.connect(self.db_path, timeout=30.0, check_same_thread=False)
conn.execute("PRAGMA journal_mode=WAL;")
conn.execute("PRAGMA synchronous=NORMAL;")
# Test connection
conn.execute("SELECT 1")
yield conn
except Exception as e:
logger.error(f"Database connection error: {e}")
if conn:
try:
conn.rollback()
except Exception:
pass
raise
finally:
if conn:
try:
conn.close()
except Exception as e:
logger.error(f"Error closing database connection: {e}")
def is_file_processed(self, file_path: str, file_hash: str) -> bool:
with self.get_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT 1 FROM file_tracking
WHERE file_path = ? AND file_hash = ? AND status = 'completed'
LIMIT 1
''', (file_path, file_hash))
return cursor.fetchone() is not None
def init_database(self):
with self.get_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS webhook_results (
id INTEGER PRIMARY KEY AUTOINCREMENT,
job_id TEXT NOT NULL,
url TEXT NOT NULL,
method TEXT,
status TEXT NOT NULL,
status_code INTEGER,
response_time REAL,
timestamp TEXT NOT NULL,
attempt INTEGER,
error_message TEXT,
response_preview TEXT,
request_size INTEGER,
response_size INTEGER,
headers_sent TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS job_history (
job_id TEXT PRIMARY KEY,
job_name TEXT,
csv_file TEXT,
total_requests INTEGER,
successful_requests INTEGER,
failed_requests INTEGER,
start_time TEXT NOT NULL,
end_time TEXT,
duration_seconds REAL,
config TEXT,
status TEXT DEFAULT 'running',
triggered_by TEXT DEFAULT 'manual',
average_response_time REAL,
error_message TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS scheduled_jobs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
job_name TEXT NOT NULL,
cron_expression TEXT,
csv_file TEXT,
config TEXT,
last_run TEXT,
next_run TEXT,
enabled BOOLEAN DEFAULT 1,
created_at TEXT NOT NULL
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS file_tracking (
id INTEGER PRIMARY KEY AUTOINCREMENT,
file_path TEXT UNIQUE NOT NULL,
file_hash TEXT NOT NULL,
last_processed DATETIME,
status TEXT DEFAULT 'pending',
job_id TEXT,
file_size INTEGER,
rows_count INTEGER,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS system_metrics (
id INTEGER PRIMARY KEY AUTOINCREMENT,
metric_name TEXT NOT NULL,
metric_value REAL NOT NULL,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS webhook_metrics (
id INTEGER PRIMARY KEY AUTOINCREMENT,
endpoint TEXT NOT NULL,
client_ip TEXT,
request_data TEXT,
response_code INTEGER,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)
''')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_webhook_timestamp ON webhook_metrics(timestamp)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_webhook_endpoint ON webhook_metrics(endpoint)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_webhook_job_id ON webhook_results(job_id)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_webhook_timestamp ON webhook_results(timestamp)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_job_status ON job_history(status)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_file_status ON file_tracking(status)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_file_path_hash_status ON file_tracking(file_path, file_hash, status)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_file_hash_status ON file_tracking(file_hash, status)')
conn.commit()
def save_webhook_result(self, job_id: str, result: Dict):
with self.get_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
INSERT INTO webhook_results
(job_id, url, method, status, status_code, response_time, timestamp, attempt,
error_message, response_preview, request_size, response_size, headers_sent)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
job_id,
result.get('url'),
result.get('method'),
result.get('status'),
result.get('status_code'),
result.get('response_time'),
result.get('timestamp'),
result.get('attempt'),
result.get('error_message'),
result.get('response_preview'),
result.get('request_size', 0),
result.get('response_size', 0),
json.dumps(result.get('headers_sent', {}))
))
conn.commit()
def start_job(self, job_id: str, job_name: str, csv_file: str, total_requests: int, config: Dict, triggered_by: str = 'manual'):
with self.get_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
INSERT OR REPLACE INTO job_history
(job_id, job_name, csv_file, total_requests, successful_requests, failed_requests,
start_time, config, status, triggered_by)
VALUES (?, ?, ?, ?, 0, 0, ?, ?, 'running', ?)
''', (job_id, job_name, csv_file, total_requests, datetime.now().isoformat(),
json.dumps(config), triggered_by))
conn.commit()
def finish_job(self, job_id: str, successful: int, failed: int):
with self.get_connection() as conn:
cursor = conn.cursor()
try:
# Calculate average response time
cursor.execute('''
SELECT AVG(response_time)
FROM webhook_results
WHERE job_id = ? AND response_time IS NOT NULL AND response_time > 0
''', (job_id,))
result = cursor.fetchone()
avg_response_time = float(result[0]) if result and result[0] is not None else 0.0
# Calculate duration from start time
cursor.execute('SELECT start_time FROM job_history WHERE job_id = ?', (job_id,))
result = cursor.fetchone()
duration = 0
if result and result[0]:
try:
start_time = datetime.fromisoformat(result[0])
duration = max(0, (datetime.now() - start_time).total_seconds())
except (ValueError, TypeError) as e:
logger.warning(f"Invalid start_time format for job {job_id}: {e}, using 0 duration")
duration = 0
# Update job record
cursor.execute('''
UPDATE job_history
SET successful_requests = ?, failed_requests = ?, end_time = ?,
duration_seconds = ?, status = 'completed', average_response_time = ?
WHERE job_id = ?
''', (successful, failed, datetime.now().isoformat(), duration, avg_response_time, job_id))
conn.commit()
except sqlite3.Error as e:
try:
conn.rollback()
except sqlite3.Error:
pass
logger.error(f"Database error finishing job {job_id}: {e}")
raise
except (ValueError, TypeError) as e:
logger.error(f"Data error finishing job {job_id}: {e}")
raise
except Exception as e:
logger.error(f"Unexpected error finishing job {job_id}: {e}")
raise
def mark_job_failed(self, job_id: str, error_message: str):
"""Mark a job as failed with error message"""
with self.get_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
UPDATE job_history
SET status = 'failed',
end_time = ?,
error_message = ?
WHERE job_id = ?
''', (datetime.now().isoformat(), error_message, job_id))
conn.commit()
def track_file(self, file_path: str, file_hash: str, file_size: int, rows_count: int = 0):
with self.get_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
INSERT OR REPLACE INTO file_tracking
(file_path, file_hash, file_size, rows_count, status)
VALUES (?, ?, ?, ?, 'pending')
''', (file_path, file_hash, file_size, rows_count))
conn.commit()
def is_hash_processed(self, file_hash: str) -> bool:
with self.get_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT 1 FROM file_tracking
WHERE file_hash = ? AND status = 'completed'
LIMIT 1
''', (file_hash,))
row = cursor.fetchone()
return bool(row)
def update_file_status(self, file_path: str, status: str, job_id: str = None):
with self.get_connection() as conn:
cursor = conn.cursor()
cursor.execute('''
UPDATE file_tracking
SET status = ?, job_id = ?, last_processed = CURRENT_TIMESTAMP
WHERE file_path = ?
''', (status, job_id, file_path))
conn.commit()
def get_file_status(self, file_path: str) -> Optional[str]:
with self.get_connection() as conn:
cursor = conn.cursor()
cursor.execute('SELECT status FROM file_tracking WHERE file_path = ?', (file_path,))
row = cursor.fetchone()
return row[0] if row else None
def get_job_stats(self, job_id: str) -> Dict:
with self.get_connection() as conn:
cursor = conn.cursor()
status_stats = {}
try:
cursor.execute('SELECT * FROM job_history WHERE job_id = ?', (job_id,))
job = cursor.fetchone()
except Exception as e:
logger.error(f"Error fetching job {job_id}: {e}")
job = None
cursor.execute('''
SELECT status, COUNT(*), AVG(response_time), MIN(response_time), MAX(response_time)
FROM webhook_results
WHERE job_id = ?
GROUP BY status
''', (job_id,))
for row in cursor.fetchall():
status_stats[row[0]] = {
'count': row[1] or 0,
'avg_response_time': _to_float(row[2], 0.0),
'min_response_time': _to_float(row[3], 0.0),
'max_response_time': _to_float(row[4], 0.0)
}
if not job:
return {
'job_id': job_id,
'job_name': '',
'csv_file': '',
'total_requests': 0,
'successful_requests': 0,
'failed_requests': 0,
'start_time': '',
'end_time': '',
'duration_seconds': 0.0,
'triggered_by': 'manual',
'average_response_time': 0.0,
'status_breakdown': status_stats,
}
# Safely access tuple elements with bounds checking
def safe_get(tup, idx, default=None):
return tup[idx] if tup and len(tup) > idx else default
duration = _to_float(safe_get(job, 8, 0), 0.0)
avg_response_time = _to_float(safe_get(job, 12, 0), 0.0)
return {
'job_id': safe_get(job, 0, job_id),
'job_name': safe_get(job, 1, ''),
'csv_file': safe_get(job, 2, ''),
'total_requests': int(_to_float(safe_get(job, 3, 0), 0.0)),
'successful_requests': int(_to_float(safe_get(job, 4, 0), 0.0)),
'failed_requests': int(_to_float(safe_get(job, 5, 0), 0.0)),
'start_time': safe_get(job, 6, ''),
'end_time': safe_get(job, 7, ''),
'duration_seconds': duration,
'triggered_by': safe_get(job, 11, 'manual'),
'average_response_time': avg_response_time,
'status_breakdown': status_stats
}
def save_metric(self, metric_name: str, metric_value: float):
with self.get_connection() as conn:
cursor = conn.cursor()
cursor.execute('INSERT INTO system_metrics (metric_name, metric_value) VALUES (?, ?)',
(metric_name, metric_value))
conn.commit()
# =========================
# Notifications (Slack & Email)
# =========================
class NotificationManager:
def __init__(self, config: Dict):
self.config = config or {}
self.email_config = config.get('email', {}) or {}
self.slack_config = config.get('slack', {}) or {}
@staticmethod
def send_startup_test_notifications(trigger: "BulkAPITrigger"):
try:
if os.getenv("SEND_TEST_NOTIFICATIONS_ON_STARTUP", "false").lower() != "true":
return
nm = trigger.notification_manager
if nm.slack_config.get('enabled'):
nm.send_slack_notification("✅ Test Slack from Bulk API Trigger (startup)", "low")
if nm.email_config.get('enabled') and nm.email_config.get('recipients'):
nm.send_email_notification(
subject="Test Email from Bulk API Trigger (startup)",
body="<p>This is a startup test notification.</p>",
to_emails=nm.email_config.get('recipients', [])
)
logger.info("Startup test notifications attempted")
except Exception as e:
logger.error(f"Startup test notifications failed: {e}")
def send_email_notification(self, subject: str, body: str, to_emails: List[str]):
if not self.email_config.get('enabled', False):
logger.debug("Email notifications disabled in config; skipping send")
return
# Validate required configuration
required_fields = ['smtp_server', 'username', 'password', 'from_email']
missing_fields = [field for field in required_fields if not self.email_config.get(field)]
if missing_fields:
logger.error(f"Email configuration missing required fields: {missing_fields}")
return
if not to_emails:
logger.warning("No email recipients specified")
return
max_retries = 3
for attempt in range(max_retries):
try:
msg = MIMEMultipart()
msg['From'] = self.email_config.get('from_email', '')
msg['To'] = ', '.join(to_emails)
msg['Subject'] = subject
msg.attach(MIMEText(body, 'html'))
smtp_port = int(self.email_config.get('smtp_port', 587) or 587)
smtp_server = self.email_config.get('smtp_server', 'smtp.gmail.com') or 'smtp.gmail.com'
use_ssl = (smtp_port == 465)
if use_ssl:
server = smtplib.SMTP_SSL(smtp_server, smtp_port)
else:
server = smtplib.SMTP(smtp_server, smtp_port)
server.ehlo()
if smtp_port == 587:
server.starttls()
server.ehlo()
server.login(self.email_config.get('username', ''), self.email_config.get('password', ''))
server.send_message(msg)
server.quit()
logger.info(f"Email notification sent to {to_emails}")
break
except (smtplib.SMTPException, OSError) as e:
logger.error(f"Failed to send email notification (attempt {attempt + 1}): {e}")
if attempt < max_retries - 1:
time.sleep(2 ** attempt)
def send_slack_notification(self, message: str, urgency: str = 'normal'):
if not self.slack_config.get('enabled', False):
logger.debug("Slack notifications disabled in config; skipping send")
return
emoji_map = {'low': '🔵','normal': '🟢','high': '🟡','critical': '🔴'}
payload = {
'text': f"{emoji_map.get(urgency, '🟢')} {message}",
'username': 'Bulk API Trigger Bot',
'icon_emoji': ':robot_face:',
'attachments': [{
'color': 'good' if urgency in ['low', 'normal'] else ('warning' if urgency == 'high' else 'danger'),
'ts': int(time.time())
}]
}
url = self.slack_config.get('webhook_url', '')
if not url:
logger.error("Slack webhook URL not configured")
return
max_attempts = 3
delay = 1.0
for attempt in range(1, max_attempts + 1):
try:
http_session = get_http_session()
resp = http_session.post(url, json=payload, timeout=10)
if resp.status_code == 200:
logger.info("Slack notification sent successfully")
return
logger.error(f"Failed to send Slack notification: HTTP {resp.status_code} (attempt {attempt}/{max_attempts})")
except requests.RequestException as e:
logger.error(f"Slack send exception (attempt {attempt}/{max_attempts}): {e}")
if attempt < max_attempts:
time.sleep(delay)
delay = min(8.0, delay * 2)
def send_job_completion_notification(self, job_stats: Dict):
total = job_stats.get('total_requests') or 0
succ = job_stats.get('successful_requests') or 0
success_rate = (succ / total * 100.0) if total else 0.0
urgency = 'normal' if success_rate >= 95 else ('high' if success_rate >= 80 else 'critical')
if self.slack_config.get('enabled') and self.slack_config.get('notify_on_completion', True):
completion_emoji = "🎉" if success_rate >= 95 else ("⚠️" if success_rate >= 80 else "🚨")
slack_message = (
f"{completion_emoji} *Bulk API Job Completed*\n\n"
f"🏷️ *Job:* {job_stats.get('job_name','')}\n"
f"📁 *File:* {os.path.basename(job_stats.get('csv_file','Multiple files'))}\n"
f"🎯 *Triggered:* {job_stats.get('triggered_by','manual')}\n"
f"📊 *Success Rate:* {success_rate:.2f}%\n"
f"📈 *Requests:* {succ}/{total} successful\n"
f"⏱️ *Duration:* {_to_float(job_stats.get('duration_seconds')):.2f}s\n"
f"⚡ *Avg Response:* {_to_float(job_stats.get('average_response_time')):.3f}s"
)
self.send_slack_notification(slack_message, urgency)
if self.email_config.get('enabled') and self.email_config.get('notify_on_completion', True):
status_word = ("Completed" if succ == total else ("Completed (with failures)" if succ > 0 else "Failed"))
subject = f"Bulk API Job {status_word}: {job_stats.get('job_name','')}"
html_body = f"""
<h2>Job Completion Report</h2>
<table border="1" cellpadding="10" style="border-collapse: collapse;">
<tr><td><strong>Job Name</strong></td><td>{job_stats.get('job_name','')}</td></tr>