-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
349 lines (297 loc) · 11.1 KB
/
Copy pathindex.js
File metadata and controls
349 lines (297 loc) · 11.1 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
// for node Registration
/*
Copyright (C) 2025 Anish Sarkar
This file is part of Loopr.
Loopr is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Loopr is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Loopr. If not, see <https://www.gnu.org/licenses/>.
*/
import { Client, Databases, Query } from 'node-appwrite';
const MAX_REDISTRIBUTION_ATTEMPTS = parseInt(process.env.MAX_REDISTRIBUTION_ATTEMPTS) || 3;
const LOAD_BALANCE_BATCH_SIZE = parseInt(process.env.LOAD_BALANCE_BATCH_SIZE) || 10;
class LoadBalancer {
constructor(databases) {
this.databases = databases;
this.batchSize = LOAD_BALANCE_BATCH_SIZE;
this.maxRetries = MAX_REDISTRIBUTION_ATTEMPTS;
}
async getActiveNodesWithCounts() {
const activeNodes = await this.databases.listDocuments(
process.env.DATABASE_ID,
process.env.WORKER_NODES_COLLECTION_ID,
[Query.equal('status', 'online')],
100
);
const nodeCounts = [];
for (const node of activeNodes.documents) {
try {
const urls = await this.databases.listDocuments(
process.env.DATABASE_ID,
process.env.URLS_COLLECTION_ID,
[Query.equal('nodeId', node.$id)]
);
nodeCounts.push({
nodeId: node.$id,
count: urls.total,
nodeType: node.nodeType || 'dynamic'
});
} catch (error) {
console.error(`Failed to get URL count for node ${node.$id}:`, error.message);
nodeCounts.push({
nodeId: node.$id,
count: 0,
nodeType: node.nodeType || 'dynamic'
});
}
}
return nodeCounts;
}
async reassignUrls(sourceNodeId, targetNodeId, count) {
const urlsToReassign = await this.databases.listDocuments(
process.env.DATABASE_ID,
process.env.URLS_COLLECTION_ID,
[Query.equal('nodeId', sourceNodeId)],
count
);
if (urlsToReassign.documents.length === 0) return 0;
let successCount = 0;
const batches = [];
for (let i = 0; i < urlsToReassign.documents.length; i += this.batchSize) {
batches.push(urlsToReassign.documents.slice(i, i + this.batchSize));
}
for (const batch of batches) {
try {
await retryOperation(async () => {
await Promise.all(
batch.map(async (url) => {
await this.databases.updateDocument(
process.env.DATABASE_ID,
process.env.URLS_COLLECTION_ID,
url.$id,
{ nodeId: targetNodeId }
);
successCount++;
})
);
}, this.maxRetries);
} catch (error) {
console.error(`Batch reassignment error:`, error.message);
}
}
return successCount;
}
}
class FixedNodeBalancer extends LoadBalancer {
async balance(currentNodeId, nodeCounts) {
const currentNode = nodeCounts.find(node => node.nodeId === currentNodeId);
if (!currentNode) return;
const avgLoad = nodeCounts.reduce((sum, node) => sum + node.count, 0) / nodeCounts.length;
if (currentNode.count < avgLoad * 0.5) {
const maxNode = nodeCounts.reduce((max, node) =>
node.count > max.count ? node : max
);
if (maxNode.nodeId !== currentNodeId && maxNode.count > currentNode.count + 20) {
const toReassign = Math.min(25, Math.floor((maxNode.count - currentNode.count) / 3));
if (toReassign > 0) {
console.log(`Fixed node balancing: moving ${toReassign} URLs from ${maxNode.nodeId} to ${currentNodeId}`);
await this.reassignUrls(maxNode.nodeId, currentNodeId, toReassign);
}
}
}
}
}
class DynamicNodeBalancer extends LoadBalancer {
async balance(currentNodeId, nodeCounts) {
const currentNode = nodeCounts.find(node => node.nodeId === currentNodeId);
if (!currentNode) return;
const maxNode = nodeCounts.reduce((max, node) =>
node.count > max.count ? node : max, { count: -1 }
);
if (maxNode.count > currentNode.count + 10) {
const diff = Math.floor((maxNode.count - currentNode.count) / 2);
const toReassign = Math.min(diff, 50);
if (toReassign > 0) {
console.log(`Dynamic balancing: moving ${toReassign} URLs from ${maxNode.nodeId} to ${currentNodeId}`);
await this.reassignUrls(maxNode.nodeId, currentNodeId, toReassign);
}
}
}
}
// Consolidated load balancing function
async function performLoadBalancing(databases, currentNodeId, strategy = 'dynamic') {
try {
const balancer = strategy === 'fixed' ?
new FixedNodeBalancer(databases) :
new DynamicNodeBalancer(databases);
const activeNodes = await balancer.getActiveNodesWithCounts();
if (activeNodes.length <= 1) {
console.log('Skipping load balancing: only one active node');
return;
}
await balancer.balance(currentNodeId, activeNodes);
} catch (error) {
console.error('Load balancing error:', error.message);
}
}
// Simplified URL assignment utility
async function assignUrlsToNodes(databases, urls, activeNodes) {
if (!urls.length || !activeNodes.length) return;
const assignments = urls.map((url, index) => {
const nodeIndex = index % activeNodes.length;
const targetNode = activeNodes[nodeIndex];
return databases.updateDocument(
process.env.DATABASE_ID,
process.env.URLS_COLLECTION_ID,
url.$id,
{ nodeId: targetNode.$id }
);
});
// Process in batches
const batchSize = LOAD_BALANCE_BATCH_SIZE;
for (let i = 0; i < assignments.length; i += batchSize) {
const batch = assignments.slice(i, i + batchSize);
try {
await Promise.all(batch);
} catch (error) {
console.error(`Assignment batch error:`, error);
}
}
}
async function retryOperation(operation, maxRetries = 3, delay = 1000) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await operation();
} catch (error) {
if (attempt === maxRetries) throw error;
console.warn(`Attempt ${attempt} failed, retrying in ${delay}ms:`, error.message);
await new Promise((resolve) => setTimeout(resolve, delay));
delay *= 2; // Exponential backoff
}
}
}
export default async function ({ res }) {
const client = new Client()
.setEndpoint(process.env.APPWRITE_ENDPOINT)
.setProject(process.env.APPWRITE_PROJECT_ID)
.setKey(process.env.APPWRITE_API_KEY);
const databases = new Databases(client);
// Use NODE_ID if provided, otherwise use dynamic pool
const nodeId =
process.env.NODE_ID ||
(() => {
const NODE_POOL_SIZE = parseInt(process.env.NODE_POOL_SIZE) || 5;
const nodeIndex = Math.floor(Math.random() * NODE_POOL_SIZE) + 1;
return `node-${nodeIndex}`;
})();
const now = new Date().toISOString();
try {
// Try to update existing node
try {
await databases.updateDocument(
process.env.DATABASE_ID,
process.env.WORKER_NODES_COLLECTION_ID,
nodeId,
{
status: 'online',
lastHeartbeat: now,
// Mark if this is a fixed node for different balancing strategy
nodeType: process.env.NODE_ID ? 'fixed' : 'dynamic'
}
);
} catch {
// Node doesn't exist, create it
await databases.createDocument(
process.env.DATABASE_ID,
process.env.WORKER_NODES_COLLECTION_ID,
nodeId,
{
name: `Worker ${nodeId}`,
status: 'online',
lastHeartbeat: now,
urlCount: 0,
region: process.env.WORKER_REGION || 'default',
nodeType: process.env.NODE_ID ? 'fixed' : 'dynamic'
}
);
}
// Assign unassigned URLs first
await assignUnassignedUrls(databases);
// load balancing
await performLoadBalancing(databases, nodeId, process.env.NODE_ID ? 'fixed' : 'dynamic');
// Getting current URL count for load balancing decisions
const urlCount = await databases.listDocuments(
process.env.DATABASE_ID,
process.env.URLS_COLLECTION_ID,
[Query.equal('nodeId', nodeId)]
);
return res.json({
success: true,
nodeId: nodeId,
nodeType: process.env.NODE_ID ? 'fixed' : 'dynamic',
urlCount: urlCount.total,
timestamp: now
});
} catch (error) {
console.error('Node registration error:', error);
return res.json(
{
success: false,
error: error.message
},
500
);
}
}
// Function to assign URLs that don't have a nodeId
async function assignUnassignedUrls(databases) {
try {
console.log('Checking for unassigned URLs...');
// Get URLs with null nodeId that are enabled
const unassignedUrls = await databases.listDocuments(
process.env.DATABASE_ID,
process.env.URLS_COLLECTION_ID,
[
Query.isNull('nodeId'),
Query.equal('isEnabled', true)
],
100
);
if (unassignedUrls.documents.length === 0) {
console.log('No unassigned enabled URLs found');
return;
}
console.log(`Found ${unassignedUrls.documents.length} unassigned enabled URLs`);
// Get active nodes
const activeNodes = await databases.listDocuments(
process.env.DATABASE_ID,
process.env.WORKER_NODES_COLLECTION_ID,
[Query.equal('status', 'online')],
100
);
if (activeNodes.documents.length === 0) {
console.log('No active nodes available for assignment');
return;
}
console.log(`Assigning ${unassignedUrls.documents.length} URLs to ${activeNodes.documents.length} nodes`);
await assignUrlsToNodes(databases, unassignedUrls.documents, activeNodes.documents);
} catch (error) {
console.error('Error assigning unassigned URLs:', error);
// Don't throw - let the main registration continue
}
}
// function hashString(str) {
// let hash = 0;
// for (let i = 0; i < str.length; i++) {
// const char = str.charCodeAt(i);
// hash = ((hash << 5) - hash) + char;
// hash = hash & hash; // Convert to 32bit integer
// }
// return hash;
// }