Spaces:
Running
Running
File size: 7,793 Bytes
f568a4f | 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 | // Data Stream Monitor - Tracks all API request/response status
// Shows which data streams are active, latency, success/failure rates
export interface StreamEntry {
id: string;
endpoint: string;
direction: 'IN' | 'OUT';
status: 'success' | 'error' | 'pending';
timestamp: Date;
latencyMs: number;
bytesSent?: number;
bytesReceived?: number;
errorMessage?: string;
requestBody?: any;
responseBody?: any;
}
export interface StreamStats {
endpoint: string;
successCount: number;
errorCount: number;
avgLatencyMs: number;
lastSuccess: Date | null;
lastError: Date | null;
isHealthy: boolean;
}
export interface DataStreamMonitorState {
streams: StreamEntry[];
stats: Map<string, StreamStats>;
totalRequests: number;
totalErrors: number;
overallHealth: 'healthy' | 'degraded' | 'down';
lastUpdate: Date;
}
type StreamListener = (state: DataStreamMonitorState) => void;
class DataStreamMonitorClass {
private streams: StreamEntry[] = [];
private stats: Map<string, StreamStats> = new Map();
private listeners: Set<StreamListener> = new Set();
private maxEntries = 100;
private healthThresholdMs = 30000; // 30s without success = unhealthy
constructor() {
// Initialize with known endpoints
const knownEndpoints = [
'ingest-master-equation',
'ingest-omega-equation',
'ingest-prism-state',
'ingest-rainbow-bridge',
'ingest-decision-fusion',
'ingest-ftcp-detector',
'ingest-qgita-signal',
'ingest-hnc-detection',
'ingest-eckoushic-cascade',
'ingest-harmonic-6d',
'ingest-unity-event',
'ingest-akashic-attunement',
'ingest-stargate-harmonizer',
'ingest-stargate-network',
'ingest-probability-matrix',
'ingest-risk-manager',
'ingest-performance-tracker',
'ingest-planetary-modulation',
'ingest-integral-aqal',
'ingest-elephant-memory',
'get-user-market-data',
'get-user-balances',
'execute-trade',
'fetch-binance-market-data',
];
knownEndpoints.forEach(ep => {
this.stats.set(ep, {
endpoint: ep,
successCount: 0,
errorCount: 0,
avgLatencyMs: 0,
lastSuccess: null,
lastError: null,
isHealthy: false,
});
});
}
// Record an outgoing request (OUT)
recordRequest(endpoint: string, requestBody?: any): string {
const id = `${endpoint}-${Date.now()}-${crypto.randomUUID()}`;
const entry: StreamEntry = {
id,
endpoint: this.extractEndpoint(endpoint),
direction: 'OUT',
status: 'pending',
timestamp: new Date(),
latencyMs: 0,
bytesSent: requestBody ? JSON.stringify(requestBody).length : 0,
requestBody,
};
this.addEntry(entry);
return id;
}
// Record a response (IN)
recordResponse(id: string, success: boolean, responseBody?: any, errorMessage?: string) {
const entry = this.streams.find(s => s.id === id);
if (entry) {
entry.direction = 'IN';
entry.status = success ? 'success' : 'error';
entry.latencyMs = Date.now() - entry.timestamp.getTime();
entry.bytesReceived = responseBody ? JSON.stringify(responseBody).length : 0;
entry.responseBody = responseBody;
entry.errorMessage = errorMessage;
this.updateStats(entry);
this.notifyListeners();
}
}
// Simplified: record complete request/response cycle
recordStream(endpoint: string, success: boolean, latencyMs: number, requestBody?: any, responseBody?: any, errorMessage?: string) {
const cleanEndpoint = this.extractEndpoint(endpoint);
const entry: StreamEntry = {
id: `${cleanEndpoint}-${Date.now()}`,
endpoint: cleanEndpoint,
direction: success ? 'IN' : 'OUT',
status: success ? 'success' : 'error',
timestamp: new Date(),
latencyMs,
bytesSent: requestBody ? JSON.stringify(requestBody).length : 0,
bytesReceived: responseBody ? JSON.stringify(responseBody).length : 0,
requestBody,
responseBody,
errorMessage,
};
this.addEntry(entry);
this.updateStats(entry);
}
private extractEndpoint(url: string): string {
// Extract function name from full URL
const match = url.match(/functions\/v1\/([^?]+)/);
if (match) return match[1];
// Or just return the last part of the path
const parts = url.split('/');
return parts[parts.length - 1].split('?')[0] || url;
}
private addEntry(entry: StreamEntry) {
this.streams.unshift(entry);
if (this.streams.length > this.maxEntries) {
this.streams = this.streams.slice(0, this.maxEntries);
}
this.notifyListeners();
}
private updateStats(entry: StreamEntry) {
let stat = this.stats.get(entry.endpoint);
if (!stat) {
stat = {
endpoint: entry.endpoint,
successCount: 0,
errorCount: 0,
avgLatencyMs: 0,
lastSuccess: null,
lastError: null,
isHealthy: false,
};
this.stats.set(entry.endpoint, stat);
}
if (entry.status === 'success') {
stat.successCount++;
stat.lastSuccess = entry.timestamp;
// Running average
stat.avgLatencyMs = (stat.avgLatencyMs * (stat.successCount - 1) + entry.latencyMs) / stat.successCount;
} else if (entry.status === 'error') {
stat.errorCount++;
stat.lastError = entry.timestamp;
}
// Check health - healthy if last success within threshold
stat.isHealthy = stat.lastSuccess !== null &&
(Date.now() - stat.lastSuccess.getTime()) < this.healthThresholdMs;
}
subscribe(listener: StreamListener): () => void {
this.listeners.add(listener);
listener(this.getState());
return () => this.listeners.delete(listener);
}
private notifyListeners() {
const state = this.getState();
this.listeners.forEach(l => l(state));
}
getState(): DataStreamMonitorState {
const totalRequests = Array.from(this.stats.values()).reduce((sum, s) => sum + s.successCount + s.errorCount, 0);
const totalErrors = Array.from(this.stats.values()).reduce((sum, s) => sum + s.errorCount, 0);
const healthyCount = Array.from(this.stats.values()).filter(s => s.isHealthy).length;
const totalEndpoints = this.stats.size;
let overallHealth: 'healthy' | 'degraded' | 'down' = 'healthy';
if (healthyCount === 0) overallHealth = 'down';
else if (healthyCount < totalEndpoints * 0.5) overallHealth = 'degraded';
return {
streams: [...this.streams],
stats: new Map(this.stats),
totalRequests,
totalErrors,
overallHealth,
lastUpdate: new Date(),
};
}
getStreamsByEndpoint(endpoint: string): StreamEntry[] {
return this.streams.filter(s => s.endpoint === endpoint);
}
getHealthyEndpoints(): string[] {
return Array.from(this.stats.values())
.filter(s => s.isHealthy)
.map(s => s.endpoint);
}
getUnhealthyEndpoints(): string[] {
return Array.from(this.stats.values())
.filter(s => !s.isHealthy && (s.successCount > 0 || s.errorCount > 0))
.map(s => s.endpoint);
}
clearHistory() {
this.streams = [];
this.stats.forEach(stat => {
stat.successCount = 0;
stat.errorCount = 0;
stat.avgLatencyMs = 0;
stat.lastSuccess = null;
stat.lastError = null;
stat.isHealthy = false;
});
this.notifyListeners();
}
}
export const dataStreamMonitor = new DataStreamMonitorClass();
|