Repository navigation
Expand file tree
/
Copy pathinstance-manager.js
More file actions
410 lines (355 loc) · 12.9 KB
/
Copy pathinstance-manager.js
File metadata and controls
410 lines (355 loc) · 12.9 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
// Instance Manager - handles multiple Spacebar backends
const fs = require('fs');
const path = require('path');
const http = require('http');
const config = require('./config');
class InstanceManager {
constructor(configPath = './instances.json') {
this.configPath = configPath;
this.instances = new Map();
this.routingConfig = {};
this.currentIndex = 0;
this.healthStatus = new Map();
this.loadConfig();
this.startHealthChecks();
}
loadConfig() {
try {
const data = JSON.parse(fs.readFileSync(this.configPath, 'utf8'));
this.instances.clear();
for (const inst of data.instances) {
this.instances.set(inst.id, {
...inst,
lastUsed: null,
requestCount: 0
});
this.healthStatus.set(inst.id, { healthy: true, lastCheck: null, latency: null });
}
this.routingConfig = data.routing || {};
this.selectionConfig = data.selection || {};
console.log(`[InstanceManager] Loaded ${this.instances.size} instance(s)`);
this.listEnabled().forEach(i => console.log(` • ${i.id}: ${i.url}`));
} catch (err) {
console.error('[InstanceManager] Failed to load config:', err.message);
// Fallback to .env configured default
this.instances.set('default', {
id: 'default',
name: 'Default',
url: config.SPACEBAR,
enabled: true,
region: 'default',
features: ['api', 'gateway', 'cdn']
});
}
}
// Reload config without restart
reload() {
this.loadConfig();
return this.list();
}
// Get all instances
list() {
return Array.from(this.instances.values());
}
// Get enabled instances only
listEnabled() {
return this.list().filter(i => i.enabled);
}
// Get instance by ID (including custom instances from cookies)
get(id, req = null) {
// Check predefined instances first
if (this.instances.has(id)) {
return this.instances.get(id);
}
// Check for custom instance from cookie
if (id === 'custom' && req?.headers?.cookie) {
const match = req.headers.cookie.match(/spacebar_custom_instance=([^;]+)/);
if (match) {
try {
const custom = JSON.parse(decodeURIComponent(match[1]));
return { ...custom, id: 'custom' };
} catch {
return null;
}
}
}
return null;
}
// Get default instance
getDefault() {
const fallback = this.routingConfig.fallback || 'default';
return this.get(fallback) || this.listEnabled()[0];
}
// Select instance based on strategy
select(req) {
const enabled = this.listEnabled();
if (enabled.length === 0) return this.getDefault();
if (enabled.length === 1) return enabled[0];
// Check for forced selection via header, cookie, or query param
const forcedId = this.getForcedSelection(req);
if (forcedId) {
const forced = this.get(forcedId, req);
if (forced && forced.enabled) {
return forced;
}
}
// Check for custom instance in cookie (auto-select if present and healthy)
if (req?.headers?.cookie) {
const customMatch = req.headers.cookie.match(/spacebar_custom_instance=([^;]+)/);
if (customMatch) {
try {
const custom = JSON.parse(decodeURIComponent(customMatch[1]));
if (custom.enabled) {
// Verify custom instance is reachable (async check not awaited for performance)
this.checkHealth('custom').catch(() => {});
return { ...custom, id: 'custom' };
}
} catch {
// Invalid custom cookie, fall through
}
}
}
// Apply routing strategy
const strategy = this.routingConfig.strategy || 'round-robin';
switch (strategy) {
case 'round-robin':
return this.roundRobin(enabled);
case 'random':
return enabled[Math.floor(Math.random() * enabled.length)];
case 'least-connections':
return this.leastConnections(enabled);
case 'health-based':
return this.healthBased(enabled);
default:
return enabled[0];
}
}
getForcedSelection(req) {
// Check header
const header = this.selectionConfig.header;
if (header && req.headers[header.toLowerCase()]) {
return req.headers[header.toLowerCase()];
}
// Check query param
const queryParam = this.selectionConfig.queryParam;
if (queryParam && req.url) {
const match = req.url.match(new RegExp(`[?&]${queryParam}=([^&]+)`));
if (match) return match[1];
}
// Check cookie
const cookie = this.selectionConfig.cookie;
if (cookie && req.headers.cookie) {
const match = req.headers.cookie.match(new RegExp(`${cookie}=([^;]+)`));
if (match) return match[1];
}
return null;
}
roundRobin(enabled) {
const instance = enabled[this.currentIndex % enabled.length];
this.currentIndex++;
instance.lastUsed = Date.now();
instance.requestCount++;
return instance;
}
leastConnections(enabled) {
return enabled.reduce((min, inst) =>
inst.requestCount < min.requestCount ? inst : min
);
}
healthBased(enabled) {
// Filter to healthy instances only
const healthy = enabled.filter(i => this.healthStatus.get(i.id)?.healthy);
if (healthy.length === 0) return this.getDefault();
return healthy[0];
}
// Health check
async checkHealth(instanceId, req = null) {
const instance = this.get(instanceId, req);
if (!instance) return false;
const url = new URL(instance.url);
const startTime = Date.now();
return new Promise((resolve) => {
const req = http.get({
hostname: url.hostname,
port: url.port || 80,
path: '/api/v9/ping',
timeout: this.routingConfig.healthCheck?.timeout || 5000
}, (res) => {
const latency = Date.now() - startTime;
const healthy = res.statusCode === 200;
this.healthStatus.set(instanceId, {
healthy,
lastCheck: Date.now(),
latency,
statusCode: res.statusCode
});
resolve(healthy);
});
req.on('error', () => {
this.healthStatus.set(instanceId, {
healthy: false,
lastCheck: Date.now(),
latency: null,
error: true
});
resolve(false);
});
req.on('timeout', () => {
req.destroy();
this.healthStatus.set(instanceId, {
healthy: false,
lastCheck: Date.now(),
latency: null,
timeout: true
});
resolve(false);
});
});
}
// Start periodic health checks
startHealthChecks() {
if (!this.routingConfig.healthCheck?.enabled) return;
const interval = this.routingConfig.healthCheck?.interval || 30000;
setInterval(() => {
for (const [id, instance] of this.instances) {
if (instance.enabled) {
this.checkHealth(id).catch(() => {});
}
}
}, interval);
console.log(`[InstanceManager] Health checks enabled (${interval}ms interval)`);
}
// Get health status for all instances
getHealth() {
const status = {};
for (const [id, health] of this.healthStatus) {
const instance = this.get(id);
status[id] = {
...health,
enabled: instance?.enabled,
url: instance?.url
};
}
return status;
}
// Middleware for instance selection info
middleware() {
return (req, res, next) => {
req.selectInstance = () => this.select(req);
req.getInstance = (id) => this.get(id);
next();
};
}
// Express routes for management
setupRoutes(app) {
// List all instances
app.get('/_instances', (req, res) => {
res.json({
instances: this.list(),
health: this.getHealth(),
routing: this.routingConfig
});
});
// Get specific instance
app.get('/_instances/:id', (req, res) => {
const instance = this.get(req.params.id);
if (!instance) {
return res.status(404).json({ error: 'Instance not found' });
}
res.json({
instance,
health: this.healthStatus.get(req.params.id)
});
});
// Force select instance (sets cookie)
app.post('/_instances/:id/select', (req, res) => {
const id = req.params.id;
// Check predefined instances first
let instance = this.instances.get(id);
// Then check custom
if (!instance && id === 'custom') {
instance = this.get(id, req);
}
if (!instance) {
return res.status(404).json({ error: 'Instance not found' });
}
if (!instance.enabled) {
return res.status(400).json({ error: 'Instance is disabled' });
}
res.cookie(this.selectionConfig.cookie, id, {
maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days
httpOnly: false,
sameSite: 'lax'
});
res.json({
success: true,
selected: id,
instance: instance
});
});
// Reload config
app.post('/_instances/reload', (req, res) => {
const result = this.reload();
res.json({ success: true, instances: result });
});
// Health check all
app.get('/_instances/health', async (req, res) => {
const checks = [];
for (const id of this.instances.keys()) {
checks.push(this.checkHealth(id));
}
await Promise.all(checks);
res.json({ health: this.getHealth() });
});
// Get current selected instance
app.get('/_instances/current', (req, res) => {
const instance = this.select(req);
res.json({
instance,
available: this.listEnabled(),
selection: this.getForcedSelection(req)
});
});
// Set custom instance URL (user-defined)
app.post('/_instances/custom', (req, res) => {
const { url, name } = req.body;
if (!url) {
return res.status(400).json({ error: 'URL is required' });
}
// Validate URL format
try {
new URL(url);
} catch {
return res.status(400).json({ error: 'Invalid URL format' });
}
// Store custom instance in cookie
const customInstance = {
id: 'custom',
name: name || 'Custom Instance',
url: url,
enabled: true,
region: 'custom',
features: ['api', 'gateway', 'cdn']
};
res.cookie('spacebar_custom_instance', JSON.stringify(customInstance), {
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
httpOnly: false,
sameSite: 'lax'
});
// Also select it as current
res.cookie(this.selectionConfig.cookie, 'custom', {
maxAge: 7 * 24 * 60 * 60 * 1000,
httpOnly: false,
sameSite: 'lax'
});
res.json({ success: true, instance: customInstance });
});
// Clear custom instance
app.post('/_instances/custom/clear', (req, res) => {
res.clearCookie('spacebar_custom_instance');
res.clearCookie(this.selectionConfig.cookie);
res.json({ success: true });
});
}
}
module.exports = InstanceManager;