-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_web.py
More file actions
300 lines (232 loc) · 11 KB
/
example_web.py
File metadata and controls
300 lines (232 loc) · 11 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
#!/usr/bin/env python3
"""
Web profiler example — Flask app with auto-profiling.
Endpoints:
GET / — HTML page with profiled operations + embedded profiler
GET /api/search?q=... — JSON API (profiler key in X-Profiler-Key header)
GET /_profiler?k=KEY — standalone HTML profiler report
Usage:
pip3 install flask
python3 example_web.py
# Open http://localhost:5000/
"""
import random
import time
import redis
from flask import Flask, Response, g, request, jsonify
from xray import Xray
app = Flask(__name__)
r = redis.Redis(host='redis')
class SearchContext:
pass
# --- Middleware: auto-profile every request ---
@app.before_request
def start_profiler():
# ON/OFF logic example:
# want_xray = isDeveloper() # turn ON for developers, OFF for visitors
# Skip auto-profiling for profiler endpoints and /worker:
# /_profiler* renders reports, /worker initializes its own shared task-id later.
want_xray = False if request.path in ('/_profiler', '/_profiler/json', '/worker') else True
Xray.init(r if want_xray else False) # task_id auto-generated when enabled
g.profiler_wait_iframes = want_xray and request.path == '/threaded'
@app.after_request
def attach_profiler(response):
if request.path == '/worker' or not Xray.task_id():
return response
return Xray.attach_profiler(
response,
endpoint='/_profiler',
wait_iframes=getattr(g, 'profiler_wait_iframes', False),
)
# --- Profiler report endpoint ---
@app.route('/_profiler')
def profiler_view():
task_id = request.args.get('k', '')
if not task_id:
return 'Missing ?k= parameter', 400
html = Xray.html_report(task_id, redis_client=r)
return Response(html, content_type='text/html; charset=utf-8')
@app.route('/_profiler/json')
def profiler_json():
task_id = request.args.get('k', '')
if not task_id:
return jsonify({'error': 'Missing ?k= parameter'}), 400
return jsonify(Xray.json(task_id, redis_client=r))
# --- Simulated operations ---
def sim_db_query(table, where=None):
with Xray.i('DB::query', {'table': table, 'where': where}) as span:
time.sleep(random.uniform(0.01, 0.04))
rows = random.randint(5, 200)
span.data({'rows': rows})
return [{'id': i} for i in range(rows)]
def sim_es_search(index, query):
with Xray.i('ES::search', {'index': index, 'query': query, 'context': SearchContext()}) as span:
time.sleep(random.uniform(0.02, 0.06))
hits = random.randint(0, 500)
span.data({'hits': hits})
return {'hits': hits}
def sim_ai_classify(text):
req = {
'text': text,
'model': 'gpt-4o-mini',
'system_prompt': 'You are a commercial real estate classifier. Analyze the property description and return category, subcategory, confidence score, key features, and suggested tags.',
'temperature': 0.3,
'max_tokens': 512,
}
with Xray.i('AI::classify', {'request': req}) as span:
time.sleep(random.uniform(0.05, 0.15))
resp = {
'category': 'office',
'subcategory': 'Class A Office Space',
'confidence': 0.92,
'tokens': {'prompt': 87, 'completion': 142, 'total': 229},
'features': ['high-rise', 'downtown', 'parking', 'elevator', 'reception', 'conference-rooms'],
'tags': ['premium', 'professional', 'CBD', 'transit-accessible', 'recently-renovated'],
'description': 'Modern Class A office space in the heart of Miami financial district with panoramic views, 24/7 security, and premium amenities including fitness center and rooftop terrace.',
}
span.data({'response': resp})
return resp
def sim_cache_lookup(key):
hit = random.random() > 0.3
if hit:
Xray.info('cache-hit', {'key': key})
else:
Xray.info('cache-miss', {'key': key})
return hit
# --- Routes ---
@app.route('/')
def index():
with Xray.i('page::index'):
Xray.info('request-start', {'ip': request.remote_addr, 'ua': request.user_agent.string[:60]})
sim_cache_lookup('page:index')
listings = sim_db_query('listings', 'state=FL')
results = sim_es_search('listing', 'miami office')
with Xray.i('API::enrich', {'listing_id': 12228396, 'source': 'resites'}):
with Xray.i('API::geocode', {'address': '553 G St, Chula Vista, CA 91910', 'provider': 'google'}) as geo:
time.sleep(random.uniform(0.005, 0.02))
geo.data({'lat': 32.6401, 'lon': -117.0842, 'confidence': 0.98, 'cached': False})
with Xray.i('API::classify', {'property_type': 'Commercial Sale', 'sqft': 5900, 'price': 1250000, 'categories': ['restaurant', 'retail']}) as cls:
time.sleep(random.uniform(0.005, 0.015))
cls.data({'result': 'restaurant', 'confidence': 0.87, 'is_business': True})
classification = sim_ai_classify('Office space in Miami')
with Xray.i('API::slow-sync', {'provider': 'crm', 'batch': 25}) as sync:
time.sleep(1.2)
sync.data({'updated': 23, 'skipped': 2})
Xray.warning('slow-query', {'ms': 320})
Xray.alert('connection-timeout', {'host': 'es-cluster', 'after_ms': 5000})
with Xray.i('render::template'):
time.sleep(random.uniform(0.005, 0.015))
Xray.info('request-done')
task_id = Xray.task_id()
return f'''<!DOCTYPE html>
<html>
<head><title>Xray Web Demo</title></head>
<body style="font-family: -apple-system, sans-serif; padding: 20px 40px; background: #f5f5f5; margin-bottom: 60vh; max-width: 800px; line-height: 1.6">
<h1>📊 Xray — Web Demo</h1>
<p>Welcome! This page is <b>auto-profiled</b>. Every database query, API call, and cache lookup
is tracked and timed. Look at the <b>panel at the bottom</b> of the screen — that's the
execution trace of this very page.</p>
<div style="background:#fff; padding:16px 20px; border-radius:8px; border-left:4px solid #4fc3f7; margin:16px 0">
<b>🔍 What happened on this page:</b>
<ul style="margin:8px 0">
<li>🗄 <b>DB query</b> fetched {len(listings)} listings from Florida</li>
<li>🔎 <b>Elasticsearch</b> found {results['hits']} matching results</li>
<li>🌍 <b>Geocoding + Classification</b> enriched a sample property</li>
<li>🤖 <b>AI classify</b> analyzed "Office space in Miami" with request/response</li>
<li>🐢 <b>Slow sync</b> simulates a long external call (> 1s)</li>
<li>⚠️ A simulated <b>slow query warning</b> and ‼️ <b>timeout alert</b></li>
</ul>
</div>
<p>Each operation shows its <b>duration</b>, <b>memory usage</b>, <b>nested children</b>,
and <b>typed parameters</b> (strings in green, numbers in teal, booleans in blue).
Long values are truncated with a <code>[+]</code> expand button.</p>
<h3>🚀 More to explore</h3>
<ul>
<li>📡 <a href="/api/search?q=miami+office">/api/search?q=miami+office</a> — JSON API
<span style="color:#888">(profiler key in <code>X-Profiler-Key</code> response header)</span></li>
<li>👥 <a href="/threaded">/threaded</a> — multi-worker demo
<span style="color:#888">(two iframe workers share the same profiler task-id)</span></li>
</ul>
<p style="color:#999; font-size:13px; margin-top:24px">
↓ Scroll down or click the red bar to see the profiler panel.
Click <b>open ↗</b> to view the report in a standalone page.
</p>
</body>
</html>'''
@app.route('/threaded')
def threaded():
with Xray.i('page::threaded'):
Xray.info('request-start', {'ip': request.remote_addr})
sim_cache_lookup('page:threaded')
listings = sim_db_query('listings', 'state=NY')
results = sim_es_search('listing', 'boston warehouse')
task_id = Xray.task_id()
return f'''<!DOCTYPE html>
<html>
<head><title>Xray — Multi-Worker</title></head>
<body style="font-family: sans-serif; padding: 20px; background: #f5f5f5; margin-bottom: 60vh">
<h1>📊 Multi-Worker Example</h1>
<p>Two background workers share the same profiler task-id. Panel loads after 4s.</p>
<ul>
<li>DB query returned {len(listings)} rows</li>
<li>ES search returned {results['hits']} hits</li>
</ul>
<h3>Background workers (task-id: {task_id})</h3>
<div style="display:flex;gap:12px">
<iframe src="/worker?task_id={task_id}&name=enricher" style="width:200px;height:30px;border:1px solid #ddd;border-radius:4px"></iframe>
<iframe src="/worker?task_id={task_id}&name=classifier" style="width:200px;height:30px;border:1px solid #ddd;border-radius:4px"></iframe>
</div>
<p><a href="/">← back to single-process</a></p>
</body>
</html>'''
@app.route('/api/search')
def api_search():
q = request.args.get('q', 'commercial real estate')
with Xray.i('api::search', {'query': q}):
sim_cache_lookup(f'search:{q}')
results = sim_es_search('listing', q)
with Xray.i('enrich'):
for i in range(min(3, results['hits'])):
sim_db_query('listing_details', f'id={i}')
if random.random() > 0.5:
classification = sim_ai_classify(q)
else:
classification = None
Xray.warning('slow-upstream', {'latency_ms': random.randint(80, 300)})
return jsonify({
'query': q,
'hits': results['hits'],
'classification': classification,
'profiler': Xray.task_id(),
})
@app.route('/worker')
def worker_iframe():
"""Simulates a background worker (called via iframe with shared task_id)."""
task_id = request.args.get('task_id', '')
worker_name = request.args.get('name', 'worker')
if not task_id:
return 'Missing task_id', 400
Xray.init(r, task_id, thread_id=worker_name)
with Xray.i(f'{worker_name}::run'):
# Simulate worker doing its own DB + API work
sim_db_query('worker_queue', f'worker={worker_name}')
with Xray.i(f'{worker_name}::process'):
time.sleep(random.uniform(0.3, 0.8))
if worker_name == 'enricher':
with Xray.i('Geo::batch_geocode', {'count': 25}) as span:
time.sleep(random.uniform(0.2, 0.5))
span.data({'resolved': 23, 'failed': 2})
Xray.info('enricher-checkpoint', {'processed': 25})
elif worker_name == 'classifier':
sim_ai_classify('Warehouse with loading dock in Boston industrial district near I-93')
sim_es_search('listing', 'similar:warehouse:boston')
Xray.warning('model-fallback', {'primary': 'gpt-4o', 'fallback': 'gpt-4o-mini', 'reason': 'rate-limited'})
Xray.info(f'{worker_name}::done')
Xray.finish()
return f'<html><body style="font:11px monospace;color:#888">✓ {worker_name} done</body></html>'
if __name__ == '__main__':
print('Xray Web Demo')
print(' http://localhost:5000/')
print(' http://localhost:5000/api/search?q=miami+office')
print()
app.run(host='0.0.0.0', port=5000, debug=True)