-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathapp.py
More file actions
1584 lines (1436 loc) · 86.4 KB
/
Copy pathapp.py
File metadata and controls
1584 lines (1436 loc) · 86.4 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
"""
app.py — PerfAI: AI-Powered JMeter Script Generator & Performance Analyser
Run with: streamlit run app.py
"""
import streamlit as st
import os
import json
import tempfile
import xml.etree.ElementTree as ET
from collections import Counter
from pathlib import Path
from datetime import datetime
from dotenv import load_dotenv
load_dotenv()
def _validate_generated_jmx(xml_text: str) -> None:
"""Fail fast if model output is not complete well-formed JMX."""
if not xml_text or not xml_text.startswith("<?xml"):
raise ValueError("Generated output is missing XML declaration.")
if not xml_text.strip().endswith("</jmeterTestPlan>"):
raise ValueError("Generated JMX appears truncated (missing </jmeterTestPlan>).")
ET.fromstring(xml_text)
def _format_percent(value) -> str:
try:
return f"{float(value):.2f}%"
except Exception:
return "n/a"
def _severity_rank(severity: str | None) -> int:
return {"high": 0, "medium": 1, "low": 2}.get((severity or "").lower(), 3)
def _build_report_insights(metrics: dict, analysis: dict) -> dict:
summary = metrics.get("summary", {})
endpoints = metrics.get("endpoints", {})
findings = analysis.get("findings", [])
slowest_endpoint = None
if endpoints:
slowest_endpoint = max(endpoints.items(), key=lambda item: item[1].get("p95_ms", 0))
worst_error_endpoint = None
if endpoints:
worst_error_endpoint = max(endpoints.items(), key=lambda item: item[1].get("error_rate_pct", 0))
bottlenecks = [f for f in findings if f.get("type") == "bottleneck"]
recommendations = [f for f in findings if f.get("type") == "recommendation"]
strengths = [f for f in findings if f.get("type") == "strength"]
warnings = [f for f in findings if f.get("type") == "warning"]
risk_level = "Low"
if summary.get("error_rate_pct", 0) >= 5 or summary.get("p99_ms", 0) >= 3000:
risk_level = "High"
elif summary.get("error_rate_pct", 0) >= 1 or summary.get("p99_ms", 0) >= 1500:
risk_level = "Medium"
root_causes = Counter()
for finding in bottlenecks:
title = str(finding.get("title", "")).lower()
description = str(finding.get("description", "")).lower()
text = f"{title} {description}"
if any(term in text for term in ["database", "db", "sql", "query"]):
root_causes["Database pressure"] += 1
if any(term in text for term in ["connection pool", "pool"]):
root_causes["Connection pool saturation"] += 1
if any(term in text for term in ["auth", "token", "jwt"]):
root_causes["Authentication flow"] += 1
if any(term in text for term in ["n+1", "n1", "multiple calls"]):
root_causes["Chatty backend / N+1 access"] += 1
if any(term in text for term in ["cache"]):
root_causes["Cache inefficiency"] += 1
if not root_causes and bottlenecks:
root_causes["Application or dependency bottleneck"] += len(bottlenecks)
key_observations = []
if summary:
key_observations.append(
f"{summary.get('total_requests', 0):,} requests completed at {summary.get('throughput_rps', 0)} req/s with {_format_percent(summary.get('error_rate_pct', 0))} errors."
)
key_observations.append(
f"Latency distribution: avg {summary.get('avg_ms', 'n/a')} ms, p95 {summary.get('p95_ms', 'n/a')} ms, p99 {summary.get('p99_ms', 'n/a')} ms."
)
if slowest_endpoint:
key_observations.append(
f"Slowest endpoint by p95 is {slowest_endpoint[0]} at {slowest_endpoint[1].get('p95_ms', 'n/a')} ms."
)
if worst_error_endpoint:
key_observations.append(
f"Highest error rate is {worst_error_endpoint[0]} at {_format_percent(worst_error_endpoint[1].get('error_rate_pct', 0))}."
)
top_findings = sorted(findings, key=lambda f: _severity_rank(f.get("severity")))
return {
"risk_level": risk_level,
"slowest_endpoint": slowest_endpoint,
"worst_error_endpoint": worst_error_endpoint,
"bottlenecks": bottlenecks,
"recommendations": recommendations,
"strengths": strengths,
"warnings": warnings,
"root_causes": root_causes,
"key_observations": key_observations,
"top_findings": top_findings,
}
# ── Page config (must be first Streamlit call) ─────────────────────────────────
st.set_page_config(
page_title="PerfAI",
page_icon="⚡",
layout="wide",
initial_sidebar_state="expanded",
)
# ── Custom CSS ─────────────────────────────────────────────────────────────────
st.markdown("""
<style>
/* ══ PERFAI — PURPLE THEME ══════════════════════════════════════════════ */
/* Global font override — clean Inter-style system font.
Exclude Material Icons / Symbols spans so their ligature names don't leak as text. */
html, body, [class*="css"], .stApp, .stMarkdown, p, div, label,
.stTextInput, .stTextArea, .stSelectbox, .stRadio, .stSlider {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif !important;
}
/* Preserve Material Icons font on icon spans (Streamlit renders icons via these). */
span[class*="material"], i[class*="material"],
span[data-testid*="Icon"], [data-testid*="Icon"] span,
.material-icons, .material-icons-outlined, .material-symbols-rounded,
.material-symbols-outlined, .material-symbols-sharp {
font-family: "Material Symbols Rounded", "Material Symbols Outlined",
"Material Icons", "Material Icons Outlined" !important;
font-feature-settings: "liga" !important;
}
/* Tone down Streamlit's default bold headings */
h1, h2, h3 {
font-weight: 700 !important;
color: #1E1B4B !important;
letter-spacing: -0.02em !important;
}
:root {
--p-purple: #7C3AED;
--p-purple-mid: #A78BFA;
--p-purple-lite:#EDE9FE;
--p-dark: #0F172A;
--p-text: #1E293B;
--p-muted: #64748B;
--p-border: #E2E8F0;
--p-surface: #FFFFFF;
--p-bg: #FAF9FF;
--p-green: #059669;
--p-red: #DC2626;
--p-amber: #D97706;
}
/* Background */
.stApp {
background: linear-gradient(160deg, #FAF9FF 0%, #F5F3FF 50%, #FAFAFF 100%);
}
.block-container { padding-top: 1.2rem; padding-bottom: 2.5rem; }
/* ── Sidebar ── */
.stSidebar > div {
background: linear-gradient(180deg, #1E1B4B 0%, #0F0E2E 100%);
}
/* All sidebar text white */
.stSidebar,
.stSidebar p, .stSidebar span, .stSidebar div,
.stSidebar label, .stSidebar [data-testid="stMarkdownContainer"],
.stSidebar [data-testid="stMarkdownContainer"] p,
.stSidebar .stSelectbox label,
.stSidebar h1, .stSidebar h2, .stSidebar h3 {
color: #FFFFFF !important;
}
.stSidebar [data-testid="stMarkdownContainer"] a { color: #C4B5FD !important; }
/* ── Hero ── */
.hero-shell {
background: linear-gradient(135deg, #FFFFFF 0%, #F5F3FF 60%, #EDE9FE 100%);
border: 1.5px solid #C4B5FD;
border-radius: 24px;
padding: 28px 32px;
box-shadow: 0 4px 24px rgba(124,58,237,0.10), 0 1px 4px rgba(0,0,0,0.04);
margin-bottom: 20px;
}
.hero-kicker {
font-size: 0.75rem; font-weight: 700;
letter-spacing: 0.14em; text-transform: uppercase;
color: var(--p-purple); margin-bottom: 10px;
}
.hero-title {
font-size: 2.2rem; line-height: 1.1; font-weight: 800;
color: var(--p-dark); margin-bottom: 10px;
}
.hero-subtitle { max-width: 820px; color: #475569; line-height: 1.7; font-size: 0.97rem; }
.hero-pills { margin-top: 16px; display: flex; flex-wrap: wrap; gap: 8px; }
.hero-pill {
border-radius: 999px; background: #FFFFFF;
border: 1.5px solid #DDD6FE; padding: 5px 13px;
font-size: 0.82rem; font-weight: 600; color: #5B21B6;
}
/* ── Tabs ── */
.stTabs [data-baseweb="tab-list"] {
gap: 6px; background: #FFFFFF; border-radius: 12px; padding: 4px;
border: 1.5px solid #DDD6FE;
box-shadow: 0 1px 8px rgba(124,58,237,0.08);
}
.stTabs [data-baseweb="tab"] {
padding: 9px 20px; font-weight: 600; border-radius: 8px;
color: var(--p-muted); font-size: 0.9rem;
}
.stTabs [aria-selected="true"] {
background: linear-gradient(135deg, #7C3AED, #A78BFA) !important;
color: #FFFFFF !important;
box-shadow: 0 2px 12px rgba(124,58,237,0.35) !important;
}
/* ── Buttons ── */
.stButton > button {
border-radius: 10px !important;
background: linear-gradient(135deg, #7C3AED, #A78BFA) !important;
color: #FFFFFF !important; font-weight: 700 !important; border: none !important;
padding: 0.55rem 1.4rem !important;
box-shadow: 0 2px 12px rgba(124,58,237,0.28) !important;
transition: all 0.15s ease !important;
}
.stButton > button:hover {
opacity: 0.9 !important;
box-shadow: 0 4px 20px rgba(124,58,237,0.42) !important;
transform: translateY(-1px) !important;
}
.stButton > button[kind="secondary"] {
background: #FFFFFF !important; color: var(--p-text) !important;
border: 1.5px solid #DDD6FE !important;
box-shadow: 0 1px 4px rgba(124,58,237,0.06) !important;
}
/* ── Inputs ── */
.stTextInput input, .stTextArea textarea, .stSelectbox > div > div {
border: 1.5px solid #DDD6FE !important;
border-radius: 9px !important; background: #FFFFFF !important;
color: var(--p-text) !important;
}
.stTextInput input:focus, .stTextArea textarea:focus {
border-color: var(--p-purple) !important;
box-shadow: 0 0 0 3px rgba(124,58,237,0.14) !important;
}
/* ── Dividers ── */
hr { border-color: #DDD6FE !important; }
/* ── Verdict labels ── */
.verdict-pass { color: #059669; font-weight: 700; font-size: 18px; }
.verdict-warning { color: #D97706; font-weight: 700; font-size: 18px; }
.verdict-fail { color: #DC2626; font-weight: 700; font-size: 18px; }
/* ── Finding cards ── */
.finding-card {
border-left: 4px solid; padding: 14px 18px; margin: 10px 0;
border-radius: 0 12px 12px 0;
}
.finding-bottleneck { border-color: #DC2626; background: #FEF2F2; }
.finding-warning { border-color: #D97706; background: #FFFBEB; }
.finding-strength { border-color: #059669; background: #ECFDF5; }
.finding-recommendation{ border-color: #7C3AED; background: #F5F3FF; }
/* ── DataFrames ── */
.stDataFrame, .stTable {
border-radius: 12px !important; overflow: hidden !important;
border: 1.5px solid #DDD6FE !important;
box-shadow: 0 1px 8px rgba(124,58,237,0.07) !important;
}
/* ── Scrollbars ── */
::-webkit-scrollbar { width: 6px; height: 6px; }
::-webkit-scrollbar-track { background: #F5F3FF; }
::-webkit-scrollbar-thumb { background: #C4B5FD; border-radius: 3px; }
::-webkit-scrollbar-thumb:hover { background: #A78BFA; }
/* ── Plotly chart card style ── */
[data-testid="stPlotlyChart"] {
background: #FFFFFF !important;
border: 1.5px solid #DDD6FE !important;
border-radius: 14px !important;
padding: 12px 8px 4px 8px !important;
box-shadow: 0 2px 14px rgba(124,58,237,0.09), 0 1px 3px rgba(0,0,0,0.04) !important;
margin-bottom: 4px !important;
}
/* ── Info/warning boxes ── */
.stAlert { border-radius: 10px !important; }
[data-testid="stInfo"] {
border-color: #A78BFA !important;
background-color: #F5F3FF !important;
}
/* ── Top toolbar — matches page background, no border ── */
header[data-testid="stHeader"] {
background: #FAF9FF !important;
box-shadow: none !important;
border-bottom: none !important;
}
[data-testid="stDecoration"] {
display: none !important;
}
/* Push main content below the toolbar height */
.block-container {
padding-top: 3.5rem !important;
}
/* ── Toolbar dropdown menu — solid opaque background ── */
[data-testid="stMainMenu"] ul,
div[role="menu"],
div[data-baseweb="popover"] > div,
div[data-baseweb="menu"] {
background: #FFFFFF !important;
backdrop-filter: none !important;
opacity: 1 !important;
}
</style>
""", unsafe_allow_html=True)
st.markdown(
"""
<div class="hero-shell">
<div class="hero-kicker">PerfAI — Performance Intelligence Platform</div>
<div class="hero-title">AI-Powered Load Testing<br>& Performance Analysis</div>
<div class="hero-subtitle">
Paste an OpenAPI spec or describe your API in plain English. PerfAI uses Azure OpenAI to generate
a production-ready JMeter plan, run the test, and deliver a detailed report with bottleneck detection,
root cause analysis, and prioritised fix recommendations.
</div>
<div class="hero-pills">
<span class="hero-pill">⚙ Swagger / OpenAPI / GraphQL / gRPC</span>
<span class="hero-pill">🤖 JMeter / Gatling / k6 generation</span>
<span class="hero-pill">📊 .jtl metrics analysis</span>
<span class="hero-pill">🔍 AI bottleneck detection</span>
<span class="hero-pill">📄 PDF performance report</span>
<span class="hero-pill">☁ AWS EC2 & Distributed runs</span>
<span class="hero-pill">📈 InfluxDB / Grafana export</span>
<span class="hero-pill">🔔 Slack / Teams notifications</span>
<span class="hero-pill">🕐 Scheduled recurring tests</span>
</div>
</div>
""",
unsafe_allow_html=True,
)
# ── Sidebar ────────────────────────────────────────────────────────────────────
with st.sidebar:
st.markdown("""
<div style="padding:12px 0 8px 0;">
<div style="font-size:1.5rem;font-weight:900;background:linear-gradient(135deg,#A78BFA,#7C3AED);-webkit-background-clip:text;-webkit-text-fill-color:transparent;">⚡ PerfAI</div>
<div style="font-size:0.78rem;color:#C4B5FD;margin-top:2px;font-weight:500;">AI-Powered Performance Intelligence</div>
</div>
""", unsafe_allow_html=True)
st.divider()
# Credentials are loaded from environment/.env only — never exposed in UI
_cfg_key = bool(os.environ.get("AZURE_OPENAI_API_KEY"))
_cfg_endpoint = bool(os.environ.get("AZURE_OPENAI_ENDPOINT"))
_cfg_deployment = bool(os.environ.get("AZURE_OPENAI_DEPLOYMENT"))
_cfg_ok = _cfg_key and _cfg_endpoint and _cfg_deployment
_status_color = "#059669" if _cfg_ok else "#D97706"
_status_icon = "●" if _cfg_ok else "●"
_status_label = "Connected" if _cfg_ok else "Not configured"
st.markdown(
f"""
<div style="font-size:0.75rem;font-weight:700;color:#C4B5FD;text-transform:uppercase;
letter-spacing:0.12em;margin-bottom:10px;">Azure OpenAI</div>
<div style="background:rgba(255,255,255,0.07);border:1px solid rgba(196,181,253,0.3);
border-radius:10px;padding:12px 14px;">
<div style="display:flex;align-items:center;gap:8px;margin-bottom:8px;">
<span style="color:{_status_color};font-size:1rem;">{_status_icon}</span>
<span style="color:#FFFFFF;font-size:0.88rem;font-weight:600;">{_status_label}</span>
</div>
<div style="font-size:0.78rem;color:#E2E8F0;line-height:1.7;">
<span style="color:{'#4ADE80' if _cfg_key else '#F87171'};">{'✔' if _cfg_key else '✘'}</span>
API Key
<span style="color:{'#4ADE80' if _cfg_endpoint else '#F87171'};">{'✔' if _cfg_endpoint else '✘'}</span>
Endpoint
<span style="color:{'#4ADE80' if _cfg_deployment else '#F87171'};">{'✔' if _cfg_deployment else '✘'}</span>
Deployment
</div>
{"" if _cfg_ok else '<div style="margin-top:8px;font-size:0.76rem;color:#FCD34D;font-weight:600;">Set credentials in .env or environment variables.</div>'}
</div>
""",
unsafe_allow_html=True,
)
st.divider()
st.markdown("""
<div style="font-size:0.75rem;font-weight:700;color:#C4B5FD;text-transform:uppercase;letter-spacing:0.12em;margin-bottom:10px;">About</div>
<div style="font-size:0.85rem;color:#A78BFA;line-height:1.65;">
Built by a performance engineer with 11 years of experience.<br><br>
Azure OpenAI powers:<br>
<span style="color:#A78BFA;">▸</span> Swagger / GraphQL / gRPC parsing<br>
<span style="color:#A78BFA;">▸</span> JMeter / Gatling / k6 generation<br>
<span style="color:#C4B5FD;">▸</span> Results analysis & diagnosis<br>
<span style="color:#C4B5FD;">▸</span> Fix recommendations<br><br>
Also ships:<br>
<span style="color:#A78BFA;">▸</span> Distributed EC2 test runs<br>
<span style="color:#A78BFA;">▸</span> InfluxDB / Grafana export<br>
<span style="color:#C4B5FD;">▸</span> Slack / Teams notifications<br>
<span style="color:#C4B5FD;">▸</span> Scheduled recurring tests<br>
</div>
""", unsafe_allow_html=True)
st.divider()
st.markdown('<div style="font-size:0.8rem;color:#7C6FAA;text-align:center;"><a href="https://github.com/yourusername/perfai" style="color:#A78BFA;text-decoration:none;">GitHub</a> · Built with Azure OpenAI</div>', unsafe_allow_html=True)
# ── Auto-switch to AI Report tab when requested ────────────────────────────────
if st.session_state.pop("goto_ai_report", False):
import streamlit.components.v1 as _stc
_stc.html("""
<script>
(function tryClick(attempt) {
var tabs = window.parent.document.querySelectorAll('[data-baseweb="tab"]');
if (tabs && tabs.length >= 3) {
tabs[2].click();
} else if (attempt < 20) {
setTimeout(function(){ tryClick(attempt + 1); }, 150);
}
})(0);
</script>
""", height=0)
# ── Main tabs ──────────────────────────────────────────────────────────────────
tab1, tab2, tab3, tab4 = st.tabs(["📝 Script Generator", "📊 Run & Analyse", "📄 AI Report", "⚖ Compare Results"])
# ═══════════════════════════════════════════════════════════════════════════════
# TAB 1 — Script Generator
# ═══════════════════════════════════════════════════════════════════════════════
with tab1:
st.markdown("""
<div style="margin-bottom:18px;">
<div style="font-size:1.6rem;font-weight:800;color:#1E1B4B;margin-bottom:6px;">JMeter Script Generator</div>
<div style="font-size:0.95rem;color:#6D28D9;">Generate a production-ready JMeter <code>.jmx</code> script from your API spec or a plain-English description.</div>
</div>
""", unsafe_allow_html=True)
# ── Input method ─────────────────────────────────────────────────────────
input_method = st.radio(
"Input method",
[
"Swagger / OpenAPI URL",
"Upload Swagger file",
"GraphQL (introspection URL)",
"GraphQL (.graphql SDL file)",
"gRPC (.proto file)",
"Describe in plain English",
],
horizontal=True,
)
endpoints_text = ""
if input_method == "Swagger / OpenAPI URL":
col1, col2 = st.columns([3, 1])
with col1:
swagger_url = st.text_input("Swagger / OpenAPI URL", placeholder="https://api.example.com/v3/openapi.json")
with col2:
st.markdown("<br>", unsafe_allow_html=True)
parse_btn = st.button("Parse spec", type="secondary", use_container_width=True)
if parse_btn and swagger_url:
with st.spinner("Fetching and parsing Swagger spec..."):
try:
from src.swagger_parser import parse_swagger, endpoints_to_plain_text
endpoints = parse_swagger(swagger_url)
endpoints_text = endpoints_to_plain_text(endpoints)
st.session_state["endpoints_text"] = endpoints_text
st.success(f"Found {len(endpoints)} endpoints")
with st.expander("Detected endpoints"):
for ep in endpoints:
st.code(f"{ep['method']:6} {ep['path']}")
except Exception as e:
st.error(f"Failed to parse spec: {e}")
elif input_method == "Upload Swagger file":
st.markdown("**Upload your OpenAPI file**")
uploaded = st.file_uploader(
"Upload your openapi.json or openapi.yaml",
type=["json", "yaml", "yml"],
label_visibility="collapsed",
)
if uploaded:
with st.spinner("Parsing..."):
try:
from src.swagger_parser import parse_swagger, endpoints_to_plain_text
import yaml, json as json_lib
content = uploaded.read()
if uploaded.name.endswith((".yaml", ".yml")):
spec = yaml.safe_load(content)
else:
spec = json_lib.loads(content)
endpoints = parse_swagger(spec)
endpoints_text = endpoints_to_plain_text(endpoints)
st.session_state["endpoints_text"] = endpoints_text
st.success(f"Found {len(endpoints)} endpoints")
except Exception as e:
st.error(f"Parse error: {e}")
elif input_method == "GraphQL (introspection URL)":
col1, col2 = st.columns([3, 1])
with col1:
gql_url = st.text_input("GraphQL endpoint URL", placeholder="https://api.example.com/graphql")
with col2:
st.markdown("<br>", unsafe_allow_html=True)
gql_parse_btn = st.button("Introspect schema", type="secondary", use_container_width=True)
if gql_parse_btn and gql_url:
with st.spinner("Running introspection query..."):
try:
from src.graphql_parser import parse_graphql_introspection, graphql_operations_to_plain_text
ops = parse_graphql_introspection(gql_url)
endpoints_text = graphql_operations_to_plain_text(ops)
st.session_state["endpoints_text"] = endpoints_text
st.success(f"Found {len(ops)} operations")
with st.expander("Detected operations"):
for op in ops:
st.code(f"{op['operation_type'].upper():12} {op['name']}")
except Exception as e:
st.error(f"GraphQL introspection failed: {e}")
elif input_method == "GraphQL (.graphql SDL file)":
st.markdown("**Upload your GraphQL SDL file**")
gql_file = st.file_uploader(
"Upload your .graphql SDL schema file",
type=["graphql", "gql"],
label_visibility="collapsed",
)
if gql_file:
with st.spinner("Parsing SDL schema..."):
try:
from src.graphql_parser import parse_graphql_schema, graphql_operations_to_plain_text
schema_text = gql_file.read().decode("utf-8")
ops = parse_graphql_schema(schema_text)
endpoints_text = graphql_operations_to_plain_text(ops)
st.session_state["endpoints_text"] = endpoints_text
st.success(f"Found {len(ops)} operations")
with st.expander("Detected operations"):
for op in ops:
st.code(f"{op['operation_type'].upper():12} {op['name']}")
except Exception as e:
st.error(f"SDL parse error: {e}")
elif input_method == "gRPC (.proto file)":
st.markdown("**Upload your gRPC proto file**")
proto_file = st.file_uploader(
"Upload your .proto file",
type=["proto"],
label_visibility="collapsed",
)
if proto_file:
with st.spinner("Parsing proto schema..."):
try:
from src.swagger_parser import parse_proto, proto_to_plain_text
proto_text = proto_file.read().decode("utf-8")
services = parse_proto(proto_text)
endpoints_text = proto_to_plain_text(services)
st.session_state["endpoints_text"] = endpoints_text
st.success(f"Found {len(services)} RPC methods")
with st.expander("Detected RPC methods"):
for svc in services:
streaming = " [streaming]" if svc.get("client_streaming") or svc.get("server_streaming") else ""
st.code(f"{svc['service']}.{svc['method']}{streaming}")
except Exception as e:
st.error(f"Proto parse error: {e}")
else: # Plain English
endpoints_text = st.text_area(
"Describe your API",
placeholder="""Example:
I have a REST API with these endpoints:
- POST /auth/login — user login with email and password
- GET /users/{id} — get user profile (requires Bearer token)
- GET /products — list all products with pagination
- POST /orders — create a new order (requires auth)
- DELETE /orders/{id} — cancel an order""",
height=180,
)
st.session_state["endpoints_text"] = endpoints_text
# Restore from session state if already parsed
if not endpoints_text:
endpoints_text = st.session_state.get("endpoints_text", "")
# ── Load test config ──────────────────────────────────────────────────────
st.divider()
st.markdown('<div style="font-size:1.1rem;font-weight:700;color:#1E1B4B;margin-bottom:4px;">Load test configuration</div>', unsafe_allow_html=True)
col1, col2, col3, col4 = st.columns(4)
with col1:
virtual_users = st.slider("Virtual users", 10, 500, 100, 10)
with col2:
duration = st.slider("Duration (minutes)", 1, 30, 5)
with col3:
ramp_up = st.slider("Ramp-up (seconds)", 10, 300, 60, 10)
with col4:
think_time = st.slider("Think time (ms)", 0, 3000, 500, 100)
col1, col2, col3, col4 = st.columns(4)
with col1:
base_url = st.text_input("Base URL", placeholder="https://api.example.com")
with col2:
auth_type = st.selectbox("Authentication", ["None", "Bearer Token", "Basic Auth"])
with col3:
protocol = st.selectbox("Protocol", ["HTTPS", "HTTP"])
with col4:
script_format = st.selectbox("Script Format", ["JMeter (.jmx)", "Gatling (.scala)", "k6 (.js)"])
# ── Generate button ───────────────────────────────────────────────────────
st.divider()
_gen_label = {"JMeter (.jmx)": "⚡ Generate JMeter Script", "Gatling (.scala)": "⚡ Generate Gatling Script", "k6 (.js)": "⚡ Generate k6 Script"}.get(script_format, "⚡ Generate Script")
if st.button(_gen_label, type="primary", disabled=not endpoints_text):
if not all([
os.environ.get("AZURE_OPENAI_API_KEY"),
os.environ.get("AZURE_OPENAI_ENDPOINT"),
os.environ.get("AZURE_OPENAI_DEPLOYMENT"),
]):
st.error("Please enter Azure OpenAI key, endpoint, and deployment in the sidebar first.")
else:
config = {
"virtual_users": virtual_users,
"duration_seconds": duration * 60,
"ramp_up_seconds": ramp_up,
"think_time_ms": think_time,
"base_url": base_url or "https://api.example.com",
"auth_type": auth_type.lower().replace(" ", "_"),
}
if script_format == "JMeter (.jmx)":
with st.spinner("Azure OpenAI is writing your JMeter script..."):
try:
from src.script_generator import generate_script
jmx_script = generate_script(endpoints_text, config)
_validate_generated_jmx(jmx_script)
st.session_state["jmx_script"] = jmx_script
st.session_state.pop("gatling_script", None)
st.session_state.pop("k6_script", None)
os.makedirs("output", exist_ok=True)
jmx_path = "output/generated_test.jmx"
with open(jmx_path, "w") as f:
f.write(jmx_script)
st.session_state["jmx_path"] = jmx_path
st.success("JMeter script generated successfully!")
except Exception as e:
st.session_state.pop("jmx_script", None)
st.session_state.pop("jmx_path", None)
st.error(f"Generation failed: {e}")
elif script_format == "Gatling (.scala)":
with st.spinner("Azure OpenAI is writing your Gatling simulation..."):
try:
from src.script_generator import generate_gatling_script
gatling_script = generate_gatling_script(endpoints_text, config)
st.session_state["gatling_script"] = gatling_script
st.session_state.pop("jmx_script", None)
st.session_state.pop("k6_script", None)
os.makedirs("output", exist_ok=True)
with open("output/generated_simulation.scala", "w") as f:
f.write(gatling_script)
st.success("Gatling simulation generated successfully!")
except Exception as e:
st.session_state.pop("gatling_script", None)
st.error(f"Generation failed: {e}")
else: # k6
with st.spinner("Azure OpenAI is writing your k6 script..."):
try:
from src.script_generator import generate_k6_script
k6_script = generate_k6_script(endpoints_text, config)
st.session_state["k6_script"] = k6_script
st.session_state.pop("jmx_script", None)
st.session_state.pop("gatling_script", None)
os.makedirs("output", exist_ok=True)
with open("output/generated_test.js", "w") as f:
f.write(k6_script)
st.success("k6 script generated successfully!")
except Exception as e:
st.session_state.pop("k6_script", None)
st.error(f"Generation failed: {e}")
if "jmx_script" in st.session_state:
with st.expander("View generated JMX script", expanded=True):
st.code(st.session_state["jmx_script"], language="xml")
st.download_button(
"⬇ Download .jmx script",
data=st.session_state["jmx_script"],
file_name="perfai_load_test.jmx",
mime="application/xml",
)
st.info("👉 Head to the **Run & Analyse** tab to execute this script and analyse results.")
if "gatling_script" in st.session_state:
with st.expander("View generated Gatling simulation", expanded=True):
st.code(st.session_state["gatling_script"], language="scala")
st.download_button(
"⬇ Download Gatling simulation (.scala)",
data=st.session_state["gatling_script"],
file_name="PerfAISimulation.scala",
mime="text/plain",
)
if "k6_script" in st.session_state:
with st.expander("View generated k6 script", expanded=True):
st.code(st.session_state["k6_script"], language="javascript")
st.download_button(
"⬇ Download k6 script (.js)",
data=st.session_state["k6_script"],
file_name="perfai_test.js",
mime="text/plain",
)
# ═══════════════════════════════════════════════════════════════════════════════
# TAB 2 — Run & Analyse
# ═══════════════════════════════════════════════════════════════════════════════
with tab2:
st.markdown("""
<div style="margin-bottom:18px;">
<div style="font-size:1.6rem;font-weight:800;color:#1E1B4B;margin-bottom:6px;">Run Test & Analyse Results</div>
<div style="font-size:0.95rem;color:#6D28D9;">Upload an existing <code>.jtl</code> file or run JMeter directly, then analyse with AI.</div>
</div>
""", unsafe_allow_html=True)
run_method = st.radio(
"How would you like to run the test?",
["Upload existing .jtl results", "Run JMeter locally", "Run on AWS EC2", "Distributed (AWS Multi-Agent)"],
horizontal=True,
)
jtl_path = None
# ── Upload .jtl ───────────────────────────────────────────────────────────
if run_method == "Upload existing .jtl results":
col1, col2 = st.columns([2, 1])
with col1:
st.markdown("**Upload JMeter results file**")
jtl_file = st.file_uploader(
"Upload JMeter .jtl results file",
type=["jtl", "csv"],
label_visibility="collapsed",
)
with col2:
st.info("📁 Don't have a .jtl file? Use our sample data to try the analyser.")
if st.button("Use sample data"):
jtl_path = "sample_data/sample_results.jtl"
st.session_state["jtl_path"] = jtl_path
st.success("Sample data loaded!")
if jtl_file:
os.makedirs("output", exist_ok=True)
jtl_path = "output/uploaded_results.jtl"
with open(jtl_path, "wb") as f:
f.write(jtl_file.read())
st.session_state["jtl_path"] = jtl_path
st.success("Results file uploaded!")
# ── Run locally ───────────────────────────────────────────────────────────
elif run_method == "Run JMeter locally":
st.info("Requires JMeter to be installed and on your PATH. Set `JMETER_PATH` env var if needed.")
jmx_path = st.session_state.get("jmx_path", "")
if not jmx_path:
st.warning("Generate a JMX script in the Script Generator tab first, or upload one below.")
st.markdown("**Upload a JMX file**")
jmx_upload = st.file_uploader(
"Upload .jmx file",
type=["jmx"],
label_visibility="collapsed",
)
if jmx_upload:
os.makedirs("output", exist_ok=True)
jmx_path = "output/uploaded.jmx"
with open(jmx_path, "wb") as f:
f.write(jmx_upload.read())
if jmx_path and st.button("▶ Run JMeter", type="primary"):
with st.spinner("Running JMeter... this may take a few minutes"):
try:
from src.jmeter_runner import run_local
jtl_path = run_local(jmx_path)
st.session_state["jtl_path"] = jtl_path
st.success(f"Test complete! Results at: {jtl_path}")
except Exception as e:
st.error(f"JMeter run failed: {e}")
# ── Run on AWS ────────────────────────────────────────────────────────────
else:
st.info("Spins up an EC2 instance, runs the test, downloads results, terminates instance.")
col1, col2, col3 = st.columns(3)
with col1:
aws_region = st.text_input("AWS Region", value="eu-west-1")
with col2:
instance_type = st.selectbox("Instance Type", ["t3.medium", "t3.large", "c5.xlarge"])
with col3:
key_name = st.text_input("EC2 Key Pair Name", placeholder="my-key-pair")
if st.button("☁ Run on AWS", type="primary"):
jmx_path = st.session_state.get("jmx_path")
if not jmx_path:
st.error("Generate or upload a JMX script first.")
else:
with st.spinner("Provisioning EC2, running test, downloading results..."):
try:
from src.jmeter_runner import run_on_aws
jtl_path = run_on_aws(jmx_path, cfg={
"region": aws_region,
"instance_type": instance_type,
"key_name": key_name,
})
st.session_state["jtl_path"] = jtl_path
st.success("AWS run complete! Results downloaded.")
except Exception as e:
st.error(f"AWS run failed: {e}")
# ── Distributed (AWS Multi-Agent) ─────────────────────────────────────────
if run_method == "Distributed (AWS Multi-Agent)":
st.info("Spins up multiple EC2 agent instances plus a controller. Each agent drives a share of the load.")
col1, col2, col3, col4 = st.columns(4)
with col1:
dist_region = st.text_input("AWS Region", value="eu-west-1", key="dist_region")
with col2:
dist_agents = st.number_input("Number of agent nodes", min_value=2, max_value=10, value=2, key="dist_agents")
with col3:
dist_agent_type = st.selectbox("Agent instance type", ["t3.large", "c5.xlarge", "c5.2xlarge"], key="dist_agent_type")
with col4:
dist_key = st.text_input("EC2 Key Pair Name", placeholder="my-key-pair", key="dist_key")
if st.button("☁ Run Distributed", type="primary"):
jmx_path = st.session_state.get("jmx_path")
if not jmx_path:
st.error("Generate or upload a JMX script in the Script Generator tab first.")
else:
with st.spinner(f"Provisioning {dist_agents} agents + controller, running distributed test..."):
try:
from src.jmeter_runner import run_distributed
jtl_path = run_distributed(jmx_path, cfg={
"region": dist_region,
"agent_count": dist_agents,
"agent_type": dist_agent_type,
"key_name": dist_key,
})
st.session_state["jtl_path"] = jtl_path
st.success("Distributed run complete! Results downloaded.")
except Exception as e:
st.error(f"Distributed run failed: {e}")
# ── Parse & Analyse ───────────────────────────────────────────────────────
st.divider()
jtl_path = st.session_state.get("jtl_path")
if jtl_path and os.path.exists(jtl_path):
st.success(f"Results ready: `{jtl_path}`")
if st.button("🤖 Analyse Results with AI", type="primary"):
if not all([
os.environ.get("AZURE_OPENAI_API_KEY"),
os.environ.get("AZURE_OPENAI_ENDPOINT"),
os.environ.get("AZURE_OPENAI_DEPLOYMENT"),
]):
st.error("Please enter Azure OpenAI key, endpoint, and deployment in the sidebar.")
else:
with st.spinner("Parsing results..."):
from src.results_parser import parse_results
metrics = parse_results(jtl_path)
st.session_state["metrics"] = metrics
with st.spinner("Azure OpenAI is analysing your results..."):
from src.ai_analyser import analyse
analysis = analyse(metrics)
st.session_state["analysis"] = analysis
st.markdown("""
<div style="background:linear-gradient(135deg,#F5F3FF,#EDE9FE);
border:1.5px solid #A78BFA;border-radius:14px;
padding:20px 26px;margin-top:14px;
box-shadow:0 3px 16px rgba(124,58,237,0.15);">
<div style="font-size:1.15rem;font-weight:800;color:#4C1D95;margin-bottom:8px;">
✅ Analysis complete!
</div>
<div style="font-size:0.92rem;color:#374151;margin-bottom:16px;">
Your full performance report is ready. Click the button below to go straight to it.
</div>
</div>
""", unsafe_allow_html=True)
if st.button("📄 View AI Report →", type="primary", key="goto_report"):
st.session_state["goto_ai_report"] = True
st.rerun()
# ── Post-analysis actions (shown whenever metrics+analysis exist) ──────────
if st.session_state.get("metrics") and st.session_state.get("analysis"):
st.divider()
st.markdown('<div style="font-size:1.05rem;font-weight:700;color:#1E1B4B;margin-bottom:4px;">Post-Analysis Actions</div>', unsafe_allow_html=True)
# ── Export to InfluxDB ────────────────────────────────────────────────
with st.expander("📈 Export to InfluxDB / Grafana"):
st.markdown('<div style="font-size:0.85rem;color:#5B21B6;margin-bottom:10px;">Push metrics to InfluxDB v2 for live Grafana dashboards.</div>', unsafe_allow_html=True)
col1, col2 = st.columns(2)
with col1:
influx_url = st.text_input("InfluxDB URL", value="http://localhost:8086", key="influx_url")
influx_token = st.text_input("API Token", type="password", key="influx_token")
with col2:
influx_org = st.text_input("Organisation", value="perfai", key="influx_org")
influx_bucket = st.text_input("Bucket", value="perfai", key="influx_bucket")
run_label_i = st.text_input("Run Label", value="perfai_run", key="influx_run_label")
if st.button("📤 Export to InfluxDB", key="export_influx"):
with st.spinner("Writing metrics to InfluxDB..."):
try:
from src.influxdb_writer import write_metrics
write_metrics(
st.session_state["metrics"]["endpoints"],
run_label=run_label_i,
url=influx_url,
token=influx_token,
org=influx_org,
bucket=influx_bucket,
)
st.success("Metrics exported to InfluxDB successfully!")
except Exception as e:
st.error(f"InfluxDB export failed: {e}")
# ── Slack / Teams notifications ───────────────────────────────────────
with st.expander("🔔 Notify via Slack / Teams"):
st.markdown('<div style="font-size:0.85rem;color:#5B21B6;margin-bottom:10px;">Send a test completion summary to Slack or Microsoft Teams.</div>', unsafe_allow_html=True)
notif_platform = st.radio("Platform", ["Slack", "Microsoft Teams"], horizontal=True, key="notif_platform")
webhook_url = st.text_input("Incoming Webhook URL", type="password", key="notif_webhook")
_s = st.session_state["metrics"]["summary"]
default_msg = (
f"Load test complete. "
f"Requests: {_s.get('total_requests',0):,} | "
f"Throughput: {_s.get('throughput_rps',0)} req/s | "
f"Error rate: {_s.get('error_rate_pct',0):.2f}% | "
f"P95: {_s.get('p95_ms',0)} ms"
)
notif_msg = st.text_area("Message", value=default_msg, key="notif_msg")
if st.button("Send Notification", key="send_notif"):
if not webhook_url:
st.error("Enter a webhook URL first.")
else:
with st.spinner("Sending notification..."):
try:
findings = st.session_state["analysis"].get("findings", [])
from src.notifier import notify_slack, notify_teams
if notif_platform == "Slack":
notify_slack(webhook_url, notif_msg, findings)
else:
notify_teams(webhook_url, notif_msg, findings)
st.success(f"{notif_platform} notification sent!")
except Exception as e:
st.error(f"Notification failed: {e}")
# ── Schedule recurring runs ───────────────────────────────────────────
with st.expander("🕐 Schedule Recurring Test Runs"):
st.markdown('<div style="font-size:0.85rem;color:#5B21B6;margin-bottom:10px;">Schedule this test to run automatically on a cron schedule (while the app is running).</div>', unsafe_allow_html=True)
col1, col2, col3 = st.columns(3)
with col1:
sched_id = st.text_input("Job ID", value="nightly-load-test", key="sched_id")
with col2:
sched_cron = st.text_input("Cron expression (5-field)", value="0 2 * * *", key="sched_cron",
help="minute hour day month weekday — e.g. '0 2 * * *' = every night at 02:00")
with col3:
st.markdown("<br>", unsafe_allow_html=True)
if st.button("➕ Add Schedule", key="add_sched"):
jmx_p = st.session_state.get("jmx_path")
if not jmx_p:
st.error("No JMX script in session. Generate one first.")
else:
try:
from src.scheduler import schedule_test
from src.jmeter_runner import run_local
schedule_test(sched_id, sched_cron, run_local, jmx_p)
st.success(f"Scheduled '{sched_id}' with cron: {sched_cron}")
except Exception as e:
st.error(f"Scheduling failed: {e}")
if st.button("📋 View scheduled jobs", key="list_sched"):
try:
from src.scheduler import list_jobs
jobs = list_jobs()
if jobs:
import pandas as pd
st.dataframe(pd.DataFrame(jobs), use_container_width=True, hide_index=True)
else:
st.info("No jobs scheduled.")
except Exception as e: