-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathoptimized-api.js
More file actions
410 lines (367 loc) · 13.5 KB
/
Copy pathoptimized-api.js
File metadata and controls
410 lines (367 loc) · 13.5 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
/**
* Optimized API Server for Customer Support
* Integrates with Node-RED and adds performance optimizations
*/
const express = require('express');
const bodyParser = require('body-parser');
const axios = require('axios');
const path = require('path');
const fs = require('fs');
// Import optimization modules
const OptimizationManager = require('./optimization-manager');
// Create API server
const app = express();
app.use(bodyParser.json());
app.use(express.static('public'));
// Root route to provide basic information
app.get('/', (req, res) => {
res.send(`
<!DOCTYPE html>
<html>
<head>
<title>Customer Support API</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body { font-family: -apple-system, BlinkMacSystemFont, sans-serif; line-height: 1.6; color: #333; max-width: 800px; margin: 0 auto; padding: 20px; }
h1 { color: #2c3e50; }
.card { background: #f9f9f9; border-radius: 8px; padding: 20px; margin-bottom: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
pre { background: #f1f1f1; padding: 15px; border-radius: 4px; overflow-x: auto; }
a { color: #3498db; text-decoration: none; }
a:hover { text-decoration: underline; }
.endpoint { margin-bottom: 15px; }
.method { display: inline-block; padding: 3px 6px; border-radius: 4px; font-size: 14px; font-weight: bold; margin-right: 10px; }
.post { background: #4CAF50; color: white; }
.get { background: #2196F3; color: white; }
</style>
</head>
<body>
<h1>Customer Support API</h1>
<p>Welcome to the optimized Customer Support API powered by Cloudflare AutoRAG.</p>
<div class="card">
<h2>Available Endpoints</h2>
<div class="endpoint">
<span class="method post">POST</span>
<strong>/api/customer-support</strong>
<p>Send customer support queries and get AI-powered responses with context awareness.</p>
<pre>{
"message": "Your question here",
"email": "customer@example.com",
"name": "Customer Name"
}</pre>
</div>
<div class="endpoint">
<span class="method get">GET</span>
<strong>/api/status</strong>
<p>Check the system status and performance metrics.</p>
</div>
<div class="endpoint">
<span class="method get">GET</span>
<strong>/admin</strong>
<p>Access the performance monitoring dashboard.</p>
</div>
</div>
<div class="card">
<h2>Quick Links</h2>
<p><a href="/admin">Performance Dashboard</a></p>
<p><a href="/api/status">System Status</a></p>
</div>
<div class="card">
<h2>Example Usage</h2>
<pre>fetch('http://localhost:3001/api/customer-support', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
message: "How do I create a new ticket in Checkbox?",
email: "customer@example.com",
name: "Customer Name"
})
})</pre>
</div>
</body>
</html>
`);
});
// Create optimization manager
const optimizationManager = new OptimizationManager({
serverUrl: 'http://localhost:1883',
apiEndpoint: '/customer-support',
preWarmEnabled: true,
debugMode: true,
cacheDir: path.join(__dirname, 'cache'),
maxCacheSize: 2000,
cacheTtl: 24 * 60 * 60 * 1000, // 24 hours
cleanInterval: 60 * 60 * 1000 // 1 hour
});
// Start pre-warming right away
optimizationManager.preWarmCache();
// Main API endpoint - optimized version
app.post('/api/customer-support', async (req, res) => {
try {
// Validate request
const { message, email, name } = req.body;
if (!message) {
return res.status(400).json({
status: 'error',
error: 'Message is required'
});
}
// Process request through optimization manager
const response = await optimizationManager.processRequest({
message,
email: email || 'anonymous@user.com',
name: name || 'Anonymous User'
});
res.json(response);
} catch (error) {
console.error('Error handling customer support request:', error.message);
res.status(500).json({
status: 'error',
error: 'Failed to process request',
message: error.message
});
}
});
// Status/health endpoint
app.get('/api/status', (req, res) => {
res.json({
status: 'ok',
timestamp: new Date().toISOString(),
stats: optimizationManager.getStats()
});
});
// Admin dashboard (simple HTML)
app.get('/admin', (req, res) => {
const dashboardHtml = `
<!DOCTYPE html>
<html>
<head>
<title>Customer Support - Performance Dashboard</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; line-height: 1.6; color: #333; max-width: 1200px; margin: 0 auto; padding: 20px; }
.card { background: white; border-radius: 8px; padding: 20px; margin-bottom: 20px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
h1, h2, h3 { margin-top: 0; }
table { width: 100%; border-collapse: collapse; }
th, td { text-align: left; padding: 8px; border-bottom: 1px solid #ddd; }
th { background-color: #f2f2f2; }
.stat-row { display: flex; flex-wrap: wrap; gap: 20px; margin-bottom: 20px; }
.stat-card { flex: 1; min-width: 200px; background: #f9f9f9; border-radius: 8px; padding: 15px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); }
.stat-value { font-size: 24px; font-weight: bold; margin: 10px 0; }
.stat-label { font-size: 14px; color: #666; }
.success { color: #28a745; }
.warning { color: #ffc107; }
.error { color: #dc3545; }
button { background: #4CAF50; color: white; border: none; padding: 10px 15px; border-radius: 4px; cursor: pointer; font-size: 14px; }
button:hover { background: #388E3C; }
.refresh-btn { background: #2196F3; margin-right: 10px; }
.refresh-btn:hover { background: #0b7dda; }
</style>
</head>
<body>
<div class="card">
<h1>Customer Support Performance Dashboard</h1>
<p>Monitor system performance and optimize response times</p>
<button id="refreshBtn" class="refresh-btn">Refresh Data</button>
<button id="preWarmBtn">Pre-warm Cache</button>
</div>
<div class="stat-row" id="summaryStats">
<!-- Summary stats will be inserted here -->
</div>
<div class="card">
<h2>Request Queue</h2>
<div id="queueStats">Loading...</div>
</div>
<div class="card">
<h2>Cache Performance</h2>
<div id="cacheStats">Loading...</div>
</div>
<div class="card">
<h2>Common Queries</h2>
<div id="commonQueries">Loading...</div>
</div>
<script>
// Load dashboard data
async function loadDashboard() {
try {
const response = await fetch('/api/status');
const data = await response.json();
// Update summary stats
const summaryHTML = \`
<div class="stat-card">
<div class="stat-label">Total Requests</div>
<div class="stat-value">\${data.stats.requestProcessing.totalRequests}</div>
</div>
<div class="stat-card">
<div class="stat-label">Cache Hit Rate</div>
<div class="stat-value \${data.stats.requestProcessing.hitRate > 70 ? 'success' : 'warning'}">\${data.stats.requestProcessing.hitRate.toFixed(1)}%</div>
</div>
<div class="stat-card">
<div class="stat-label">Active Requests</div>
<div class="stat-value">\${data.stats.queue.activeRequests}</div>
</div>
<div class="stat-card">
<div class="stat-label">Queue Length</div>
<div class="stat-value \${data.stats.queue.queueLength > 10 ? 'error' : 'success'}">\${data.stats.queue.queueLength}</div>
</div>
<div class="stat-card">
<div class="stat-label">Cache Size</div>
<div class="stat-value">\${data.stats.cache.valid} / \${data.stats.cache.total}</div>
</div>
<div class="stat-card">
<div class="stat-label">Last Update</div>
<div class="stat-value" style="font-size: 16px">\${new Date().toLocaleTimeString()}</div>
</div>
\`;
document.getElementById('summaryStats').innerHTML = summaryHTML;
// Update queue stats
document.getElementById('queueStats').innerHTML = \`
<table>
<tr>
<th>Metric</th>
<th>Value</th>
</tr>
<tr>
<td>Queue Length</td>
<td>\${data.stats.queue.queueLength}</td>
</tr>
<tr>
<td>Active Requests</td>
<td>\${data.stats.queue.activeRequests}</td>
</tr>
<tr>
<td>Total Managed Requests</td>
<td>\${data.stats.queue.totalRequests}</td>
</tr>
</table>
\`;
// Update cache stats
document.getElementById('cacheStats').innerHTML = \`
<table>
<tr>
<th>Metric</th>
<th>Value</th>
</tr>
<tr>
<td>Total Cache Entries</td>
<td>\${data.stats.cache.total}</td>
</tr>
<tr>
<td>Valid Entries</td>
<td>\${data.stats.cache.valid}</td>
</tr>
<tr>
<td>Expired Entries</td>
<td>\${data.stats.cache.expired}</td>
</tr>
<tr>
<td>Cache Hits</td>
<td>\${data.stats.requestProcessing.cacheHits}</td>
</tr>
<tr>
<td>Cache Misses</td>
<td>\${data.stats.requestProcessing.cacheMisses}</td>
</tr>
<tr>
<td>Hit Rate</td>
<td>\${data.stats.requestProcessing.hitRate.toFixed(1)}%</td>
</tr>
<tr>
<td>Last Cleanup</td>
<td>\${new Date(data.stats.cache.lastCleanup).toLocaleString()}</td>
</tr>
</table>
\`;
// Load common queries
loadCommonQueries();
} catch (error) {
console.error('Error loading dashboard data:', error);
}
}
// Load common queries from file
async function loadCommonQueries() {
try {
const response = await fetch('/common-queries.json');
const queries = await response.json();
if (queries && queries.length > 0) {
let html = '<table><tr><th>#</th><th>Query</th></tr>';
queries.forEach((query, index) => {
html += \`
<tr>
<td>\${index + 1}</td>
<td>\${query}</td>
</tr>
\`;
});
html += '</table>';
document.getElementById('commonQueries').innerHTML = html;
} else {
document.getElementById('commonQueries').innerHTML = '<p>No common queries recorded yet.</p>';
}
} catch (error) {
document.getElementById('commonQueries').innerHTML = '<p>Error loading common queries.</p>';
}
}
// Pre-warm cache
async function preWarmCache() {
try {
document.getElementById('preWarmBtn').disabled = true;
document.getElementById('preWarmBtn').textContent = 'Pre-warming...';
const response = await fetch('/api/pre-warm', { method: 'POST' });
const result = await response.json();
alert(\`Cache pre-warming completed. Warmed \${result.warmed} queries.\`);
} catch (error) {
console.error('Error pre-warming cache:', error);
alert('Error pre-warming cache. Check console for details.');
} finally {
document.getElementById('preWarmBtn').disabled = false;
document.getElementById('preWarmBtn').textContent = 'Pre-warm Cache';
loadDashboard();
}
}
// Event listeners
document.getElementById('refreshBtn').addEventListener('click', loadDashboard);
document.getElementById('preWarmBtn').addEventListener('click', preWarmCache);
// Load dashboard on page load
loadDashboard();
// Refresh every 10 seconds
setInterval(loadDashboard, 10000);
</script>
</body>
</html>
`;
res.send(dashboardHtml);
});
// Serve common-queries.json
app.get('/common-queries.json', (req, res) => {
try {
const filePath = path.join(__dirname, 'common-queries.json');
if (fs.existsSync(filePath)) {
const content = fs.readFileSync(filePath, 'utf8');
res.setHeader('Content-Type', 'application/json');
res.send(content);
} else {
res.json([]);
}
} catch (error) {
console.error('Error reading common queries file:', error);
res.status(500).json({ error: 'Failed to read common queries' });
}
});
// Endpoint to manually trigger pre-warming
app.post('/api/pre-warm', async (req, res) => {
try {
const warmed = await optimizationManager.preWarmCache();
res.json({ success: true, warmed });
} catch (error) {
console.error('Error pre-warming cache:', error);
res.status(500).json({ success: false, error: error.message });
}
});
// Start the server
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log(`Optimized API server running on port ${PORT}`);
console.log(`Performance dashboard available at http://localhost:${PORT}/admin`);
});