forked from Open-audit-foundation/Open-Audit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
186 lines (167 loc) · 6.97 KB
/
Copy pathserver.ts
File metadata and controls
186 lines (167 loc) · 6.97 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
/**
* ⚠️ DEPRECATION NOTICE ⚠️
*
* This is the LEGACY monolithic server implementation.
*
* KNOWN ISSUES:
* - Under heavy network load, indexing logic starves HTTP/WebSocket server of CPU cycles
* - Dropped WebSocket connections during high transaction velocity
* - No fault isolation: indexer crash kills entire server
* - Cannot scale independently
*
* RECOMMENDED: Use the decoupled microservices architecture instead:
*
* 1. DOCKER COMPOSE (Recommended for Production):
* $ npm run docker:up
* $ npm run docker:logs
*
* 2. PM2 PROCESS MANAGER:
* $ npm run start:pm2
* $ npm run monit:pm2
*
* 3. MANUAL (Development):
* Terminal 1: $ redis-server
* Terminal 2: $ npm run dev:decoupled
* Terminal 3: $ npm run worker:indexer
*
* See: MICROSERVICES_ARCHITECTURE.md for complete documentation
* See: .env.microservices.example for configuration
*
* ---
*
* Custom Next.js server with an attached WebSocket server.
* Broadcasts newly translated Soroban events to all connected clients.
* Bloated event data (>2KB) is automatically offloaded to IPFS before broadcast.
*
* Run with: npx ts-node --project tsconfig.server.json server.ts
* (or via the `dev:ws` npm script)
*/
import { createServer, IncomingMessage } from "http";
import { parse } from "url";
import next from "next";
import { WebSocketServer, WebSocket } from "ws";
import { MOCK_RAW_EVENTS } from "./lib/mock-data";
import { translateEvent } from "./lib/translator/registry";
import { processEventForIpfs } from "./lib/ipfs/offloader";
import { createFileIngestionStateStore, startResilientEventIngestion } from "./lib/stellar/indexer";
import { getNetworkConfig } from "./lib/stellar/client";
import { captureExceptionSync, eventsIngestedTotal, metricsHandler, recordTranslationDuration, startTelemetry } from "./lib/telemetry";
import { startRetentionScheduler } from "./lib/retention/scheduler";
const dev = process.env.NODE_ENV !== "production";
const port = parseInt(process.env.PORT ?? "3000", 10);
const MAX_WS_CONNECTIONS_PER_IP = parseInt(process.env.MAX_WS_CONNECTIONS_PER_IP ?? "5", 10);
const connectionsByIp = new Map<string, number>();
function parseHistoryArchives(): Record<string, string> {
const raw = process.env.STELLAR_HISTORY_ARCHIVES;
if (!raw) {
return {};
}
try {
const parsed = JSON.parse(raw) as Record<string, string>;
return parsed;
} catch (error) {
console.warn("[Indexer] Failed to parse STELLAR_HISTORY_ARCHIVES JSON:", error);
return {};
}
}
function getClientIp(req: IncomingMessage): string {
const forwardedFor = req.headers["x-forwarded-for"];
if (typeof forwardedFor === "string" && forwardedFor.length > 0) {
return forwardedFor.split(",")[0].trim();
}
return req.socket.remoteAddress ?? "unknown";
}
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(async () => {
await startTelemetry();
startRetentionScheduler();
const httpServer = createServer((req, res) => {
res.setHeader(
"Content-Security-Policy",
"default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; connect-src 'self' wss://* https://horizon-testnet.stellar.org https://soroban-testnet.stellar.org https://horizon.stellar.org https://mainnet.stellar.validationcloud.io; img-src 'self' data:; font-src 'self' data:;"
);
const parsedUrl = parse(req.url ?? "/", true);
handle(req, res, parsedUrl);
});
const wss = new WebSocketServer({ server: httpServer, path: "/ws/events" });
wss.on("connection", (socket, request) => {
const clientIp = request ? getClientIp(request) : "unknown";
const activeConnections = (connectionsByIp.get(clientIp) ?? 0) + 1;
if (activeConnections > MAX_WS_CONNECTIONS_PER_IP) {
console.warn(
`[WS] Rejecting connection from ${clientIp}: too many connections (${activeConnections})`
);
socket.close(1008, "Too many connections from this IP");
return;
}
connectionsByIp.set(clientIp, activeConnections);
console.log(`[WS] Client connected from ${clientIp} (${activeConnections} active)`);
socket.on("close", () => {
const remaining = (connectionsByIp.get(clientIp) ?? 1) - 1;
if (remaining <= 0) {
connectionsByIp.delete(clientIp);
} else {
connectionsByIp.set(clientIp, remaining);
}
console.log(`[WS] Client disconnected from ${clientIp} (${Math.max(remaining, 0)} remaining)`);
});
});
/** Broadcast a JSON payload to every connected client. */
function broadcast(data: unknown): void {
const message = JSON.stringify(data);
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
}
// Start the real-time streaming indexer
const stateStore = createFileIngestionStateStore(
process.env.INGESTION_STATE_FILE ?? ".open-audit/ingestion-state.json"
);
const indexer = startResilientEventIngestion({
networkConfig: getNetworkConfig(),
stateStore,
coldStartLookbackLedgers: Number(process.env.INGESTION_COLD_START_LOOKBACK_LEDGERS ?? "100"),
captiveCore: process.env.STELLAR_CORE_BINARY
? {
binaryPath: process.env.STELLAR_CORE_BINARY,
networkPassphrase: getNetworkConfig().networkPassphrase,
historyArchives: parseHistoryArchives(),
startLedger: Number(process.env.INGESTION_START_LEDGER ?? "0"),
transport:
process.env.STELLAR_CORE_TRANSPORT === "tcp"
? {
type: "tcp",
host: process.env.STELLAR_CORE_STREAM_HOST ?? "127.0.0.1",
port: process.env.STELLAR_CORE_STREAM_PORT
? Number(process.env.STELLAR_CORE_STREAM_PORT)
: undefined,
}
: { type: "stdio" },
heartbeatTimeoutMs: Number(process.env.STELLAR_CORE_HEARTBEAT_TIMEOUT_MS ?? "30000"),
restartDelayMs: Number(process.env.STELLAR_CORE_RESTART_DELAY_MS ?? "5000"),
maxRestartAttempts: Number(process.env.STELLAR_CORE_MAX_RESTARTS ?? "2"),
}
: undefined,
onEvent: async (rawEvent) => {
console.log(`[Indexer] New event: ${rawEvent.id} from contract ${rawEvent.contractId}`);
const processed = await processEventForIpfs(rawEvent);
rawEvent.data = processed.data;
rawEvent.topics = processed.topics;
const translated = recordTranslationDuration(rawEvent.contractId, () => translateEvent(rawEvent));
eventsIngestedTotal.labels(rawEvent.contractId, translated.status === "translated" ? "success" : "failed").inc();
broadcast(translated);
},
onError: (err) => {
captureExceptionSync(err, { context: { operation: "resilientStreamingIndexer" } });
console.error("[Indexer] Streaming error:", err);
},
});
// Start the retention pruner cron (no-op if RETENTION_ENABLED=false)
schedulePruner();
httpServer.listen(port, () => {
console.log(`> Ready on http://localhost:${port}`);
});
});