Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: sort nodes based on distance and weight #26

Merged
merged 4 commits into from
Oct 26, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions src/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import { getJWT } from './utils/jwt.js'
import { parseUrl, addHttpPrefix } from './utils/url.js'
import { isBrowserContext } from './utils/runtime.js'

const MAX_NODE_WEIGHT = 100

export class Saturn {
static nodesListKey = 'saturn-nodes'
/**
Expand Down Expand Up @@ -369,6 +371,30 @@ export class Saturn {
}
}

_sortNodes (nodes) {
// Determine the maximum distance for normalization
const maxDistance = Math.max(...nodes.map(node => node.distance))

// These weights determine how important each factor is in determining
const distanceImportanceFactor = 0.8
const weightImportanceFactor = 1 - distanceImportanceFactor

nodes.sort((a, b) => {
const normalizedDistanceA = a.distance / maxDistance
const normalizedDistanceB = b.distance / maxDistance
const normalizedWeightA = a.weight / MAX_NODE_WEIGHT
const normalizedWeightB = b.weight / MAX_NODE_WEIGHT

const metricA =
distanceImportanceFactor * normalizedDistanceA - weightImportanceFactor * normalizedWeightA
const metricB =
distanceImportanceFactor * normalizedDistanceB - weightImportanceFactor * normalizedWeightB

return metricA - metricB
})
return nodes
}

async _loadNodes (opts) {
let origin = opts.orchURL

Expand Down Expand Up @@ -407,6 +433,7 @@ export class Saturn {
}
// we always want to update from the orchestrator regardless.
nodes = await orchNodesListPromise
nodes = this._sortNodes(nodes)
this.nodes = nodes
this.storage?.set(Saturn.nodesListKey, nodes)
}
Expand Down
2 changes: 1 addition & 1 deletion test/test-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export function generateNodes (count, originDomain) {
const nodeIp = `node${i}`
const node = {
ip: nodeIp,
weight: i,
weight: 50,
distance: 100,
url: `https://${nodeIp}.${originDomain}`
}
Expand Down