forked from Xoulomon/Stellar-Save
-
Notifications
You must be signed in to change notification settings - Fork 0
398 lines (342 loc) · 14.2 KB
/
Copy pathperformance-benchmarks.yml
File metadata and controls
398 lines (342 loc) · 14.2 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
name: Performance Benchmarking
on:
push:
branches: [main, develop]
pull_request:
branches: [main, develop]
paths-ignore:
- '**.md'
- 'docs/**'
- 'design/**'
schedule:
- cron: '0 2 * * 0' # Weekly on Sunday at 2 AM UTC
env:
CACHE_NAME_PREFIX: perf-bench
RESULTS_DIR: performance-results
jobs:
# ─── Gas Cost Benchmarking ──────────────────────────────────────────────────
gas-benchmarks:
name: Contract Gas Cost Benchmarking
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@stable
with:
components: llvm-tools-preview
- name: Cache Rust dependencies
uses: Swatinem/rust-cache@v2
with:
workspaces: ". -> target"
- name: Install benchmarking tools
run: |
cargo install wasm-opt || true
- name: Run gas cost benchmarks
run: |
mkdir -p ${{ env.RESULTS_DIR }}
cargo test \
--manifest-path contracts/stellar-save/Cargo.toml \
--lib benchmark \
-- --nocapture \
--test-threads=1 2>&1 | tee ${{ env.RESULTS_DIR }}/gas-benchmarks.log
- name: Analyze gas costs
run: |
python3 - <<'EOF'
import json
import re
from datetime import datetime
# Parse benchmark results
benchmark_results = {}
try:
with open("${{ env.RESULTS_DIR }}/gas-benchmarks.log", "r") as f:
content = f.read()
# Extract gas costs from test output
gas_pattern = r"test.*?gas.*?(\d+)"
matches = re.findall(gas_pattern, content, re.IGNORECASE)
if matches:
benchmark_results['gas_costs'] = [int(m) for m in matches]
except Exception as e:
print(f"Error reading benchmarks: {e}")
# Generate report
report = {
'timestamp': datetime.utcnow().isoformat(),
'branch': '${{ github.ref_name }}',
'commit_sha': '${{ github.sha }}',
'results': benchmark_results
}
with open("${{ env.RESULTS_DIR }}/gas-report.json", "w") as f:
json.dump(report, f, indent=2)
print("Gas benchmarking complete")
EOF
- name: Check gas regression thresholds
run: |
python3 - <<'EOF'
import json
# Define thresholds for critical functions
THRESHOLDS = {
'contribution': 2000000, # 2M gas
'auto_advance': 3000000, # 3M gas
'distribute_winnings': 4000000, # 4M gas
'create_group': 1500000, # 1.5M gas
}
results_file = "${{ env.RESULTS_DIR }}/gas-report.json"
try:
with open(results_file, "r") as f:
report = json.load(f)
costs = report.get('results', {}).get('gas_costs', [])
if costs and any(c > max(THRESHOLDS.values()) for c in costs):
print(f"⚠️ WARNING: Some gas costs exceed thresholds!")
exit(1)
else:
print(f"✓ Gas costs within acceptable thresholds")
except Exception as e:
print(f"Error checking thresholds: {e}")
EOF
- name: Upload gas benchmarks
uses: actions/upload-artifact@v4
if: always()
with:
name: gas-benchmarks
path: ${{ env.RESULTS_DIR }}/
# ─── Frontend Performance Benchmarking ──────────────────────────────────────
frontend-performance:
name: Frontend Performance Metrics
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
cache-dependency-path: frontend/package-lock.json
- name: Install dependencies
run: npm ci
working-directory: frontend
- name: Build frontend optimized
run: npm run build
working-directory: frontend
env:
NODE_ENV: production
- name: Create Lighthouse config
run: |
cat > frontend/.lighthouserc-perf.json <<'EOF'
{
"ci": {
"upload": {
"target": "temporary-public-storage"
},
"collect": {
"url": [
"http://localhost:4173",
"http://localhost:4173/groups",
"http://localhost:4173/profile"
],
"numberOfRuns": 3,
"settings": {
"configPath": "frontend/lighthouse-config.js"
}
},
"assert": {
"preset": "lighthouse:recommended",
"assertions": {
"categories:performance": ["error", {"minScore": 0.85}],
"categories:accessibility": ["error", {"minScore": 0.90}],
"categories:best-practices": ["error", {"minScore": 0.85}],
"categories:seo": ["error", {"minScore": 0.90}],
"categories:pwa": ["warn"]
}
}
}
}
EOF
- name: Start frontend preview
run: |
cd frontend
nohup npm run preview -- --host 127.0.0.1 --port 4173 > /tmp/lighthouse-server.log 2>&1 &
echo $! > /tmp/lighthouse-server.pid
sleep 5
- name: Run Lighthouse benchmarks
run: |
mkdir -p ${{ env.RESULTS_DIR }}
cd frontend
npx lhci autorun --config .lighthouserc-perf.json > ../${{ env.RESULTS_DIR }}/lighthouse.log 2>&1 || true
- name: Extract and analyze metrics
run: |
python3 - <<'EOF'
import json
from datetime import datetime
metrics = {
'timestamp': datetime.utcnow().isoformat(),
'branch': '${{ github.ref_name }}',
'lightouse_results': {},
'web_vitals': {}
}
try:
with open("${{ env.RESULTS_DIR }}/lighthouse.log", "r") as f:
content = f.read()
metrics['lighthouse_report'] = content[:500]
except:
pass
with open("${{ env.RESULTS_DIR }}/performance-metrics.json", "w") as f:
json.dump(metrics, f, indent=2)
print("Frontend performance metrics collected")
EOF
- name: Stop frontend preview
run: |
PID=$(cat /tmp/lighthouse-server.pid 2>/dev/null)
kill $PID 2>/dev/null || true
- name: Upload frontend performance results
uses: actions/upload-artifact@v4
if: always()
with:
name: frontend-performance
path: ${{ env.RESULTS_DIR }}/
# ─── Performance Trend Tracking ─────────────────────────────────────────────
performance-trends:
name: Performance Trend Analysis
needs: [gas-benchmarks, frontend-performance]
runs-on: ubuntu-latest
if: always()
steps:
- uses: actions/checkout@v4
- name: Download all performance artifacts
uses: actions/download-artifact@v4
with:
path: artifact-downloads
- name: Analyze performance trends
run: |
mkdir -p ${{ env.RESULTS_DIR }}
python3 - <<'EOF'
import json
import os
from datetime import datetime
from pathlib import Path
artifacts_dir = "artifact-downloads"
trends_data = {
'timestamp': datetime.utcnow().isoformat(),
'branch': '${{ github.ref_name }}',
'build_number': '${{ github.run_number }}',
'commit_sha': '${{ github.sha }}',
'gas_benchmarks': {},
'frontend_metrics': {},
'regression_alerts': []
}
# Collect gas benchmark data
gas_report_path = Path(artifacts_dir) / "gas-benchmarks" / "gas-report.json"
if gas_report_path.exists():
with open(gas_report_path) as f:
trends_data['gas_benchmarks'] = json.load(f)
# Collect frontend performance data
perf_metrics_path = Path(artifacts_dir) / "frontend-performance" / "performance-metrics.json"
if perf_metrics_path.exists():
with open(perf_metrics_path) as f:
trends_data['frontend_metrics'] = json.load(f)
# Define regression detection thresholds
regressions = []
gas_costs = trends_data['gas_benchmarks'].get('results', {}).get('gas_costs', [])
if gas_costs:
avg_gas = sum(gas_costs) / len(gas_costs)
# Flag if average gas is 10% above baseline (2M)
if avg_gas > 2200000:
regressions.append(f"Gas cost regression detected: {avg_gas:.0f} gas")
trends_data['regression_alerts'] = regressions
# Save trends
with open("${{ env.RESULTS_DIR }}/performance-trends.json", "w") as f:
json.dump(trends_data, f, indent=2)
if regressions:
print("⚠️ Performance regressions detected:")
for r in regressions:
print(f" - {r}")
else:
print("✓ No performance regressions detected")
EOF
- name: Generate performance dashboard
run: |
cat > ${{ env.RESULTS_DIR }}/dashboard.html <<'EOF'
<!DOCTYPE html>
<html>
<head>
<title>Performance Dashboard</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }
.container { max-width: 1200px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; }
h1 { color: #333; border-bottom: 2px solid #007bff; padding-bottom: 10px; }
.metric-card { display: inline-block; margin: 10px; padding: 15px; background: #f9f9f9; border-left: 4px solid #007bff; border-radius: 4px; }
.metric-value { font-size: 24px; font-weight: bold; color: #007bff; }
.metric-label { font-size: 12px; color: #666; margin-top: 5px; }
.alert { padding: 10px; margin: 10px 0; background: #fff3cd; border-left: 4px solid #ffc107; border-radius: 4px; }
.success { background: #d4edda; border-left-color: #28a745; }
.error { background: #f8d7da; border-left-color: #dc3545; }
table { width: 100%; border-collapse: collapse; margin-top: 20px; }
th, td { padding: 12px; text-align: left; border-bottom: 1px solid #ddd; }
th { background: #f9f9f9; font-weight: bold; }
</style>
</head>
<body>
<div class="container">
<h1>🎯 Performance Dashboard</h1>
<p>Generated on: <strong id="timestamp"></strong></p>
<h2>Key Metrics</h2>
<div class="metric-card">
<div class="metric-value" id="gas-value">N/A</div>
<div class="metric-label">Avg Gas Cost</div>
</div>
<div class="metric-card">
<div class="metric-value" id="lighthouse-value">N/A</div>
<div class="metric-label">Lighthouse Score</div>
</div>
<h2>Status</h2>
<div id="status-container"></div>
<h2>Recent Data</h2>
<table id="data-table">
<tr>
<th>Metric</th>
<th>Value</th>
<th>Status</th>
</tr>
</table>
</div>
<script>
document.getElementById('timestamp').textContent = new Date().toISOString();
document.getElementById('status-container').innerHTML = '<div class="alert success">✓ Performance monitoring active</div>';
</script>
</body>
</html>
EOF
- name: Upload performance trends
uses: actions/upload-artifact@v4
if: always()
with:
name: performance-dashboard
path: ${{ env.RESULTS_DIR }}/
- name: Comment on PR with performance results
uses: actions/github-script@v7
if: github.event_name == 'pull_request'
with:
script: |
const fs = require('fs');
const path = require('path');
let performanceReport = '## 📊 Performance Benchmarking Results\n\n';
try {
const trendsPath = path.join('${{ env.RESULTS_DIR }}', 'performance-trends.json');
if (fs.existsSync(trendsPath)) {
const trends = JSON.parse(fs.readFileSync(trendsPath, 'utf8'));
if (trends.regression_alerts && trends.regression_alerts.length > 0) {
performanceReport += '⚠️ **Performance Regressions Detected**\n';
trends.regression_alerts.forEach(alert => {
performanceReport += `- ${alert}\n`;
});
} else {
performanceReport += '✅ No performance regressions detected\n';
}
}
} catch (e) {
performanceReport += 'Could not load performance data\n';
}
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: performanceReport
});