Skip to content

Commit 897481c

Browse files
authored
feat: sort nodes based on distance and weight (#26)
* feat: sort nodes based on distance and weight * make sorting a pure func * fix
1 parent 0596f99 commit 897481c

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

src/client.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ import { getJWT } from './utils/jwt.js'
1010
import { parseUrl, addHttpPrefix } from './utils/url.js'
1111
import { isBrowserContext } from './utils/runtime.js'
1212

13+
const MAX_NODE_WEIGHT = 100
14+
1315
export class Saturn {
1416
static nodesListKey = 'saturn-nodes'
1517
/**
@@ -369,6 +371,29 @@ export class Saturn {
369371
}
370372
}
371373

374+
_sortNodes (nodes) {
375+
// Determine the maximum distance for normalization
376+
const maxDistance = Math.max(...nodes.map(node => node.distance))
377+
378+
// These weights determine how important each factor is in determining
379+
const distanceImportanceFactor = 0.8
380+
const weightImportanceFactor = 1 - distanceImportanceFactor
381+
382+
return nodes.slice().sort((a, b) => {
383+
const normalizedDistanceA = a.distance / maxDistance
384+
const normalizedDistanceB = b.distance / maxDistance
385+
const normalizedWeightA = a.weight / MAX_NODE_WEIGHT
386+
const normalizedWeightB = b.weight / MAX_NODE_WEIGHT
387+
388+
const metricA =
389+
distanceImportanceFactor * normalizedDistanceA - weightImportanceFactor * normalizedWeightA
390+
const metricB =
391+
distanceImportanceFactor * normalizedDistanceB - weightImportanceFactor * normalizedWeightB
392+
393+
return metricA - metricB
394+
})
395+
}
396+
372397
async _loadNodes (opts) {
373398
let origin = opts.orchURL
374399

@@ -407,6 +432,7 @@ export class Saturn {
407432
}
408433
// we always want to update from the orchestrator regardless.
409434
nodes = await orchNodesListPromise
435+
nodes = this._sortNodes(nodes)
410436
this.nodes = nodes
411437
this.storage?.set(Saturn.nodesListKey, nodes)
412438
}

test/test-utils.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ export function generateNodes (count, originDomain) {
3636
const nodeIp = `node${i}`
3737
const node = {
3838
ip: nodeIp,
39-
weight: i,
39+
weight: 50,
4040
distance: 100,
4141
url: `https://${nodeIp}.${originDomain}`
4242
}

0 commit comments

Comments
 (0)